Java code for shuffling

Many times we are required to shuffle a particular set of objects so that they may mix up properly. A standard way to shuffle any set of objects is to swap their positions randomly. The code given below does this by swapping the position of all the numbers of the array. The code uses the Random utility of utils class for generating random numbers.

Random obj = new Random();
int[] items = new int[10];
int randomPosition;

for (int i=0; i<items.length; i++) {
    items[i] = i;
}

//--- Shuffle by exchanging each element randomly
for (int i=0; i<tems.length; i++) {
    randomPosition = obj.nextInt(items.length);
    int temp = items[i];
    items[i] = items[randomPosition];
    items[randomPosition] = temp;
}


Related Posts

  • Share/Bookmark
You can leave a response, or trackback from your own site.

3 Responses to “Java code for shuffling”

  1. jefu says:

    Actually, you need to select randomPosition from the part of the array starting at item i, rather than randomly from the whole array. You can see this by just counting the possibilities – there are n! permutations of an array of length n,
    but the code given generates n^n possibilities (n at each step for n steps). Since n! does not divide n^n evenly, the n^n method produces some permutations more frequently than others.

    I think :
    randomPosition = i + obj.nextInt(items.length – i)
    is what is needed. If you do this, it is easy to see that there’s nothing to swap on the last iteration, so you can go from 0 to items.length – 1.

  2. Chris says:

    Nice code, but a slightly more “standard” way would be:

    Collections.shuffle( Arrays.asList(items), new Random());

    Just a suggestion.

    C

Leave a Reply

| Shop Free Cellular Phones at Bestincellphones.com. | Thanks to Best CD Rates, iCellPhoneDeals.com Offers Best Cell Phone Deals. and Incinerador De Grasa