I have this code that returns cartesian product of three arrays:
function getcartesianProduct(symbols: Array<string>) { const cartesian = <T,>(...sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]); return cartesian(symbols, symbols, symbols).map((items: Array<string>) => items.join("")); }
For example, like this:
>> const numbers: Array<string> = "0123456789".split(""); >> getcartesianProduct(numbers).slice(0, 5) ["000", "001", "002", "003", "004"]
However, I don’t always want my number series to be made out of three numbers. Sometimes, I want four, five, or any other number. That is why I would like to have an argument that would populate the arguments inside cartesian()
function call, accordingly.
I would imagine something like this:
function getcartesianProduct(symbols: Array<string>, n: number) { const cartesian = <T,>(...sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]); return cartesian(symbols * 3).map((items: Array<string>) => items.join("")); }
How can I do that, please? Every help is appreciated.
Advertisement
Answer
I think something like this should work:
function getcartesianProduct(symbols: string[], nrOfArrays: number) { const cartesian = <T,>(sets: T[][]) => sets.reduce<T[][]>((accSets, set) => accSets.flatMap(accSet => set.map(value => [...accSet, value])), [[]]); return cartesian<string>(new Array(nrOfArrays).fill(symbols)).map((items: string[]) => items.join("")).slice(0, nrOfArrays); } const numbers = "0123456789".split(""); console.log(getcartesianProduct(numbers, 5))