Skip to content

Instantly share code, notes, and snippets.

@incon incon/AoC-2017-day13.js
Last active Dec 13, 2017

Embed
What would you like to do?
const input = require("fs").readFileSync("day13-input.txt", "UTF-8");
function cycle() {
keys = Object.keys(map);
keys.forEach(key => {
up = map[key]["up"];
depth = map[key]["length"];
if (up) {
map[key]["state"] += 1;
if (map[key]["state"] == depth - 1) {
map[key]["up"] = false;
}
} else {
map[key]["state"] -= 1;
if (map[key]["state"] === 0) {
map[key]["up"] = true;
}
}
});
}
function part1() {
map = {};
input.split("\n").forEach(row => {
split = row.split(": ");
map[split[0]] = {
state: 0,
length: parseInt(split[1]),
up: true
};
});
keys = Object.keys(map).map(n => parseInt(n));
min = Math.min(...keys);
max = Math.max(...keys);
hits = [];
for (let i = 0; i <= max; i++) {
key = String(i);
if (typeof map[key] !== "undefined" && map[key]["state"] === 0) {
hits.push(key);
}
cycle();
}
severity = hits.reduce((count, key) => {
return count + parseInt(key) * map[key]["length"];
}, 0);
return severity;
}
function part2() {
map = {};
input.split("\n").forEach(row => {
split = row.split(": ");
map[split[0]] = {
state: 0,
length: parseInt(split[1]),
up: true
};
});
keys = Object.keys(map).map(n => parseInt(n));
min = Math.min(...keys);
max = Math.max(...keys);
progress = 0;
safeMap = { ...map };
lastDelay = 0;
while (progress < max + 1) {
key = String(progress);
if (
typeof map[key] === "undefined" ||
(typeof map[key] !== "undefined" && map[key]["state"] !== 0)
) {
progress++;
} else {
progress = 0;
map = { ...safeMap };
cycle();
safeMap = JSON.parse(JSON.stringify(map));
lastDelay++;
}
cycle();
}
return lastDelay + 1;
}
console.log("Part 1:", part1());
console.log("Part 2:", part2());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.