通过单个数组递归记录javascript中所有可能的组合 [英] Recurse through single array logging all possible combinations in javascript

查看:64
本文介绍了通过单个数组递归记录javascript中所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个数组

["red", "green", "blue", "purple"]

此数组中可以有任意数量的条目。
使用这个数组我想创建一个可能的组合列表,但从不复制组合

There can be any amount of entries in this array. Using this array I want to create a list of possible combinations but never duplicating a combination

例如,上面的数组将导致

For example, the above array will result in

red,green,blue,purple
red,green,purple,blue
red,blue,green,purple
red,blue,purple,green
red,purple,blue,green
red,purple,green,blue

green,red,blue,purple
green,red,purple,blue
green,blue,red,purple
green,blue,purple,red
green,purple,blue,red
green,purple,red,blue

blue,red,green,purple
blue,red,purple,green
blue,green,red,purple
blue,green,purple,red
blue,purple,green,red
blue,purple,red,green

purple,red,green,blue
purple,red,purple,blue
purple,green,red,blue
purple,green,blue,red
purple,blue,green,red
purple,blue,red,green

我是递归的新手,我还没有完全掌握如何使用它,

I am new to recursion and I havent quite gripped how to accomplish this with it,

推荐答案

function combs(arr,str){
  var arrCopy,popped;
  for(var i =0; i<arr.length; i++){
     arrCopy = arr.splice(0);
     popped = arrCopy.splice(i,1)
     combs(arrCopy,popped);
  }
  if(arr.length === 0){
    console.log(str);
  }
}

这会将所有选项打印到控制台。如果你需要以某种格式返回它们,你可以返回而不是在基本情况下打印,并根据需要将递归调用的结果连接在一起。

That will print all the options to the console. If you need to return them all in some format you can return instead of printing at the base case, and concat the results of the recursive calls together as necessary.

这篇关于通过单个数组递归记录javascript中所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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