Created
November 11, 2019 19:07
-
-
Save mcmillhj/baef7c6b1c3e1714393ea22eff711bb4 to your computer and use it in GitHub Desktop.
casidoo interview question: logic gates
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
"use strict"; | |
// Using De Morgan's Law each of these logic gates can be implemented using one or more NAND gate. | |
const nand = (p, q) => !(p && q); | |
const not = p => nand(p, p); | |
const and = (p, q) => not(nand(p, q)); | |
const or = (p, q) => nand(nand(p, p), nand(q, q)); | |
const nor = (p, q) => not(or(p, q)); | |
const xor = (p, q) => nand(nand(p, nand(p, q)), nand(q, nand(p, q))); | |
const xnor = (p, q) => not(xor(p, q)); | |
const unaryFuncs = [{ f: not, label: "NOT " }]; | |
const binaryFuncs = [ | |
{ f: nand, label: "NAND" }, | |
{ f: and, label: "AND" }, | |
{ f: or, label: "OR" }, | |
{ f: nor, label: "NOR" }, | |
{ f: xor, label: "XOR" }, | |
{ f: xnor, label: "XNOR" } | |
]; | |
const COLUMN_WIDTH = 5; | |
const BINARY_INPUTS = [ | |
[true, true], | |
[true, false], | |
[false, true], | |
[false, false] | |
]; | |
const UNARY_INPUTS = [true, false]; | |
const pad = s => { | |
let padded = s; | |
if (typeof padded !== "string") { | |
padded = padded.toString(); | |
} | |
return padded.padStart(COLUMN_WIDTH); | |
}; | |
const P = pad("P"); | |
const Q = pad("Q"); | |
// binary truth table | |
console.log([P, Q, ...binaryFuncs.map(({ label }) => pad(label))].join("\t")); | |
console.log("--------------------------------------------------------------"); | |
for (const [p, q] of BINARY_INPUTS) { | |
console.log( | |
[pad(p), pad(q), ...binaryFuncs.map(({ f }) => f(p, q))].join("\t") | |
); | |
} | |
// separating line | |
console.log(); | |
// unary truth table | |
console.log([P, ...unaryFuncs.map(({ label }) => pad(label))].join("\t")); | |
for (const p of UNARY_INPUTS) { | |
console.log([pad(p), ...unaryFuncs.map(({ f }) => f(p))].join("\t")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment