动态嵌套的for循环用递归来解决 [英] Dynamic nested for loops to be solved with recursion

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

问题描述

我想要得到的结果看起来像这样: Miniors |男孩| 54公斤 - 62公斤,其中的每一个值由管道分隔|来自含有一定的类型的限制的阵列。例如: ageGroups,性别,weightClasses (如上所示)

我可以现在就得到这样的结果的方式是,如果我硬code嵌套的foreach循环(使用underscorejs),但这意味着我得我现在有多少阵列具有遍历得到通缉的结果。
此作品精:

  VAR类别= [];
_.each(ageGroups,功能(ageGroup){
   _.each(性别,功能(性别){
     _.each(weightClasses,功能(weightClass){
       categories.push(ageGroup.name +'|'+ gender.name +'|'+ weightClass.name);
      });
   });
});

的输出是一个数组(类别)用限制阵列的所有可能的组合。

现在,我的问题是,我需要一种方法做同样的数目不详的限制阵列。
我对一个妥善解决的猜测是的递归 BUT 我一直没能产生任何实际工作,因为我不能换我周围的递归的头,只是还没有:)

用一些测试数据ppared小提琴$ P $可以在这里找到: 的jsfiddle
小提琴使用的角度进行一些简单的数据绑定和调试结果输出和underscorejs用于处理数组。


解决方案

我最近写了一个递归函数来创​​建数组的所有组合。你将不得不将数据转化为我的函数使用数组的数组,但这不应该是困难的。

总之,这里的code具有一个可运行的例子:

\r
\r

VAR V = ['Miniors','Kadettes','青年', '老年人'],['男孩','女','男人','女性'],['54千克 - 62公斤','64公斤 - 70公斤','71公斤 - 78公斤','79公斤 - 84公斤'];\r
VAR连击= createCombinations(V);\r
对于(VAR I = 0; I< combos.length;我++){\r
  document.getElementsByTagName(身体)[0] .innerHTML + =组合[I] +< BR />中;\r
}\r
\r
功能createCombinations(字段,currentCombinations){\r
  // prevent副作用\r
  变种tempFields = fields.slice();\r
\r
  //递归建立一个列表组合\r
  VAR分隔符=| ';\r
  如果(!tempFields || tempFields.length == 0){\r
    返回currentCombinations;\r
  }\r
  其他{\r
    变种组合= [];\r
    变种字段= tempFields.pop();\r
\r
    为(VAR valueIndex = 0; valueIndex&下; field.length; valueIndex ++){\r
      VAR VALUENAME =字段[valueIndex]\r
\r
      如果(!currentCombinations || currentCombinations.length == 0){\r
        VAR combinationName = VALUENAME;\r
        combinations.push(combinationName);\r
      }\r
      其他{\r
        为(VAR combinationIndex = 0; combinationIndex&下; currentCombinations.length; combinationIndex ++){\r
          VAR currentCombination = currentCombinations [combinationIndex]\r
          VAR combinationName = VALUENAME +分隔符+ currentCombination;\r
          combinations.push(combinationName);\r
        }\r
      }\r
    }\r
    返回createCombinations(tempFields,组合);\r
  }\r
}

\r

\r
\r

I'm trying to get a result looking something like this: Miniors | Boys | 54kg - 62kg where every value delimited by a pipe | comes from an array containing a certain "type of restriction". For example: ageGroups, genders, weightClasses (as seen above).

The way I'm able to get this result right now is if I hard code the nested forEach-loops (using underscorejs), but this means I have to now how many arrays I have to loop over to get wanted result. This works "fine":

var categories = [];
_.each(ageGroups, function(ageGroup) {
   _.each(gender, function(gender) {
     _.each(weightClasses, function(weightClass) {
       categories.push(ageGroup.name + ' | ' + gender.name + ' | ' + weightClass.name);
      });
   });
});

The output is an array (categories) with all the possible combinations of the restriction arrays.

Now, my problem is that I need a way to do the same with an unknown number of restriction arrays. My guess for a proper solution is recursion, BUT I haven't been able to produce anything that actually works since I'm not able to wrap my head around recursion just yet :)

A fiddle prepared with some test data can be found here: jsFiddle. The fiddle uses angular for some simple databinding and debugging the result output and underscorejs for handling the arrays.

解决方案

I recently wrote a recursive function to create all combinations of arrays. You would have to translate your data into an array of arrays that my function uses, but that shouldn't be difficult.

Anyway, here's the code with a runnable example:

var v = [['Miniors','Kadettes','Juniors', 'Seniors'], ['Boys','Girls','Men','Women'],['54kg - 62kg','64kg - 70kg','71kg - 78kg','79kg - 84kg']];
var combos = createCombinations(v);
for(var i = 0; i < combos.length; i++) {
  document.getElementsByTagName("body")[0].innerHTML += combos[i] + "<br/>";
}

function createCombinations(fields, currentCombinations) {
  //prevent side-effects
  var tempFields = fields.slice();

  //recursively build a list combinations
  var delimiter = ' | ';
  if (!tempFields || tempFields.length == 0) {
    return currentCombinations;
  }
  else {
    var combinations = [];
    var field = tempFields.pop();

    for (var valueIndex = 0; valueIndex < field.length; valueIndex++) {
      var valueName = field[valueIndex];

      if (!currentCombinations || currentCombinations.length == 0) {
        var combinationName = valueName;
        combinations.push(combinationName);
      }
      else {
        for (var combinationIndex = 0; combinationIndex < currentCombinations.length; combinationIndex++) {
          var currentCombination = currentCombinations[combinationIndex];
          var combinationName = valueName + delimiter + currentCombination;
          combinations.push(combinationName);
        }
      }
    }
    return createCombinations(tempFields, combinations);
  }
}

这篇关于动态嵌套的for循环用递归来解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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