Skip to content

Instantly share code, notes, and snippets.

@josepot
Created December 7, 2018 21:24
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 josepot/f71fb372111bb9c17003edc94ffc539e to your computer and use it in GitHub Desktop.
Save josepot/f71fb372111bb9c17003edc94ffc539e to your computer and use it in GitHub Desktop.
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