我想构造一个函数 showNum(ar,k)
从数组 ar
中获取所有 k 位数字。
例如,showNum([1,2,3],2)
应该返回 12,13,21,23,31,32
和showNum([1,2,3],1)
应该返回1,2,3
。
我的代码在 k
已修复的情况下运行良好。
例如,k
的情况是 3。
我的想法是循环3次。
function showNum(a){
var ar = [];
var n = a.length;
for(i = 0; i <= n; i++){
for(j = 0; j <= n; j++){
for(k = 0; k <= n; k++){
if(a[i] != a[j] && a[i] != a[k] && a[k] != a[j]) ar.push(a[i]*100 + a[j]*10 + a[k]);
}
}
}
return ar;
}
但是当k
任意小于n
时,我不知道如何循环。
最佳答案
递归在这里非常有用:在循环内部,进行递归调用以再次迭代数字。这可以使用生成器轻松完成:
function* combinations(values, depth, previous = []) {
if(depth <=0) {
yield previous.reduce((res, n, i) => res + n * 10 ** i, 0);
return;
}
for(const value of values) {
if(previous.includes(value))
continue;
yield* combinations(values, depth - 1, [...previous, value]);
}
}
可用作:
[...combinations([1, 2, 3], 2)]
function* combinations(values, depth, previous = []) {
if(depth <=0) {
yield previous.reduce((res, n, i) => res + n * 10 ** i, 0);
return;
}
for(const value of values) {
if(previous.includes(value))
continue;
yield* combinations(values, depth - 1, [...previous, value]);
}
}
console.log([...combinations([1, 2, 3], 2)])
关于javascript - 从 n 位数组返回 k 位数字的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847084/