Add solution for Day 1

This commit is contained in:
William Brawner 2022-12-01 09:20:06 -07:00
parent 384d4723e3
commit ea8f48dfe0

View file

@ -1,15 +1,51 @@
fun main() {
fun part1(input: List<String>): Int {
return input.size
var calories = 0
var maxCalories = 0
input.forEach {
if (it.isBlank()) {
if (calories > maxCalories) {
maxCalories = calories
}
calories = 0
} else {
calories += it.toInt()
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
return input.size
var calories = 0
var maxCalories = 0
var secondMaxCalories = 0
var thirdMaxCalories = 0
input.forEachIndexed { index, food ->
if (food.isBlank() || index == input.lastIndex) {
if (index == input.lastIndex) {
calories = food.toInt()
}
if (calories >= maxCalories) {
thirdMaxCalories = secondMaxCalories
secondMaxCalories = maxCalories
maxCalories = calories
} else if (calories >= secondMaxCalories) {
thirdMaxCalories = secondMaxCalories
secondMaxCalories = calories
} else if (calories > thirdMaxCalories) {
thirdMaxCalories = calories
}
calories = 0
} else {
calories += food.toInt()
}
}
return maxCalories + secondMaxCalories + thirdMaxCalories
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))