Created
January 21, 2022 11:58
-
-
Save sungkmi/90ac32a0a27727e3a6b61f036c437281 to your computer and use it in GitHub Desktop.
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
package lascala.aoc2021.day1_10.day7 | |
def findMinCost(from: Int, to: Int, cost: Int => Int): Int = | |
val mid = (from + to) / 2 | |
val fromCost = cost(from) | |
val toCost = cost(to) | |
if (from + 1) >= to then (fromCost min toCost) | |
else if fromCost >= toCost then findMinCost(mid, to, cost) | |
else findMinCost(from, mid, cost) | |
def flatFuel(xs: IndexedSeq[Int])(x: Int): Int = | |
xs.map(_ - x).map(_.abs).sum | |
def incrementalFuel(xs: IndexedSeq[Int])(x: Int): Int = | |
xs.map(_ - x).map(_.abs).map(x => x * (x + 1) / 2).sum | |
def solve1(s: String): BigInt = | |
val xs = s.split(",").map(_.toInt).toIndexedSeq | |
findMinCost(xs.min, xs.max, flatFuel(xs)) | |
end solve1 | |
def solve2(s: String): BigInt = | |
val xs = s.split(",").map(_.toInt).toIndexedSeq | |
findMinCost(xs.min, xs.max, incrementalFuel(xs)) | |
end solve2 | |
@main def part1: Unit = | |
val ans = solve1(input) | |
println(ans) | |
@main def part2: Unit = | |
val ans = solve2(input) | |
println(ans) | |
val input = |
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
package lascala.aoc2021.day1_10.day7 | |
import minitest.SimpleTestSuite | |
import hedgehog.minitest.HedgehogSupport | |
import hedgehog.* | |
object Day7Test extends SimpleTestSuite with HedgehogSupport: | |
val testInput = """16,1,2,0,4,2,7,1,2,14""" | |
example("day7 - solve1") { | |
solve1(testInput) ==== 37 | |
} | |
example("day7 - solve2") { | |
solve2(testInput) ==== 168 | |
} | |
end Day7Test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment