Skip to content

Commit

Permalink
Day 3
Browse files Browse the repository at this point in the history
  • Loading branch information
mohsen-biglari committed Dec 3, 2024
1 parent 5f01444 commit f071d1a
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 10 deletions.
8 changes: 3 additions & 5 deletions src/Day01.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,9 @@ fun main() {
}
}

val testInput1 = readInput("Day01_test_part1")
check(part1(testInput1) == 11L)

val testInput2 = readInput("Day01_test_part2")
check(part2(testInput2) == 31L)
val testInput = readInput("Day01_test")
check(part1(testInput) == 11L)
check(part2(testInput) == 31L)

val input = readInput("Day01")
part1(input).println()
Expand Down
8 changes: 3 additions & 5 deletions src/Day02.kt
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,9 @@ fun main() {
}
}

val testInput1 = readInput("Day02_test_part1")
check(part1(testInput1) == 2)

val testInput2 = readInput("Day02_test_part2")
check(part2(testInput2) == 4)
val testInput = readInput("Day02_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)

val input = readInput("Day02")
part1(input).println()
Expand Down
58 changes: 58 additions & 0 deletions src/Day03.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
fun main() {

data class Multiplication(
val a: Int,
val b: Int
) {
constructor(a: String, b: String) : this(a.toInt(), b.toInt())

fun mul() = a * b
}

fun String.extractEnabledMuls(): List<Multiplication> {
val regex = Regex("mul\\((\\d{1,3}),(\\d{1,3})\\)|do\\(\\)|don't\\(\\)")
var isEnabled = true
return buildList {
regex.findAll(this@extractEnabledMuls).forEach {
val isDo = it.value == "do()"
val isDonot = it.value == "don't()"
when {
isDo -> isEnabled = true
isDonot -> isEnabled = false
else -> {
if (isEnabled) {
add(Multiplication(it.groups[1]!!.value, it.groups[2]!!.value))
}
}
}
}
}
}

fun String.extractMuls(): List<Multiplication> {
val regex = Regex("mul\\((\\d{1,3}),(\\d{1,3})\\)")
return buildList {
regex.findAll(this@extractMuls).forEach {
add(Multiplication(it.groups[1]!!.value, it.groups[2]!!.value))
}
}
}

fun part1(input: List<String>): Int {
val oneBigLine = input.joinToString(separator = "")
return oneBigLine.extractMuls().sumOf { it.mul() }
}

fun part2(input: List<String>): Int {
val oneBigLine = input.joinToString(separator = "")
return oneBigLine.extractEnabledMuls().sumOf { it.mul() }
}

val testInput1 = readInput("Day03_test")
check(part1(testInput1) == 161)
check(part2(testInput1) == 48)

val input = readInput("Day03")
part1(input).println()
part2(input).println()
}

0 comments on commit f071d1a

Please sign in to comment.