|
| 1 | +package com.markkovari.adventofcode |
| 2 | + |
| 3 | +import scala.collection.immutable.HashMap |
| 4 | +import scala.io.Source |
| 5 | + |
| 6 | +@main def part1: Unit = println(s"The solution is ${firstResult}") |
| 7 | +@main def part2: Unit = println(s"The solution is ${secondResult}") |
| 8 | + |
| 9 | +val numbersAsStringsAndValues = |
| 10 | + HashMap[String, Int]( |
| 11 | + "one" -> 1, |
| 12 | + "two" -> 2, |
| 13 | + "three" -> 3, |
| 14 | + "four" -> 4, |
| 15 | + "five" -> 5, |
| 16 | + "six" -> 6, |
| 17 | + "seven" -> 7, |
| 18 | + "eight" -> 8, |
| 19 | + "nine" -> 9 |
| 20 | + ) |
| 21 | + |
| 22 | +private def stringStartsStringifiedDigit(text: String): Option[Int] = { |
| 23 | + numbersAsStringsAndValues |
| 24 | + .find { case (key, _) => text.startsWith(key) } |
| 25 | + .map { case (_, value) => value } |
| 26 | +} |
| 27 | + |
| 28 | +private val exampleFilename = "example_1" |
| 29 | +private val exampleFilename2 = "example_2" |
| 30 | +private val valuesFilename = "values" |
| 31 | + |
| 32 | +private val lines = |
| 33 | + Source.fromFile(s"./src/main/resources/1/${valuesFilename}").getLines |
| 34 | +private val linesForSecond = |
| 35 | + Source.fromFile(s"./src/main/resources/1/${valuesFilename}").getLines |
| 36 | + |
| 37 | +val firstResult = |
| 38 | + lines |
| 39 | + .map(line => getFirstAndLastMultipliedTen(getDigits(line))) |
| 40 | + .sum |
| 41 | + |
| 42 | +val secondResult = |
| 43 | + linesForSecond |
| 44 | + .map(line => getFirstAndLastMultipliedTen(getMixedUpDigits(line))) |
| 45 | + .sum |
| 46 | + |
| 47 | +private def getFirstAndLastMultipliedTen(list: List[Int]): Int = { |
| 48 | + list match { |
| 49 | + case a :: Nil => a * 10 + a |
| 50 | + case a :: b :: Nil => a * 10 + b |
| 51 | + case a :: b :: tail => a * 10 + tail.last |
| 52 | + case _ => 0 |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +def getMixedUpDigits(of: String): List[Int] = of match { |
| 57 | + case "" => List() |
| 58 | + case other => { |
| 59 | + stringStartsStringifiedDigit(other) match { |
| 60 | + case Some(value) => value :: getMixedUpDigits(other.splitAt(1)._2) |
| 61 | + case None => { |
| 62 | + val (head, tail) = other.splitAt(1) |
| 63 | + head.toIntOption match { |
| 64 | + case None => getMixedUpDigits(tail) |
| 65 | + case Some(_) => head.toInt :: getMixedUpDigits(tail) |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
| 72 | + |
| 73 | +def getDigits(of: String): List[Int] = of match { |
| 74 | + case "" => List() |
| 75 | + case a => { |
| 76 | + val (head, tail) = a.splitAt(1) |
| 77 | + head.toIntOption match { |
| 78 | + case None => getDigits(tail) |
| 79 | + case Some(_) => head.toInt :: getDigits(tail) |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments