-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bd95d40
commit f9ddc19
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import utils.AoCDay | ||
import utils.splitAndMapToLong | ||
|
||
class Day07 : AoCDay() { | ||
|
||
val equations = input.map { | ||
val parts = it.split(":") | ||
parts[0].toLong() to parts[1].splitAndMapToLong() | ||
} | ||
|
||
override fun part1(): Any { | ||
return equations.filter { solve(it.second, it.first) }.sumOf { it.first } | ||
} | ||
|
||
override fun part2(): Any { | ||
return equations.filter { solve(it.second, it.first, true) }.sumOf { it.first } | ||
} | ||
|
||
fun solve(numbers: List<Long>, target: Long, partB: Boolean = false): Boolean { | ||
if (numbers.size == 1) { | ||
return numbers.first() == target | ||
} | ||
if (numbers.first() > target) { | ||
return false | ||
} | ||
val unused = numbers.drop(2) | ||
val addition = mutableListOf(numbers[0] + numbers[1]) | ||
val multiplication = mutableListOf(numbers[0] * numbers[1]) | ||
addition.addAll(unused) | ||
multiplication.addAll(unused) | ||
val result = solve(addition, target, partB) || solve(multiplication, target, partB) | ||
|
||
if (!partB) { | ||
return result | ||
} | ||
|
||
val concat = mutableListOf("${numbers[0]}${numbers[1]}".toLong()) | ||
return result || solve(concat + unused, target, true) | ||
} | ||
} | ||
|
||
fun main() { | ||
Day07().execute() | ||
} |