jeudi 29 octobre 2020

Explanation of card shuffling algorithm (java)

I was trying to better understand in a common Java shuffle deck of cards algorithm, this piece of code:

// Random for remaining positions. 
int r = i + rand.nextInt(52 - i); 

Why is it necessary to "pad" or add i index to the resultant random number? It looks like as you iterate and add i, by subtracting i, you keep the max possible range of random numbers consistent from 0 to 51, but why not just do:

int r = rand.nextInt(52);

Full code:

      
    // Function which shuffle and print the array 
    public static void shuffle(int card[], int n) 
    { 
          
        Random rand = new Random(); 
          
        for (int i = 0; i < n; i++) 
        { 
            // Random for remaining positions. 
            int r = i + rand.nextInt(52 - i); 
              
             //swapping the elements 
             int temp = card[r]; 
             card[r] = card[i]; 
             card[i] = temp; 
               
        } 
    } 



Aucun commentaire:

Enregistrer un commentaire