Skip to content

Commit

Permalink
Finished 2024 day 7 both parts
Browse files Browse the repository at this point in the history
  • Loading branch information
tymscar committed Dec 7, 2024
1 parent cf6b27c commit e053d1d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
2 changes: 2 additions & 0 deletions 2024/kotlin/src/main/kotlin/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.tymscar.day03.solve as day03
import com.tymscar.day04.solve as day04
import com.tymscar.day05.solve as day05
import com.tymscar.day06.solve as day06
import com.tymscar.day07.solve as day07

fun main() {
day01()
Expand All @@ -14,4 +15,5 @@ fun main() {
day04()
day05()
day06()
day07()
}
17 changes: 16 additions & 1 deletion 2024/kotlin/src/main/kotlin/com/tymscar/day07/part1/part1.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package com.tymscar.day07.part1

private fun isValid(solution: Long, equation: List<Long>): Boolean {
if (equation.isEmpty()) return solution == 0L
val sumSolution = isValid(solution - equation.first(), equation.drop(1))
val multSolution =
if (solution % equation.first() == 0L) isValid(solution / equation.first(), equation.drop(1)) else false
return sumSolution || multSolution
}

fun solve(input: String): String {
return input
var equations = input.lines().map {
Regex("""(\d+)""").findAll(it).map { it.value.toLong() }.toList()
}

return equations
.filter { isValid(it.first(), it.drop(1).reversed()) }
.sumOf { it.first() }
.toString()
}
31 changes: 30 additions & 1 deletion 2024/kotlin/src/main/kotlin/com/tymscar/day07/part2/part2.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
package com.tymscar.day07.part2

import kotlin.math.floor
import kotlin.math.log10
import kotlin.math.pow

private fun deconcat(log: Long, splinter: Long): Long? {
val splinterSizeInHundreds = 10.0.pow(floor(log10(splinter.toDouble())) + 1).toLong()
val afterDeconcat: Long = log / splinterSizeInHundreds
return if ((afterDeconcat * splinterSizeInHundreds + splinter) == log) afterDeconcat else null
}

private fun isValid(solution: Long?, equation: List<Long>): Boolean {
if (solution == null) return false
if (equation.isEmpty()) return solution == 0L
val remainingEq = equation.drop(1)
val sumSolution = isValid(solution - equation.first(), remainingEq)
val multSolution =
if (solution % equation.first() == 0L) isValid(solution / equation.first(), remainingEq) else false
val concatSolution =
isValid(deconcat(solution, equation.first()), remainingEq)
return sumSolution || multSolution || concatSolution
}

fun solve(input: String): String {
return input
var equations = input.lines().map {
Regex("""(\d+)""").findAll(it).map { it.value.toLong() }.toList()
}

return equations
.filter { isValid(it.first(), it.drop(1).reversed()) }
.sumOf { it.first() }
.toString()
}

0 comments on commit e053d1d

Please sign in to comment.