Last active
April 15, 2019 00:47
-
-
Save dance2die/cee0a284dcf0be414a2974f567140e7d to your computer and use it in GitHub Desktop.
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
const or = (a, b) => Boolean(a) || Boolean(b); | |
const orBit = toBit(or); | |
const fullAdder = (a, b, c = 0) => { | |
const first = halfAdder(a, b); | |
const second = halfAdder(first.s, c); | |
return { c: orBit(first.c, second.c), s: second.s }; | |
}; | |
function addTwoBits(a1, a2) { | |
// Note that we start with the index `1` here | |
// because we need to start from the right-most (least significant) bit. | |
// e.g.) given a1 = "01", we start from "1", not "0". | |
const { c: c0, s: b0 } = halfAdder(+a1[1], +a2[1]); | |
const { c: c1, s: b1 } = fullAdder(+a1[0], +a2[0], c0); | |
return { c1, b1, b0 }; | |
} | |
[ | |
["00", "10"], ["01", "00"], ["10", "00"], | |
["10", "01"], ["10", "10"], ["11", "00"], | |
["11", "01"], ["11", "10"], ["11", "11"] | |
].map(v => log(`addTwoBits(${v[0]}, ${v[1]})`, addTwoBits(v[0], v[1]))); | |
// result | |
// addTwoBits(00, 10) { c1: 0, b1: 1, b0: 0 } | |
// addTwoBits(01, 00) { c1: 0, b1: 0, b0: 1 } | |
// addTwoBits(10, 00) { c1: 0, b1: 1, b0: 0 } | |
// addTwoBits(10, 01) { c1: 0, b1: 1, b0: 1 } | |
// addTwoBits(10, 10) { c1: 1, b1: 0, b0: 0 } | |
// addTwoBits(11, 00) { c1: 0, b1: 1, b0: 1 } | |
// addTwoBits(11, 01) { c1: 1, b1: 0, b0: 0 } | |
// addTwoBits(11, 10) { c1: 1, b1: 0, b0: 1 } | |
// addTwoBits(11, 11) { c1: 1, b1: 1, b0: 0 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment