无标题
There is an array generated by a rule:
- The first item is
1 . - If
k is in the array, then k*3+1 and k*2+1 are in the array. - The array is sorted. There are no duplicate values.
Please write a function that accepts an input N . It should return the index N of the array. For example [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ....] n = 10 , return 22 n = 100 , return 447
const arr = [1];
let cache = [1];
const generate = (index) => {
let stable = arr[index] && ((2 * cache[0] + 1) > arr[index]);
while (arr.length < index + 1 || !stable) {
console.log('计算');
const newer = [];
cache.forEach((n) => {
const k2 = 2 * n + 1;
const k3 = 3 * n + 1;
if (!arr.includes(k2) && !newer.includes(k2)) {
newer.push(k2);
}
if (!arr.includes(k3) && !newer.includes(k3)) {
newer.push(k3);
}
})
arr.push(...newer);
cache = newer.sort((a, b) => a - b);
arr.sort((a, b) => a - b);
stable = !!arr[index] && ((2 * cache[0] + 1) > arr[index]);
}
return arr[index];
}
console.log(generate(10));
console.log(generate(100));
console.log(generate(20));
console.log(arr);
暂记
|