Advent of Code 2022 - Day 3: Rucksack Reorganization Solution
Find shared item and calculatePart 1
Find shared item and calculate based on lowercase or uppercase
Implementation
1const fs = require("fs")23const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/).filter(Boolean)45const isLower = char => char === char.toLowerCase()67const 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))1112 return (13 acc +14 sharedItem.charCodeAt(0) -15 (isLower(sharedItem) ? "a" : "A").charCodeAt(0) +16 1 +17 (isLower(sharedItem) ? 0 : 26)18 )19}, 0)2021console.log(res)
Part 2
Group data into chunks with size of 3
Calculation is the same as Part 1
Implementation
1const fs = require("fs")23const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/).filter(Boolean)45const isLower = char => char === char.toLowerCase()67const chunks = []8const chunkSize = 39for (let i = 0; i < data.length; i += chunkSize) {10 const chunk = data.slice(i, i + chunkSize)11 chunks.push(chunk)12}1314const res = chunks.reduce((acc, [part1, part2, part3]) => {15 const sharedItem = part116 .split("")17 .find(char => part2.includes(char) && part3.includes(char))1819 return (20 acc +21 sharedItem.charCodeAt(0) -22 (isLower(sharedItem) ? "a" : "A").charCodeAt(0) +23 1 +24 (isLower(sharedItem) ? 0 : 26)25 )26}, 0)2728console.log(res)
References
Comments
Loading comments...
Tags
adventofcode
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.