Skip to content

Instantly share code, notes, and snippets.

@FayDoom
Last active July 15, 2026 23:33
Show Gist options
  • Select an option

  • Save FayDoom/cd64538fb8ec14a5e1bf54a0de3a48f6 to your computer and use it in GitHub Desktop.

Select an option

Save FayDoom/cd64538fb8ec14a5e1bf54a0de3a48f6 to your computer and use it in GitHub Desktop.
Javascript - Very fast cartesian product algorithm
/*
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