Created
March 13, 2015 19:03
-
-
Save sixfeetover/65aa153a35279e0a12de to your computer and use it in GitHub Desktop.
Lazy cartesian product
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From http://jsperf.com/lazy-cartesian-product/33 and http://stackoverflow.com/questions/9422386/lazy-cartesian-product-of-arrays-arbitrary-nested-loops | |
function lazyProductMZ2(sets, block, _context) { | |
var n = sets.length, | |
carets = [], | |
args = []; | |
function init() { | |
for (var i = 0; i < n; i++) { | |
carets[i] = 0; | |
args[i] = sets[i][0]; | |
} | |
} | |
function next() { | |
if (!args.length) { | |
init(); | |
return true; | |
} | |
var i = n - 1; | |
carets[i]++; | |
while (carets[i] == sets[i].length) { | |
if (i == 0) { | |
return false; | |
} | |
carets[i] = 0; | |
args[i] = sets[i][0]; | |
carets[--i]++; | |
} | |
args[i] = sets[i][carets[i]]; | |
return true; | |
} | |
while (next()) { | |
block.apply(_context, args); | |
} | |
} | |
function CrossProduct(sets) { | |
this.sets = sets; | |
this.carets = []; | |
this.args = []; | |
} | |
CrossProduct.prototype = { | |
init: function() { | |
for (var i = 0, n = this.sets.length; i < n; i++) { | |
this.carets[i] = 0; | |
this.args[i] = this.sets[i][0]; | |
} | |
}, | |
next: function() { | |
if (!this.args.length) { | |
this.init(); | |
return true; | |
} | |
var i = this.sets.length - 1; | |
this.carets[i]++; | |
if (this.carets[i] < this.sets[i].length) { | |
this.args[i] = this.sets[i][this.carets[i]]; | |
return true; | |
} | |
while (this.carets[i] == this.sets[i].length) { | |
if (i == 0) { | |
return false; | |
} | |
this.carets[i] = 0; | |
this.args[i] = this.sets[i][0]; | |
this.carets[--i]++; | |
} | |
this.args[i] = this.sets[i][this.carets[i]]; | |
return true; | |
}, | |
do: function(block, _context) { | |
return block.apply(_context, this.args); | |
} | |
} | |
function callback() {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment