Skip to content

Instantly share code, notes, and snippets.

@swarajd
Last active October 31, 2018 03:45
Show Gist options
  • Save swarajd/e2c9498765ca3a30fe8f2f4640a7b772 to your computer and use it in GitHub Desktop.
Save swarajd/e2c9498765ca3a30fe8f2f4640a7b772 to your computer and use it in GitHub Desktop.
const getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const dValues = (() => {
const result = new Array(27);
result[0] = 1;
result[1] = 0;
for (let i = 2; i < letters.length; i++) {
result[i] = (i - 1) * (result[i - 1] + result[i - 2]);
}
return result;
})();
const swap = (arr, i, j) => {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
const randomDerangement = (arr) => {
const A = arr.slice();
const mark = new Array(A.length);
mark.fill(false);
let i = A.length - 1;
let u = A.length - 1;
while (u >= 2) {
if (!mark[i]) {
let j = getRandomInt(0, i - 1);
while (mark[j]) {
j = getRandomInt(0, i - 1);
}
swap(A, i, j);
let p = Math.random();
let uVal = ((u - 1) * dValues[u - 2])/ dValues[u];
if (p < uVal) {
mark[j] = true;
u = u - 1;
}
u = u - 1;
}
i = i - 1;
}
return A;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment