Jul 17

The Random class provides a method that returns a random integer between 0 and n (exclusive).


Random wheel = new Random();
int random = wheel.nextInt(n); 

By default it uses the current timestamp as the seed for the random generator, or alternately you can provide your own.

written by objects \\ tags: ,

Nov 27

Sometimes we need to shuffle the oder of elements in a list or array, like shuffling a deck of cards. The Collections utility class has a shuffle() method that achieves this for List’s, but what about arrays. There is no corresponding shuffle() method in the Arrays class, surely we don’t need to loop through the array.

Turns out the solution is very simple. We can just use the same method we use for shuffling lists after first creating a List representation of our array using Arrays.asList()

String[] array = {"A", "B", "C", "D", "E"};
Collections.shuffle(Arrays.asList(array));
System.out.println(Arrays.toString(array));

written by objects \\ tags: , , , ,

Sep 25

The Random class provides a method to return a random integer between 0 and n (exclusive) which can be used. Just add one to the returned value to shift the range from 0-n-1 to 1-n


Random wheel = new Random();
int random = wheel.nextInt(n) + 1; 

written by objects \\ tags: ,