Created
December 7, 2015 19:13
-
-
Save soutar/a842cb3d863ce5ffc72f to your computer and use it in GitHub Desktop.
Advent of Code - Day 7
This file contains hidden or 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
import fetch from 'node-fetch'; | |
const OPERATIONS = { | |
'AND': (x, y) => x & y, | |
'OR': (x, y) => x | y, | |
'NOT': (value) => ~ value, | |
'LSHIFT': (x, y) => x << y, | |
'RSHIFT': (x, y) => x >> y | |
} | |
function parseInput (input) { | |
let components = input.split(' '); | |
let first; | |
let operator; | |
let second; | |
switch (components.length) { | |
case 1: | |
return { components: [components] } | |
break; | |
case 2: | |
[operator, first] = components; | |
return { components: [first], operation: OPERATIONS[operator] }; | |
break; | |
case 3: | |
[first, operator, second] = components; | |
return { components: [first, second], operation: OPERATIONS[operator] }; | |
break; | |
} | |
} | |
function parseCircuitDefinition (circuitDefinition) { | |
return circuitDefinition.split('\n').reduce((circuit, wire) => { | |
let [input, output] = wire.split('->').map(string => string.trim()); | |
circuit[output] = parseInput(input); | |
return circuit; | |
}, {}); | |
} | |
function readSignal (circuit, wire, state = {}) { | |
let input = circuit[wire]; | |
let { operation } = input; | |
if (state[wire]) { | |
return state[wire]; | |
} | |
let components = input.components.map(component => { | |
return (!isNaN(component)) | |
? parseInt(component) | |
: readSignal(circuit, component, state); | |
}); | |
let result = (operation) | |
? operation(...components) | |
: components[0]; | |
return state[wire] = wrap(result, 0, 65536); | |
} | |
function wrap (number, min, max) { | |
let range = max - min; | |
return ((number - min) % range < 0) | |
? number + range | |
: number; | |
} | |
fetch('https://gist.githubusercontent.com/soutar/60af14354c560946f992/raw/ae38f4a978c2d46578820595e0c77c168934958c/input.txt') | |
.then(response => response.text()) | |
.then(response => { | |
let circuit = parseCircuitDefinition(response); | |
let signal = readSignal(circuit, 'a'); | |
console.log(signal); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment