Created
April 17, 2024 16:18
-
-
Save renatoargh/d81215afff82dc58fa2ae2cde932ee3d to your computer and use it in GitHub Desktop.
Generates a truth table out of arbritrary array elements
This file contains 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
[ | |
["1", "A", "X"], | |
["1", "A", "Y"], | |
["1", "B", "X"], | |
["1", "B", "Y"], | |
["2", "A", "X"], | |
["2", "A", "Y"], | |
["2", "B", "X"], | |
["2", "B", "Y"] | |
] |
This file contains 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
class Sequence { | |
private currentIndex = 0; | |
constructor(private readonly elements: string[]) {} | |
public get isFinished() { | |
return this.currentIndex === this.elements.length | |
} | |
public getNext() { | |
return this.elements[this.currentIndex++] | |
} | |
public reset() { | |
this.currentIndex = 0 | |
} | |
} | |
const getTruthTable = (sequences: Sequence[], base: string[] = []): string[][] => { | |
if (!sequences.length) { | |
return [base] | |
} | |
const results: string[][] = [] | |
while(!sequences[0].isFinished) { | |
const combinations = getTruthTable(sequences.slice(1), [...base, sequences[0].getNext()]) | |
Array.prototype.push.apply(results, combinations) | |
} | |
sequences[0].reset() | |
return results | |
} | |
const truthTable = getTruthTable([ | |
new Sequence(['1', '2']), | |
new Sequence(['A', 'B']), | |
new Sequence(['X', 'Y']), | |
]) | |
console.log(JSON.stringify(truthTable, null, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment