• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Wednesday, June 30, 2010

    Write a program to shuffle an pack of cards in the most efficient way. This question can be asked in several flavors.
    Knuth Shuffle / Fisher-Yates Shuffle(Modified version by Durstenfeld) algorithm is the answer to all the trick questions. So how does this algorithm work ?
    Fisher and Yates’ original method was designed to be implemented using pencil and paper, with a precomputed table of random numbers as the source of randomness. Modern approach suggested by – Richard Durstenfeld is as follows:
    To shuffle an array a of n elements:
    for i from n - 1 downto 1 do
            j ← random integer with 0 ≤ ji
            exchange a[j] and a[i]
    Reduced time complexity to O(n), compared to O(n2) for the naive implementation. A sample java implementation :

    01import java.util.Random;
    02
    03static Random rng = new Random();
    04public static void shuffle(int[] array) {
    05 // i is the number of items remaining to be shuffled.
    06 for (int i = array.length; i > 1; i--) {
    07 // Pick a random element to swap with the i-th element.
    08 int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array)
    09 // Swap array elements.
    10 int tmp = array[j];
    11 array[j] = array[i-1];
    12 array[i-1] = tmp;
    13 }
    14}

    0 comments:

    Post a Comment