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

Java

I am surprised nobody stated the obvious:

    // safe swap
    static void s(int i, int j){
        if( i!=j ) swap(i,j);
    }

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

OK, ok, it can be shorter:

    package stackexchange;

import java.util.Arrays;

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

    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;
            s(i,rand(0,i));
        }
    }
    
    static void s(int i, int j){
        if( i!=j ) swap(i,j);
    }

    static void shuffle(){
        while( deck[0]!=0 ) s(0,deck[0]);
        for( deck[0]=52; deck[0]-->1 ; ) s(deck[0],rand(deck[0],51));
        s(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));
    }

}
Florian F
  • 591
  • 4
  • 9