views:

309

answers:

4

How to generate random number from an array? and not from a range.

int n [] = {1,7,3,5,8,10,33,12,18}
+7  A: 
import java.util.Random;

...

Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
Barthelemy
Thank you :-) ...you are brilliant!
Jessy
Note that you should cache the `Random` instance in a field instead of creating a new instance each time you need a random number.
Joey
Just make random static.
Steve Kuo
A: 

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.

kbenson
A: 

definitive random number generator: http://xkcd.com/221/

rhu
That's pretty funny.
Steve Kuo
Lol funny, but totally not useful to solve this problem :)
Alfred
−1. It's getting pretty old around here by now and it's not an answer to the question. If anything, then it should have been a comment.
Joey
A: 

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)]);

My code

public class Numbers {
    private static Random random = new Random();

    public static Integer random(Integer[] n) {
        return n[random.nextInt(n.length)];
    }
}

My Test

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?

Alfred