Last active
July 18, 2024 14:48
-
-
Save lysenko-sergey-developer/2c6ee0e418a9a7af62439ec85b519942 to your computer and use it in GitHub Desktop.
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
/** | |
Cartesian product | |
for example for input: [['x', 'y'], [1, 2 ]] | |
we will have output: ['x1', 'x2', 'y1', 'y2'] | |
for example for input: [['x', 'y'], [1, 2, 3]] | |
we will have output: ['x1', 'x2', 'x3', 'y1', 'y2', 'y3'] | |
1 1 -> 1 | |
1 2 -> 2 | |
2 2 -> 4 | |
2 3 -> 6 | |
3 3 -> 9 | |
n m -> n*m | |
n m k -> n*m*k | |
O(n^n) | |
**/ | |
type Set = string[] | number[]; | |
const getIndexes = (index: number, setsLength: number[]) => { | |
const indexes = [index % setsLength[0]]; | |
let mathExpression = index; | |
// O(n) | |
for (let i = 1; i < setsLength.length; i++) { | |
mathExpression = Math.floor(mathExpression / setsLength[i - 1]); | |
indexes.push(mathExpression % setsLength[i]); | |
} | |
return indexes; | |
}; | |
function cartesianProduct(sets: Set[]) { | |
if (!sets.length) return []; | |
if (sets.length === 1) return sets[0]; | |
const setsLength = sets.map((s) => s.length); | |
const setsLenghtProduct = setsLength.reduce((a, b) => a * b, 1); | |
const product = Array.from({ length: setsLenghtProduct }); | |
// O(n^n) | |
for (let index = 0; index < setsLenghtProduct; index++) { | |
// O(n) | |
const setsIndexes = getIndexes(index, setsLength); | |
let productPart = ""; | |
// | |
for (let i = 0; i < setsIndexes.length; i++) { | |
productPart += sets[i][setsIndexes[i]]; | |
} | |
product[index] = productPart; | |
} | |
return product; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works for any Cartesian size. However, if you know the size of your Cartesian, the simpler implementation will be faster. Here is an example of a simple n^4 implementation