Created
December 7, 2018 21:24
-
-
Save josepot/f71fb372111bb9c17003edc94ffc539e 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 {map, pipe} = require('ramda'); | |
const operations = { | |
NOT: a => ~a, | |
COPY: a => a, | |
AND: (a, b) => a & b, | |
OR: (a, b) => a | b, | |
LSHIFT: (a, b) => a << b, | |
RSHIFT: (a, b) => a >> b, | |
}; | |
const parseLine = line => { | |
const [instruction, to] = line.split(' -> '); | |
if (instruction.startsWith('NOT')) { | |
const [, a] = instruction.split(' '); | |
return {operation: 'NOT', a, to}; | |
} | |
if (instruction.indexOf(' ') === -1) { | |
return {operation: 'COPY', a: instruction, to}; | |
} | |
const [, a, operation, b] = instruction.match(/(\w*) (\w*) (\w*)/); | |
return {operation, a, b, to}; | |
}; | |
const connectWire = wires => { | |
const getValue = x => { | |
const n = parseInt(x); | |
if (!Number.isNaN(n)) return n; | |
const wireVal = wires[x]; | |
return typeof wireVal === 'function' ? wireVal() : wireVal; | |
}; | |
return ({operation, a: a_, b: b_, to}) => { | |
wires[to] = () => { | |
const [a, b] = [a_, b_].filter(x => x !== undefined).map(getValue); | |
return (wires[to] = operations[operation](a, b)); | |
}; | |
}; | |
}; | |
const solution1 = pipe( | |
map(parseLine), | |
parsedLines => { | |
const wires = {}; | |
parsedLines.forEach(connectWire(wires)); | |
return wires.a(); | |
} | |
); | |
const solution2 = pipe( | |
map(parseLine), | |
parsedLines => { | |
const wires = {}; | |
const copy = {}; | |
parsedLines.forEach(connectWire(wires)); | |
parsedLines.forEach(connectWire(copy)); | |
copy.b = wires.a(); | |
return copy.a(); | |
} | |
); | |
module.exports = [solution1, solution2]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment