Last active
July 15, 2026 23:33
-
-
Save FayDoom/cd64538fb8ec14a5e1bf54a0de3a48f6 to your computer and use it in GitHub Desktop.
Javascript - Very fast cartesian product algorithm
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
| /* | |
| Just a cartesian product algorithm I made. The fastest I've seen. | |
| Not limited to 250 arguments (almost every other use the spread operator in the function's arguments) | |
| Enjoy ! (If you want to thank me, a ferrari would be nice) | |
| - Christophe Jochum | |
| */ | |
| //Generator function, useful when there's a lot of input arrays | |
| const cProd = function* (inTab) { | |
| const inLen = inTab.length | |
| const posCount = new Array(inLen).fill(0) | |
| var pos | |
| do { | |
| let tab = [] | |
| for (let i = 0; i < inLen; i++) | |
| tab[i] = inTab[i][posCount[i]] | |
| for (pos = inLen - 1; pos !== -1; pos--) { | |
| if (++posCount[pos] < inTab[pos].length) break | |
| posCount[pos] = 0 | |
| } | |
| yield tab | |
| } while (pos !== -1) | |
| } | |
| for (const res of cProd([[1, 2, 3], [4, 5, 6]])) console.log(res) | |
| //Simple array output | |
| const cProd = (inTab)=>{ | |
| const inLen = inTab.length | |
| const outTab = [] | |
| const posCount = new Array(inLen).fill(0) | |
| var pos | |
| do { | |
| let tab = [] | |
| outTab.push(tab) | |
| for (let i = 0; i < inLen; i++) | |
| tab[i] = inTab[i][posCount[i]] | |
| for (pos = inLen - 1; pos !== -1; pos--) { | |
| if (++posCount[pos] < inTab[pos].length) break | |
| posCount[pos] = 0 | |
| } | |
| } while (pos !== -1) | |
| return outTab | |
| } | |
| const result = cProd([[1, 2, 3], [4, 5, 6]]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment