Monday, 14 October 2013

Get a random item in a list

From the post of StackOverFlow, it seems the best way to generate a random number within a defined range is the follow one:

Min + (int)(Math.random() * ((Max - Min) + 1))

The most important explanation is the operation Math.random() returns a number (double) between [0, 1). Not that 1 is not included, this is why from the range it must adds 1 in order to include the last element.

By using the same method we can get a random item from a list by passing the list size. Here is the sample code

int randomPosition = (int)(Math.random()*list.size());
Object randomObject = list.get(randomPosition);

Here are some important points:
- The elements of a list in Java starts from 0, so no minimum position value needs to be added.
- the last position element is list.size() -1, so it is not need to add one extra value to the range.

Here is an example(method randomViajero):

Source:

No comments:

Post a Comment