Advertisement
hrabrica

AoC 2024 | Day 3 | Part 2

Dec 2nd, 2024 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.99 KB | None | 0 0
  1. fun partTwo() {
  2.     println("[2024] Day three, part two...")
  3.     val input = input()
  4.     val regex = "mul\\(\\d+,\\d+\\)|do\\(\\)|don't\\(\\)".toRegex()
  5.     val validMulsDosAndDonts = regex.findAll(input)
  6.         .map { it.value }
  7.         .toList()
  8.  
  9.     val enabledMuls = mutableListOf<String>()
  10.     var mulsEnabled = true
  11.     validMulsDosAndDonts.forEach { command ->
  12.         if (command == "do()") {
  13.             mulsEnabled = true
  14.             return@forEach
  15.         }
  16.         if (command == "don't()") {
  17.             mulsEnabled = false
  18.             return@forEach
  19.         }
  20.         if (mulsEnabled) {
  21.             enabledMuls.add(command)
  22.         }
  23.     }
  24.  
  25.     val mappedMuls = enabledMuls.map {
  26.         val values = it
  27.             .substringAfter("(")
  28.             .substringBeforeLast(")")
  29.             .split(",")
  30.             .map { it.toLong() }
  31.  
  32.         values[0] to values[1]
  33.     }
  34.  
  35.     val result = mappedMuls.sumOf { it.first * it.second }
  36.     println("Result: $result")
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement