Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through all permutations of two variables

Tags:

javascript

I need to call the following function cross 4 times, for all permutations of the x and y variable with the values 1 and -1;

my approach:

var p = [-1, 1];

p.forEach(function(x) {
  p.forEach(function(y) {
    cross(x, y);
  });
});

Is there a shorter way of doing this?

like image 311
Anton Harald Avatar asked Jun 08 '15 16:06

Anton Harald


2 Answers

If you want to be extra functional, you can use map and then reduce the arrays into one. I don't think it would necessarily be any more efficient than what you have now, nor is it much simpler (it is more functional, just slightly).

var d = [-1, 1];

var r = d.reduce(function(p, x) {
  return p.concat(d.map(function(y) {
    return cross(x, y);
  }));
}, []);

document.getElementById('r').textContent = JSON.stringify(r);
<pre id=r></pre>

I really don't think there is an algorithm with better than n^2 efficiency to produce n^2 combinations.

like image 150
ssube Avatar answered Nov 07 '22 11:11

ssube


There is some overhead in calling a function. e.g. putting the return pointer on the stack. It would probably be slightly faster to use two for loops rather than callbacks to forEach.

var p = [-1, 1];
for (var x = 0; x < p.length; x++) {
    for (var y = 0; y < p.length; y++) {
        cross(p[x], p[y]);
    } 
}
like image 33
bhspencer Avatar answered Nov 07 '22 13:11

bhspencer