Skip to content

Instantly share code, notes, and snippets.

@Araxeus
Last active April 9, 2022 09:22
Show Gist options
  • Save Araxeus/9541ad9652efab515d2aca807e01fdb0 to your computer and use it in GitHub Desktop.
Save Araxeus/9541ad9652efab515d2aca807e01fdb0 to your computer and use it in GitHub Desktop.
Advent of Code 2021
const x = $('pre').textContent;
[...x.matchAll(/(?<dir>\w+) (?<num>\d+)/g)].reduce((p, c) => ({
y: c.groups.dir === 'forward' ? p.y + Number(c.groups.num) : p.y,
x: p.x + (c.groups.dir === 'up' ? Number(-c.groups.num) : c.groups.dir === 'down' ? Number(c.groups.num) : 0)
}),{x: 0, y: 0});
// ******************************************************************************************************************** Part 2
const x = $('pre').textContent;
[...x.matchAll(/(?<dir>\w+) (?<num>\d+)/g)].reduce((p, c) => {
c.groups.num = Number(c.groups.num);
switch(c.groups.dir) {
case 'down': p.aim += c.groups.num; break;
case 'up': p.aim -= c.groups.num; break;
case 'forward':
p.x += c.groups.num;
p.y += p.aim * c.groups.num;
}
return p;
},
{ x: 0, y: 0, aim: 0 }
);
const x = $('pre').textContent.trim().split('\n');
let res = [],
gamma = '',
epsilon = '';
x.forEach(line => {
[...line].forEach((v, i) => {
res[i] ??= [0, 0];
res[i][Number(v)]++;
});
});
for (const count of res) {
const [a, b] = count[0] > count[1] ? [0, 1] : [1, 0];
gamma += a;
epsilon += b;
}
console.log({ gamma, epsilon, mult: parseInt(gamma, 2) * parseInt(epsilon, 2) });
// ******************************************************************************************************************** Part 2
const x = $('pre').textContent.trim().split('\n');
const find = (lines, i, mostCommon) => {
let zero = 0, one = 0;
lines.forEach(line => line[i] === '0' ? zero++ : one++);
return mostCommon ? (zero > one ? '0' : '1') : (one < zero ? '1' : '0');
}
let oxygen = [...x];
let scrubber = [...x];
for (let i = 0; oxygen.length > 1; i++) {
const max = find(oxygen, i, true);
oxygen = oxygen.filter(line => line[i] === max)
}
for (let i = 0; scrubber.length > 1; i++) {
const min = find(scrubber, i, false);
scrubber = scrubber.filter(line => line[i] === min)
}
const result = parseInt(oxygen[0], 2) * parseInt(scrubber[0], 2);
// ******************************** Part 2 V2
const x = $('pre').textContent.trim().split('\n');
const types = ['scrubber', 'oxygen'].map(e => ({ name: e, lines: [...x] }));
const find = ({ lines }, i, mostCommon) => {
let zero = [], one = [];
lines.forEach(line => (line[i] === '0' ? zero : one).push(line));
return mostCommon
? (zero.length > one.length ? zero : one)
: (one.length < zero.length ? one : zero);
}
types.forEach(type => {
for (let i = 0; type.lines.length > 1; i++)
type.lines = find(type, i, type.name === 'oxygen');
})
const result = types.reduce((p, c) => parseInt(p.lines[0], 2) * parseInt(c.lines[0], 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment