javascript - 从 n 位数组返回 k 位数字的函数

标签 javascript arrays algorithm

我想构造一个函数 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/

相关文章:

javascript - 在 Javascript 中对数字数组进行排序

arrays - 采访任务: check if array consists of pairs in O(n) time and O(1) of additional memory

java - 看不懂非递归MergeSort算法

arrays - 跟踪数组的最高占用索引

javascript - 使用 ajax 进行 Jquery 表单验证

javascript - 使用 jwplayer 进行动态 rtmp 流传输

javascript - 多维数组 JAVASCRIPT 出了问题

javascript - 将 VBA 转换为 JavaScript 自定义函数,得到不同的答案

C# + N单元 : Unit testing methods with byte array arguments

algorithm - Base91,是怎么计算出来的?