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 ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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:
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 requiresO(n)
for all the queries.Put the numbers in an ArrayList and use Collections.shuffle(arrayList);
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)