以编程方式生成嵌套的for循环 [英] Programmatically generate nested for loops

查看:74
本文介绍了以编程方式生成嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下划线mixin和下面的函数以两种不同的方式执行完全相同的操作,它们获取数组的所有对.我想知道如何创建一个函数(闭包?),该函数允许我传递多少个对"或数组项分组,而不是嵌套 for循环 range-maps每次.

The underscore mixin and the function below do the exact same thing in two different ways, they get all the pairs for an array. I was wondering how I can create a function (closure?) that allows me to pass in how many "pairs" or groupings of array items I want instead of nesting for loops or range-maps every time.

getPairs: function(arr){
  return _.chain(_.range(arr.length))
  .map(function(setOne){
    return _.chain(_.range(arr.length))
    .map(function(setTwo){
      return [
        arr[setOne],
        arr[setTwo],
      ]
    })
    .value()
  })
  .value()
}

function getPairs(arr){
  var pairs = []
  for(var i = 0; i < arr.length; i++){
    for(var p = 0; p < arr.length; p++){
      var pair = [
        arr[i],
        arr[p],
      ]
      pairs.push()
    }
  }
  return pairs
}

推荐答案

引人入胜的问题.为了获得一个简单的解决方案,我不得不在框外思考.实际上,整个过程可以通过两个 for 循环和一些繁重的数学运算来完成.这是代码:

Fascinating question. To get a simple solution I had to think a bit outside the box. As it is, the whole thing can be accomplished with two for loops and some heavy math. Here's the code:

function getGroupings(arr, numPerGroup){
    numPerGroup > 1 || (numPerGroup = 2);
    var groups = Math.pow(arr.length, numPerGroup);
    var groupings = [];
    for (var i = 0; i < numPerGroup; i++) {
        for (var j = 0; j < groups; j++) {
            groupings[j] || groupings.push(Array(numPerGroup));
            var index = Math.floor(j / Math.pow(arr.length, i)) % arr.length;
            groupings[j][i] = arr[index];
            if (i === numPerGroup - 1) groupings[j] = groupings[j].reverse();
        }
    }
    return groupings;
}

有关其工作原理的一些说明:

A few notes on how this works:

  • 它为内部数组中的每个项目运行一次外部"for"循环,并为外部数组中的每个项目运行一次内部"for"循环.向后,您可能会说.
  • 内部"for"循环的工作方式类似于二进制时钟,其中(时钟值)===(我们要访问的传入数组的索引).
  • 其中 n =(传入数组的长度),它将每次在自己的位置递增时钟,即第一个( n ^ 1)经常位于( n ^ 1)的位置,通常是( n ^ 2)'的一个( n ^ 2)'位置,依此类推,直到( n ^ num-per-group)的位置为止.
  • 在最后一次迭代中,它反转所有内部数组以实际上将一个人的位置放到最后,将( n ^ 1)的位置放到倒数第二,等等...不一定必要,但会产生更多预期的输出.
  • It runs the outer `for` loop once for every item in the inner arrays, and the inner `for` loop once for every item in the outer array. Backwards, you might say.
  • The inner `for` loop works kind of like a binary clock where (value-of-clock) === (index of the passed-in array we want to access).
  • Where n = (length of the passed-in array), it will increment the clock every time in the one's place, one (n ^ 1)th as often in the (n ^ 1)'s place, one (n ^ 2)th as often in the (n ^ 2)'s place, and so on until the (n ^ num-per-group)'s place.
  • On the last iteration, it reverses all the inner arrays to actually put the one's place last, the (n ^ 1)'s place second-to-last, etc... Not necessarily necessary, but produces a more expected output.

示例:

假设您有一个数组, var arr = [3,6,9] ,并且想要获取所有3- getGroupings(arr,3); .实际的组数为 arr.length ^ 3 = 27 ,因此该函数将生成一个包含27个数组的数组.

Say you have an array, var arr = [3, 6, 9], and you want to get all possible groupings of 3--getGroupings(arr, 3);. The actual number of groups is arr.length ^ 3 = 27, so the function will generate an array of 27 arrays.

(忽略外部 for 循环-想象它的所有迭代一次发生)二进制时钟从0s开始,因此第一个分组是 arr [0],arr [0],arr [0] - [3,3,3] .

(Ignoring the outer for loop--imagine all its iterations happen at once) The binary clock starts at 0s, so the first grouping is arr[0], arr[0], arr[0]--[3, 3, 3].

在下一次迭代中,1的位置前进一个- arr [0],arr [0],arr [1] - [3,3,6] ,然后是 [3、3、9] .

On the next iteration, the 1's place advances by one--arr[0], arr[0], arr[1]--[3, 3, 6], then [3, 3, 9].

接下来是时候让3的位置前进并重置一个位置了- arr [0],arr [1],arr [0] ,因此分组4为 [3,6,3] .依此类推,直到第27个数组 [9,9,9] .

Next it's time for the 3's place to advance and the one's place to reset--arr[0], arr[1], arr[0], so grouping 4 is [3, 6, 3]. And so on until the 27th array, [9, 9, 9].

这是 JSFiddle .试试吧!

Here's a JSFiddle. Try it out!

这篇关于以编程方式生成嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆