link mingle home | logged in as: guest | login/register| submit link


IndiaDiscuss.com : Social Bookmarkings and News Networking Site for India
interview_questions
Bookmarks
Knuth Card Shuffling Algorithm Code Snippet
15
Votes

Move through the array from top to bottom (i.e, index 0,1,..,n), swapping each card in turn with another card from a random position in the part of the pack that has not yet been passed through (including itself). With unbiased random numbers, it always generates a random permutation. Complexity: O(n)

saved under Code Snippets by interview_questions

 
import java.util.Arrays;

public class CardShuffling {
    public CardShuffling() {
    }

    public static void main(String[] args) {
        CardShuffling cardShuffling = new CardShuffling();
        int[] cards = new int[52];
        for (int i = 0; i <cards.length ; i++)cards[i]=i;
        System.out.println("Initial stetae of the deck");
        System.out.println(Arrays.toString(cards));
        knuthShuffle(cards);
        System.out.println("After shuffling");
        System.out.println(Arrays.toString(cards));
       
    }
    
    /** Generates a random permutation of the array using Knuth's shuffle algorithm */
    public static void knuthShuffle(int[] a) {
      for (int i = 0; i < a.length; i++) {
        // Pick a random index in i ... a.length-1
        int k = i + (int) (Math.random() * (a.length - i));
        // Swap.
        int temp = a[i];
        a[i] = a[k];
        a[k] = temp;
      }
    }
}

comment by webmaster on 2008-05-29 02:21:05
 



Enter the string above
 
IndiaDiscuss | Published News | Hot
Indian Social News and Links Network
IndiaDiscuss | Published News
Indian Social News and Links Network