day 1 puzzle 2

This commit is contained in:
Louis Heredero 2023-12-01 09:41:15 +01:00
parent 0ce0be9a6d
commit ddbddcd743
4 changed files with 80 additions and 1 deletions

61
src/day1/Puzzle2.scala Normal file
View File

@ -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")
}
}

View File

@ -2,7 +2,7 @@ package day1
import org.scalatest.funsuite.AnyFunSuite import org.scalatest.funsuite.AnyFunSuite
class Puzzle1Tester extends AnyFunSuite { class Puzzle1Test extends AnyFunSuite {
test("Puzzle1.loadInput") { test("Puzzle1.loadInput") {
assert(Puzzle1.loadInput("tests_res/day1/input1.txt") == 142) assert(Puzzle1.loadInput("tests_res/day1/input1.txt") == 142)
} }

View File

@ -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)
}
}

View File

@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen