Open harrytothemoon opened 3 years ago
var countArrangement = function(n) {
let count = 0
let arr = new Array(n).fill(0).map((_, index) => index + 1)
recursion(arr, 0)
return count
function recursion(arr, index) {
if (index === n) return count++
for (let i = index; i < n; i++) {
// try swap
[arr[i], arr[index]] = [arr[index], arr[i]]
// check
if (check(index)) recursion(arr, index + 1)
// swap back
[arr[i], arr[index]] = [arr[index], arr[i]]
}
}
function check(index) {
if (arr[index] % (index + 1) === 0 || (index + 1) % arr[index] === 0) {
return true
}
return false
}
};
runout