Advent of Code 2022 - Day 3: Rucksack Reorganization Solution

Find shared item and calculate

Part 1

Find shared item and calculate based on lowercase or uppercase

Implementation

1const fs = require("fs")
2
3const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/).filter(Boolean)
4
5const isLower = char => char === char.toLowerCase()
6
7const res = data.reduce((acc, el) => {
8 const mid = Math.floor(el.length / 2)
9 const [part1, part2] = [el.substring(0, mid), el.substring(mid)]
10 const sharedItem = part1.split("").find(char => part2.includes(char))
11
12 return (
13 acc +
14 sharedItem.charCodeAt(0) -
15 (isLower(sharedItem) ? "a" : "A").charCodeAt(0) +
16 1 +
17 (isLower(sharedItem) ? 0 : 26)
18 )
19}, 0)
20
21console.log(res)

Part 2

Group data into chunks with size of 3

Calculation is the same as Part 1

Implementation

1const fs = require("fs")
2
3const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/).filter(Boolean)
4
5const isLower = char => char === char.toLowerCase()
6
7const chunks = []
8const chunkSize = 3
9for (let i = 0; i < data.length; i += chunkSize) {
10 const chunk = data.slice(i, i + chunkSize)
11 chunks.push(chunk)
12}
13
14const res = chunks.reduce((acc, [part1, part2, part3]) => {
15 const sharedItem = part1
16 .split("")
17 .find(char => part2.includes(char) && part3.includes(char))
18
19 return (
20 acc +
21 sharedItem.charCodeAt(0) -
22 (isLower(sharedItem) ? "a" : "A").charCodeAt(0) +
23 1 +
24 (isLower(sharedItem) ? 0 : 26)
25 )
26}, 0)
27
28console.log(res)

References

Original problem

Comments

Loading comments...

Tags

adventofcode

Next Post

Advent of Code 2022 - Day 2: Rock Paper Scissors

Dec 3, 2022

Key-pair to the help

Previous Post

HoningJS

Search Posts