函数从n位数组返回k位数字

问题描述 投票:1回答:1

我想构建一个函数showNum(ar,k)从数组ar获取所有k位数字。

例如,showNum([1,2,3],2)应该返回12,13,21,23,31,32

andshowNum([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时,我不知道如何循环。

javascript arrays algorithm
1个回答
3
投票

递归在这里非常有用:在循环内部,进行递归调用以再次迭代数字。这可以使用发电机轻松完成:

 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)])
© www.soinside.com 2019 - 2024. All rights reserved.