Advertisement
Guest User

Untitled

a guest
Dec 15th, 2023
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.29 KB | Source Code | 0 0
  1. class FocalLensCollection {
  2.     private val lensBox = mutableMapOf<Int, MutableMap<String, Int>>()
  3.  
  4.     init {
  5.         repeat(256) {
  6.             lensBox[it] = mutableMapOf<String, Int>()
  7.         }
  8.     }
  9.  
  10.     fun sumUpHashes(commands: List<String>): Int {
  11.         return commands.sumBy { hash(it) }
  12.     }
  13.  
  14.     fun order(lenses: List<String>): Int {
  15.         lenses.forEach { command ->
  16.             val indexOfOperation = command.indexOfFirst { it == '-' || it == '=' }
  17.             val label = command.substring(0 until indexOfOperation)
  18.             val operation = command[indexOfOperation]
  19.             val focus = command.substring((indexOfOperation+1) until command.length)
  20.             val hash = hash(label)
  21.  
  22.             if (operation == '=') lensBox[hash]?.set(label, focus.toInt())
  23.             else lensBox[hash]?.remove(label)
  24.         }
  25.  
  26.         return lensBox.entries.map { box ->
  27.             val boxValue = 1 + box.key
  28.             box.value.values.mapIndexed { slotNumber, lensFocus ->
  29.                 boxValue * (slotNumber + 1) * lensFocus
  30.             }.sum()
  31.         }.sum()
  32.     }
  33.  
  34.     fun hash(command: String): Int {
  35.         return command.map { it.toInt() }.fold(0) { currentValue, characterValue ->
  36.             ((currentValue + characterValue) * 17) % 256
  37.         }
  38.     }
  39. }
Tags: adventofcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement