Skip to content

Instantly share code, notes, and snippets.

@incon
Last active December 13, 2017 14:11
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 incon/459adfd86afcd9f4de4bc066f96ed2e2 to your computer and use it in GitHub Desktop.
Save incon/459adfd86afcd9f4de4bc066f96ed2e2 to your computer and use it in GitHub Desktop.
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