0

A want to create a function that takes an array of arrays as arguments. I then want it to find all the combinations using 1 value from each array. I want the array to be able to be any length. The order of the arrays would not matter, although I want the first element of an array to correspond to the first array. For example:

function combine(arr){
    return /* I need help with this part */;
}
var list = [['c',4,'b'],[1,'a']];
var foo = combine(list); //should equal bar
var bar = [['c',1],['c','a'],[4,1],[4,'a'],['b',1],['b','a']; //this should be the result of combine(list)

Also, could this be done with just for-loops, or would it have to be recursive?

Cyoce
  • 253
  • 3
  • 14
  • 4
    Nothing ever *has to be* recursive; it's just a convenience. – Pointy Apr 12 '15 at 02:45
  • `list[0].map(function(a){ return list[1].map(function(b){ return [a, b];});});` – dandavis Apr 12 '15 at 02:49
  • That's basically a flatmapping transformation. – elclanrs Apr 12 '15 at 02:50
  • @Pointy traversing of tree structures has to be recursive. – zerkms Apr 12 '15 at 02:51
  • @zerkms: you can iterate trees using while(), push(), common helper functions, etc, but it is usually much simpler to use recursion. – dandavis Apr 12 '15 at 02:53
  • @dandavis it would like to see an implementation (that does not use implicit or explicit recursion) of a function that pretty-prints the structure (key: value pairs with nesting) of this tree: http://pastebin.com/iwqbjGfi – zerkms Apr 12 '15 at 02:55
  • @zerkms recall that FORTRAN (at least in the old days) did not allow recursive function calls, and yet people could write code to do this stuff. "Implicit recursion" is just another way of saying "use some loops" :) – Pointy Apr 12 '15 at 02:58
  • 1
    @Pointy we don't need loops either then! :-) A counter, a condition check and `goto` :-) PS: yep, now I agree you can traverse it though, with a stack. – zerkms Apr 12 '15 at 03:01
  • @zerkms: i wouldn't, the recursive version would be a lot neater... – dandavis Apr 12 '15 at 03:16

0 Answers0