How to implement sattolo's algorithm

Here is a reference implementation for sattolo’s algorithm in JavaScript.

sattoloTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
// Variant shuffle of Fischer-yates
// No item will be in its original location, since elements can't be swapped by themselves
function sattolo(array) {
const len = array.length;
for (let i = 0; i < len - 1; i++) { // 0 to n -1, exclusive because the last item doesn't need swapping
let j = Math.floor(Math.random() * (len-(i+1)))+(i+1); // i+1 to len, exclusive
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}