How to generate random number from an array? and not from a range.
int n [] = {1,7,3,5,8,10,33,12,18}
How to generate random number from an array? and not from a range.
int n [] = {1,7,3,5,8,10,33,12,18}
import java.util.Random;
...
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
In general terms, get a random integer ranging from a minimum of 0 to a maximum of the array length -1, and use that as the array index.
I also tried to unit test Barthelemy's code:
import java.util.Random;
...
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
public class Numbers {
private static Random random = new Random();
public static Integer random(Integer[] n) {
return n[random.nextInt(n.length)];
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.*;
import static org.junit.Assert.*;
public class NumbersTest {
private static Integer[] n = {1,7,3,5,8,10,33,12,18};
public NumbersTest() {
}
@Test(timeout=100L) public void testRandom() {
Integer[] i = new Integer[1000];
for (int j=0;j<1000;j++) {
i[j] = j;
}
List<Integer> copy = new ArrayList<Integer>(Arrays.asList(i));
long start = System.nanoTime();
int k = 0;
while(!copy.isEmpty()) {
copy.remove(Numbers.random(i));
k++;
}
System.out.println(k);
System.out.println(System.nanoTime() - start);
}
}
When I run this test all items are tested? What do you think of this? I guess I could improve test by repeating it?