Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FocalLensCollection {
- private val lensBox = mutableMapOf<Int, MutableMap<String, Int>>()
- init {
- repeat(256) {
- lensBox[it] = mutableMapOf<String, Int>()
- }
- }
- fun sumUpHashes(commands: List<String>): Int {
- return commands.sumBy { hash(it) }
- }
- fun order(lenses: List<String>): Int {
- lenses.forEach { command ->
- val indexOfOperation = command.indexOfFirst { it == '-' || it == '=' }
- val label = command.substring(0 until indexOfOperation)
- val operation = command[indexOfOperation]
- val focus = command.substring((indexOfOperation+1) until command.length)
- val hash = hash(label)
- if (operation == '=') lensBox[hash]?.set(label, focus.toInt())
- else lensBox[hash]?.remove(label)
- }
- return lensBox.entries.map { box ->
- val boxValue = 1 + box.key
- box.value.values.mapIndexed { slotNumber, lensFocus ->
- boxValue * (slotNumber + 1) * lensFocus
- }.sum()
- }.sum()
- }
- fun hash(command: String): Int {
- return command.map { it.toInt() }.fold(0) { currentValue, characterValue ->
- ((currentValue + characterValue) * 17) % 256
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement