Advertisement
Guest User

Untitled

a guest
Dec 15th, 2023
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { readFileSync } from 'fs'
  2.  
  3. function hash(input: string): number {
  4.     let curr = 0
  5.     for (let i = 0; i < input.length; i++) {
  6.         const code = input[i].charCodeAt(0)
  7.         curr += code
  8.         curr *= 17
  9.         curr %= 256
  10.     }
  11.     return curr
  12. }
  13.  
  14. function part1(input: string): number {
  15.     const strings = input.replace(/\n+/, '').split(',')
  16.     return strings.reduce((acc, s) => acc + hash(s), 0)
  17. }
  18.  
  19. function part2(input: string): number {
  20.     const boxes = Array.from({ length: 256 }, () => new Map<string, number>())
  21.     const strings = input.replace(/\n+/, '').split(',')
  22.  
  23.     for (let string of strings) {
  24.         const [label, op, n] = string.split(/\b/)
  25.         const index = hash(label)
  26.         if (op === '=') {
  27.             boxes[index].set(label, Number(n))
  28.         } else {
  29.             boxes[index].delete(label)
  30.         }
  31.     }
  32.  
  33.     let total = 0
  34.     for (let i = 0; i < boxes.length; i++) {
  35.         let slot = 1
  36.         for (const focalLength of boxes[i].values()) {
  37.             total += (i + 1) * slot++ * focalLength
  38.         }
  39.     }
  40.  
  41.     return total
  42. }
  43.  
  44. let input = 'rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7'
  45. input = readFileSync('day15.txt', { encoding: 'utf8' })
  46.  
  47. console.log('part 1:', part1(input))
  48. console.log('part 2:', part2(input))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement