JSFiddle - React, Tailwind, and code Playground
by mschock
JavaScript
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
function findkthperm(k, n, perm, a) {
perm = perm || '';
if (n === 1) {
return perm + a[0];
} else {
var r = factorial(n - 1),
box = Math.abs(Math.ceil((k / r) - 1)),
k = k % r;
console.log('r: ', r, '; box: ', box, ';k: ', k);
b = a.slice();
console.log('b: ', b, ';a: ', a);
b.splice(box, 1);
console.log('b: ', b);
return findkthperm(k, n - 1, perm + a[box], b);
}
}
console.log(findkthperm(8, 4, '', [1, 2, 3, 4]));