Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created April 17, 2024 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/d81215afff82dc58fa2ae2cde932ee3d to your computer and use it in GitHub Desktop.
Save renatoargh/d81215afff82dc58fa2ae2cde932ee3d to your computer and use it in GitHub Desktop.
Generates a truth table out of arbritrary array elements
[
["1", "A", "X"],
["1", "A", "Y"],
["1", "B", "X"],
["1", "B", "Y"],
["2", "A", "X"],
["2", "A", "Y"],
["2", "B", "X"],
["2", "B", "Y"]
]
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