Skip to content

Commit

Permalink
Day 5
Browse files Browse the repository at this point in the history
  • Loading branch information
Av32000 committed Dec 6, 2024
1 parent c571904 commit bab8ca0
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 0 deletions.
49 changes: 49 additions & 0 deletions 05/part1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString();
const rules = [];
const updates = [];

input.split("\n").forEach((line) => {
if (line.includes("|")) {
rules.push(line.split("|").map((x) => parseInt(x)));
} else if (line.includes(",")) {
updates.push(line.split(",").map((x) => parseInt(x)));
}
});

function checkRule(rule, update) {
const n1 = update.indexOf(rule[0]);
const n2 = update.indexOf(rule[1]);

return n1 == -1 || n2 == -1 || n1 < n2;
}

function findRulesForNumber(number) {
const result = [];
rules.forEach((r) => {
if (r.includes(number)) result.push(r);
});

return result;
}

const valid = [];
updates.forEach((u) => {
let isValid = true;
u.forEach((n) => {
findRulesForNumber(n).forEach((r) => {
if (!checkRule(r, u)) isValid = false;
});
});

if (isValid) valid.push(u);
});

let result = 0;
valid.forEach((u) => {
result += u[(u.length / 2) >> 0];
});

console.log(result);
70 changes: 70 additions & 0 deletions 05/part2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString();
const rules = [];
const updates = [];

input.split("\n").forEach((line) => {
if (line.includes("|")) {
rules.push(line.split("|").map((x) => parseInt(x)));
} else if (line.includes(",")) {
updates.push(line.split(",").map((x) => parseInt(x)));
}
});

function applyRule(rule, update) {
const n1 = update.indexOf(rule[0]);
const n2 = update.indexOf(rule[1]);

if (n1 == -1 || n2 == -1 || n1 < n2) {
return;
}

let newUpdate = update;
let temp = newUpdate[n2];
newUpdate[n2] = newUpdate[n1];
newUpdate[n1] = temp;

return newUpdate;
}

function findRulesForNumber(number) {
const result = [];
rules.forEach((r) => {
if (r.includes(number)) result.push(r);
});

return result;
}

const invalid = [];
updates.forEach((u) => {
let currentUpdate = u;
let updated = false;
let modified = true;
while (modified) {
modified = false;
currentUpdate.forEach((n) => {
findRulesForNumber(n).forEach((r) => {
const fixed = applyRule(r, currentUpdate);
if (fixed) {
currentUpdate = fixed;
updated = true;
modified = true;
}
});
});
}

if (updated) {
invalid.push(currentUpdate);
}
});

let result = 0;
invalid.forEach((u) => {
result += u[(u.length / 2) >> 0];
});

console.log(result);

0 comments on commit bab8ca0

Please sign in to comment.