0

For example, I have an array

["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,

Wesley Skeen
  • 6,937
  • 12
  • 37
  • 55

2 Answers2

1
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.

Ben McCormick
  • 23,365
  • 11
  • 48
  • 70
  • Thanks, This would of done it. I got an answer from this link stackoverflow.com/questions/9960908/permutations-in-javascript, just before you added this – Wesley Skeen Mar 27 '13 at 20:49
  • 1
    Just tried this today. All it does is print one item of the array, not the combination. – Raymond Camden Dec 09 '15 at 11:15
0

You could start with this:

http://rosettacode.org/wiki/Permutations#JavaScript

It's implemented to output to an HTML element, but you should be able to easily adapt it to meet your needs.

Mike Van Til
  • 133
  • 1
  • 7