Skip to main content
3 of 5
added 667 characters in body
Florian F
  • 591
  • 4
  • 9

Java

I am surprised nobody stated the obvious: (I'll assume swap(x,x) does nothing)

static void shuffle(){
    swap(1,rand(0,1));
    swap(2,rand(0,2));
    swap(3,rand(0,3));
    swap(4,rand(0,4));
    swap(5,rand(0,5));
    swap(6,rand(0,6));
    swap(7,rand(0,7));
    swap(8,rand(0,8));
    swap(9,rand(0,9));
    swap(10,rand(0,10));
    swap(11,rand(0,11));
    swap(12,rand(0,12));
    swap(13,rand(0,13));
    swap(14,rand(0,14));
    swap(15,rand(0,15));
    swap(16,rand(0,16));
    swap(17,rand(0,17));
    swap(18,rand(0,18));
    swap(19,rand(0,19));
    swap(20,rand(0,20));
    swap(21,rand(0,21));
    swap(22,rand(0,22));
    swap(23,rand(0,23));
    swap(24,rand(0,24));
    swap(25,rand(0,25));
    swap(26,rand(0,26));
    swap(27,rand(0,27));
    swap(28,rand(0,28));
    swap(29,rand(0,29));
    swap(30,rand(0,30));
    swap(31,rand(0,31));
    swap(32,rand(0,32));
    swap(33,rand(0,33));
    swap(34,rand(0,34));
    swap(35,rand(0,35));
    swap(36,rand(0,36));
    swap(37,rand(0,37));
    swap(38,rand(0,38));
    swap(39,rand(0,39));
    swap(40,rand(0,40));
    swap(41,rand(0,41));
    swap(42,rand(0,42));
    swap(43,rand(0,43));
    swap(44,rand(0,44));
    swap(45,rand(0,45));
    swap(46,rand(0,46));
    swap(47,rand(0,47));
    swap(48,rand(0,48));
    swap(49,rand(0,49));
    swap(50,rand(0,50));
    swap(51,rand(0,51));
}

OK, ok, it can be shorter:

package stackexchange;

import java.util.Arrays;

public class ShuffleDry
{
    static int[] deck = new int[52];
    
    static void swap(int i, int j){
        int t=deck[i];
        deck[i] = deck[j];
        deck[j] = t;
    }

    static int rand(int min, int max){
        return (int)Math.floor(Math.random()*(max-min+1))+min;
    }

    static void initialize(){
        for( int i=0 ; i<deck.length ; i++ ){
            deck[i] = i;
            swap(i,rand(0,i));
        }
    }
    
    static void shuffle(){
        while( deck[0]!=0 ) swap(0,deck[0]);
        for( deck[0]=52; deck[0]-->1 ; ) swap(deck[0],rand(deck[0],51));
        swap(0,rand(0,51));
    }

    public static void main(String[] args) {
        initialize();
        System.out.println("init: " + Arrays.toString(deck));
        shuffle();
        System.out.println("rand: " + Arrays.toString(deck));
    }

}

PS: oops, the XOR swap algorithm won't like it. I'll correct that shortly.

Florian F
  • 591
  • 4
  • 9