Created
December 3, 2022 10:35
-
-
Save jmrnilsson/f23795f9f83005be8e45380fb6bc1317 to your computer and use it in GitHub Desktop.
Advent-of-Code 2022-02
This file contains 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
function intersect(left, right){ | |
return new Set([...left].filter(x => right.has(x))); | |
} | |
function* chunked(arr, n) { | |
for (let i = 0; i < arr.length; i += n) { | |
yield arr.slice(i, i + n); | |
} | |
} | |
async function solve1(input){ | |
let [seed, value] = [[], 0] | |
for (const line of (await readFile(input, { encoding: 'utf8' })).split('\n')){ | |
if (!line) continue; | |
seed.push([line, line.length / 2]) | |
} | |
for (const [rs, len] of seed){ | |
let [char] = intersect(new Set(rs.split('').slice(0, len)), new Set(rs.split('').slice(len, len*2))); | |
value += char == char.toLowerCase() ? char.charCodeAt() - 96 : char.charCodeAt() - 38; | |
} | |
return value; | |
} | |
async function solve2(input){ | |
let [seed, value] = [[], 0] | |
const lines = (await readFile(input, { encoding: 'utf8' })).split('\n'); | |
for (const chunk of chunked(lines.slice(0, lines.length -2), 3)){ | |
seed.push([chunk]) | |
} | |
for (const [rucksack] of seed){ | |
var [tail, head] = [rucksack.slice(1, rucksack.length), new Set(rucksack[0])]; | |
let [char] = tail.reduce((a, v) => intersect(a, new Set(v)), head); | |
value += char == char.toLowerCase() ? char.charCodeAt() - 96 : char.charCodeAt() - 38; | |
} | |
return value; | |
} |
This file contains 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
def solve_1(input_=None): | |
seed, value = [], 0 | |
with open(locate(input_), "r") as fp: | |
for line in (line for line in fp.readlines() if line != "\n"): | |
seed.append([i for i in re.findall(r"\w+", line)][0]) | |
for rucksacks, length in ((r, len(r) // 2) for r in seed): | |
char, = set(rucksacks[:length]).intersection(rucksacks[length:]) | |
value += ord(char) - 96 if char == char.lower() else ord(char) - 38 | |
return value | |
def solve_2(input_=None): | |
seed, value, n = [], 0, 0 | |
with open(locate(input_), "r") as fp: | |
for chunk in chunked((line for line in fp.readlines() if line != "\n"), 3): | |
seed.append([i for i in re.findall(r"\w+", line)][0] for line in chunk) | |
for rucksacks in seed: | |
char, = set.intersection(*[set(r) for r in rucksacks]) | |
value += ord(char) - 96 if char == char.lower() else ord(char) - 38 | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment