This commit is contained in:
Andrew Glaze
2024-12-12 14:45:51 -05:00
parent 0aaeb40a74
commit 4a04b2408a
2 changed files with 104 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
package day07
import kotlin.io.println
import kotlin.collections.listOf
import kotlin.coroutines.*
class Day07 {
fun parse(input: String): List<Pair<Long, List<Long>>> {
return input.lines().map { line ->
val split = line.split(":")
Pair(split[0].toLong(), split[1].trim().split(" ").map { it.toLong() })
}
}
fun part1(input: String): Long {
return parse(input)
.filter { tryOperations(it, listOf("+", "*")) }
.map { it.first }
.sum()
}
fun tryOperations(equation: Pair<Long, List<Long>>, operations: List<String>): Boolean {
var operPermutations: List<List<String>> = listOf(listOf())
for (i in 0..<equation.second.count() - 1) {
operPermutations = getCombos(operPermutations, operations)
}
for (opers in operPermutations) {
var total = equation.second[0]
for (i in 1..<equation.second.count()) {
when (opers[i - 1]) {
"+" -> total += equation.second[i]
"*" -> total *= equation.second[i]
"||" -> total = "${total}${equation.second[i]}".toLong()
}
}
if (total == equation.first) {
return true
}
}
return false
}
fun getCombos(combos: List<List<String>>, items: List<String>): List<List<String>> {
var newCombos: MutableList<List<String>> = mutableListOf()
for (combo in combos) {
for (item in items) {
newCombos.add(combo + item)
}
}
return newCombos
}
fun part2(input: String): Long {
return parse(input)
.filter {
tryOperations(it, listOf("+", "*", "||"))
}
.map { it.first }
.sum()
}
}

View File

@@ -0,0 +1,41 @@
package day07
import kotlin.test.Test
import util.InputDownloader
class Day07Test {
val dayNum = 7
val day = Day07()
val input = InputDownloader().getInput(dayNum)
val example = InputDownloader().getExample(dayNum)
@Test fun part1Example() {
part1(example, 3749)
}
@Test fun part1Solution() {
part1(input, 1289579105366)
}
@Test fun part2Example() {
part2(example, 11387)
}
@Test fun part2Solution() {
part2(input, 92148721834692)
}
fun part1(input: String, expected: Long) {
val output = day.part1(input)
println("output: $output")
assert(output == expected)
}
fun part2(input: String, expected: Long) {
val output = day.part2(input)
println("output: $output")
assert(output == expected)
}
}