diff --git a/src/day1/Puzzle2.scala b/src/day1/Puzzle2.scala new file mode 100644 index 0000000..4dea1a7 --- /dev/null +++ b/src/day1/Puzzle2.scala @@ -0,0 +1,61 @@ +package day1 + +import scala.io.{BufferedSource, Source} + +object Puzzle2 { + val DIGITS: Array[String] = Array( + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine" + ) + def loadInput(path: String): Int = { + var sum: Int = 0 + val source: BufferedSource = Source.fromFile(path) + for (line: String <- source.getLines()) { + var a: Int = -1 + var b: Int = -1 + var i: Int = 0 + while (i < line.length) { + val c: Char = line(i) + var value: Int = -1 + if ('0' <= c && c <= '9') { + value = c - '0' + } else { + for (j: Int <- DIGITS.indices) { + val digit: String = DIGITS(j) + if (value == -1 && i < line.length - digit.length + 1) { + if (line.substring(i, i+digit.length) == digit) { + value = j+1 + if (a == -1) { + i += digit.length - 1 + } + } + } + } + } + if (value != -1) { + if (a == -1) { + a = value + } + b = value + } + + i += 1 + } + + sum += a*10 + b + } + source.close() + return sum + } + def main(args: Array[String]): Unit = { + val sum: Int = loadInput("res/day1/input1.txt") + println(s"sum = $sum") + } +} diff --git a/tests/day1/Puzzle1Tester.scala b/tests/day1/Puzzle1Test.scala similarity index 79% rename from tests/day1/Puzzle1Tester.scala rename to tests/day1/Puzzle1Test.scala index 91dbd95..afe128d 100644 --- a/tests/day1/Puzzle1Tester.scala +++ b/tests/day1/Puzzle1Test.scala @@ -2,7 +2,7 @@ package day1 import org.scalatest.funsuite.AnyFunSuite -class Puzzle1Tester extends AnyFunSuite { +class Puzzle1Test extends AnyFunSuite { test("Puzzle1.loadInput") { assert(Puzzle1.loadInput("tests_res/day1/input1.txt") == 142) } diff --git a/tests/day1/Puzzle2Test.scala b/tests/day1/Puzzle2Test.scala new file mode 100644 index 0000000..cf1687e --- /dev/null +++ b/tests/day1/Puzzle2Test.scala @@ -0,0 +1,11 @@ +package day1 + +import org.scalatest.funsuite.AnyFunSuite + +class Puzzle2Test extends AnyFunSuite { + + test("Puzzle2.loadInput") { + assert(Puzzle2.loadInput("tests_res/day1/input2.txt") == 281) + } + +} diff --git a/tests_res/day1/input2.txt b/tests_res/day1/input2.txt new file mode 100644 index 0000000..4316a6b --- /dev/null +++ b/tests_res/day1/input2.txt @@ -0,0 +1,7 @@ +two1nine +eightwothree +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen \ No newline at end of file