Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { readFileSync } from 'fs'
- function hash(input: string): number {
- let curr = 0
- for (let i = 0; i < input.length; i++) {
- const code = input[i].charCodeAt(0)
- curr += code
- curr *= 17
- curr %= 256
- }
- return curr
- }
- function part1(input: string): number {
- const strings = input.replace(/\n+/, '').split(',')
- return strings.reduce((acc, s) => acc + hash(s), 0)
- }
- function part2(input: string): number {
- const boxes = Array.from({ length: 256 }, () => new Map<string, number>())
- const strings = input.replace(/\n+/, '').split(',')
- for (let string of strings) {
- const [label, op, n] = string.split(/\b/)
- const index = hash(label)
- if (op === '=') {
- boxes[index].set(label, Number(n))
- } else {
- boxes[index].delete(label)
- }
- }
- let total = 0
- for (let i = 0; i < boxes.length; i++) {
- let slot = 1
- for (const focalLength of boxes[i].values()) {
- total += (i + 1) * slot++ * focalLength
- }
- }
- return total
- }
- let input = 'rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7'
- input = readFileSync('day15.txt', { encoding: 'utf8' })
- console.log('part 1:', part1(input))
- console.log('part 2:', part2(input))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement