views:

1715

answers:

3

Hi,

Assume I have an array/vector of numbers like 1,3,7,9 then I need to guess a number from this list randomly. Using Random class in Java it seems like not possible to do this. Could anyone kindly help me to tell a way to do this kind of thing. I have to change the list of numbers used to generate random number. I am trying to implement a strategy to play battleship game automatically as an assignment. Kindly help me to do this ?

Kind Regards,

Tharindu Madushanka

+1  A: 

Put the numbers in an ArrayList and use Collections.shuffle(arrayList);

Charles Ma
Why take O(N) when O(1) will suffice?
Tordek
But in my case I need multiple hits at once. Usually Battleship game played one by one hits, here its changeable at game initialization
Tharindu Madushanka
+8  A: 

If you just want to select one random number only, or want to select multiple random numbers with reinsertion (i.e. allow possibility of selecting the same number multiple times), you can generate a random index:

List<Integer> lst = ....;
int index = new Random().nextInt(lst.size());
Integer randomeValue = lst.get(index);

You can use an array instead as well. This requires O(1) for each selection.

If you need to select multiple distinct random numbers from the list, then using Collections.shuffle() and iterating through the list would be a better solution. This requires O(n) for all the queries.

notnoop
Thank you for your kind replies. it's really helpful
Tharindu Madushanka
If you need multiple random numbers then remember to reuse the same Random instance instead of newing one each time.
Steve Kuo
A: 

I'm with tordek on this one: Doesn't shuffling seem like a fairly heavy-weight way to select a configured number of random numbers from a source vector?

Wouldn't it be faster to just take msaeed's suggestion for how to pick one random number, and repeat it n times? Perhaps assemble your random values as a Set, and keep selecting until your set size is big enough... (don't forget some kind of a check for the edge condition where there's insufficient numbers in the source vector to supply the configured number of random values)

CPerkins