Last active
March 19, 2021 13:13
-
-
Save sungkmi/e5803b637504e474b001b951915de5f4 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 sungkmi.aoc2020.day15 | |
case class State( | |
lastSpokenTurn: IndexedSeq[Int], | |
lastSpokenNumber: Int, | |
turn: Int, | |
) | |
extension (s: State) | |
def next: State = State( | |
lastSpokenTurn = s.lastSpokenTurn.updated(s.lastSpokenNumber, s.turn), | |
lastSpokenNumber = s.lastSpokenTurn(s.lastSpokenNumber) match | |
case 0 => 0 | |
case n => s.turn - n, | |
turn = s.turn + 1, | |
) | |
object State: | |
def withStartingNumbers(startingNumbers: Seq[Int], size: Int): State = State( | |
lastSpokenTurn = startingNumbers.init.zipWithIndex | |
.foldLeft(Vector.fill(size)(0)): | |
case (memory, (n, i)) => memory.updated(n, i + 1) | |
, | |
lastSpokenNumber = startingNumbers.last, | |
turn = startingNumbers.size, | |
) | |
def parse(s: String, size: Int): State = | |
State.withStartingNumbers(s.split(",").toSeq.map(_.toInt), size) | |
def solve(input: String, until: Int): Int = | |
@annotation.tailrec | |
def loop(state: State): State = | |
if state.turn >= until then state else loop(state.next) | |
loop(parse(input, until)).lastSpokenNumber | |
def solve1(input: String): Int = solve(input, 2020) | |
def solve2(input: String): Int = solve(input, 30000000) | |
@main def part1: Unit = | |
val ans = solve1(input) | |
println(ans) | |
@main def part2: Unit = | |
val ans = solve2(input) | |
println(ans) | |
lazy val input: String = "9,19,1,6,0,5,4" |
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 sungkmi.aoc2020.day15 | |
class Day15Test extends munit.FunSuite { | |
test("solve1") { | |
assertEquals(solve1("0,3,6"), 436) | |
assertEquals(solve1("1,3,2"), 1) | |
assertEquals(solve1("2,1,3"), 10) | |
assertEquals(solve1("1,2,3"), 27) | |
assertEquals(solve1("2,3,1"), 78) | |
assertEquals(solve1("3,2,1"), 438) | |
assertEquals(solve1("3,1,2"), 1836) | |
} | |
// test("solve2") { | |
// assertEquals(solve2("0,3,6"), 175594) | |
// assertEquals(solve2("1,3,2"), 2578) | |
// assertEquals(solve2("2,1,3"), 3544142) | |
// assertEquals(solve2("1,2,3"), 261214) | |
// assertEquals(solve2("2,3,1"), 6895259) | |
// assertEquals(solve2("3,2,1"), 18) | |
// assertEquals(solve2("3,1,2"), 362) | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment