JavaScript
NOTE: This solution is technically not correct because it uses a second parameter, i
, in the call to shuffle
, which counts as an external variable.
function shuffle(deck, i) {
if (i <= 0)
return;
else {
swap(deck[rand(0,i-1)], deck[i-1]);
shuffle(deck, i - 1);
}
}
Call with shuffle(deck,52)
A complete working example (had to modify swap
slightly because there is no pass-by-reference of ints in JavaScript):
function rand(min, max) { return Math.floor(Math.random()*(max-min+1)+min); }
function swap(deck, i, j) {
var t=deck[i];
deck[i] = deck[j];
deck[j] = t;
}
function shuffle(deck, i) {
if (i <= 0)
return;
else {
swap(deck, rand(0,i-1), i-1);
shuffle(deck, i - 1);
}
}
// create deck
var deck=[];
for(i=0;i<52;i++)deck[i]=i;
document.writeln(deck);
shuffle(deck,52);
document.writeln(deck);