From ebc93485ccdf908c487a9539dc7b2aeb382a5466 Mon Sep 17 00:00:00 2001 From: Jamie Thompson Date: Sat, 2 Dec 2023 18:46:00 +0100 Subject: [PATCH] Update day02.md (#301) make parsing a bit more elegant --- docs/2023/puzzles/day02.md | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/docs/2023/puzzles/day02.md b/docs/2023/puzzles/day02.md index 37f7d07b5..5332b5621 100644 --- a/docs/2023/puzzles/day02.md +++ b/docs/2023/puzzles/day02.md @@ -47,15 +47,14 @@ Let's fill in the `parse` function as follows: ```scala def parseColors(pair: String): Colors = - val Array(count0, color0) = pair.split(" ") - Colors(color = color0, count = count0.toInt) + val (s"$value $name") = pair: @unchecked + Colors(color = name, count = value.toInt) def parse(line: String): Game = - val Array(game0, hands) = line.split(": "): @unchecked - val Array(_, id) = game0.split(" "): @unchecked - val hands0 = hands.split("; ").toList - val hands1 = hands0.map(_.split(", ").map(parseColors).toList) - Game(id = id.toInt, hands = hands1) + val (s"Game $id: $hands0") = line: @unchecked + val hands1 = hands0.split("; ").toList + val hands2 = hands1.map(_.split(", ").toList.map(parseColors)) + Game(id = id.toInt, hands = hands2) ``` #### Summary @@ -122,15 +121,14 @@ case class Game(id: Int, hands: List[List[Colors]]) type Summary = Game => Int def parseColors(pair: String): Colors = - val Array(count0, color0) = pair.split(" ") - Colors(color = color0, count = count0.toInt) + val (s"$value $name") = pair: @unchecked + Colors(color = name, count = value.toInt) def parse(line: String): Game = - val Array(game0, hands) = line.split(": "): @unchecked - val Array(_, id) = game0.split(" "): @unchecked - val hands0 = hands.split("; ").toList - val hands1 = hands0.map(_.split(", ").map(parseColors).toList) - Game(id = id.toInt, hands = hands1) + val (s"Game $id: $hands0") = line: @unchecked + val hands1 = hands0.split("; ").toList + val hands2 = hands1.map(_.split(", ").toList.map(parseColors)) + Game(id = id.toInt, hands = hands2) def solution(input: String, summarise: Summary): Int = input.linesIterator.map(parse andThen summarise).sum