Commit 77c85597 authored by Alexander Gehrke's avatar Alexander Gehrke
Browse files

[day2] solution + refactoring of day 1/main

parent e746f7ae
......@@ -15,11 +15,9 @@ sbt '++ 3.0.0-M1 publishLocal'
To run the code for a day:
```
sbt "run <input_dir> <day> <part>"
sbt "run <input_dir> <day>"
```
where
- `<input_dir>` is the path to a folder with AOC inputs named "day1.txt", "day2.txt", ...
Can be downloaded e.g. using [cargo-aoc](https://github.com/gobanos/cargo-aoc)
- `<day>` is the day to run
- `<part>` is either 1 or 2. Defaults to 1 if not given
1
where `<input_dir>` is the path to a folder with AOC inputs named "day1.txt", "day2.txt", ...
and `<day>` is the day to run.
Inputs can be downloaded e.g. using [cargo-aoc](https://github.com/gobanos/cargo-aoc) or of course manually.
def day1_1(input: List[Int]): Int =
input.groupWithSum(2020, groupSize = 2).product
def day1_2(input: List[Int]): Int =
input.groupWithSum(2020, groupSize = 3).product
def day1(input: List[Int]): String =
List(2, 3).map(groupSize => input.groupWithSum(2020, groupSize).product)
.mkString("\n")
extension (input: List[Int]) def groupWithSum(sum: Int, groupSize: Int = 2): List[Int] =
input.combinations(groupSize).filter(_.sum == sum).next
......
def day2(passwords: List[String]): String =
List(
passwords.count(validAmount),
passwords.count(validPositions)
).mkString("\n")
// part 1, password must contain given amount of character
def validAmount(passLine: String): Boolean =
val (min, max, char, pass) = parse(passLine)
(min to max) contains pass.count(_ == char)
// part 2, password must contain character at exactly one of the given positions
def validPositions(passLine: String): Boolean =
val (a, b, char, pass) = parse(passLine)
pass(a-1) == char ^ pass(b-1) == char
def parse(passLine: String): (Int, Int, Char, String) =
val s"$min-$max $char:$pass" = passLine
(min.toInt, max.toInt, char(0), pass)
@main def runDay(inputDir: String, day: Int, part: Int = 1): Unit =
@main def runDay(inputDir: String, day: Int): Unit =
val s = scala.io.Source.fromFile(s"${inputDir}/day${day}.txt").getLines
val out = (day, part) match {
case (1, 1) => day1_1(s.map(_.toInt).toList).toString
case (1, 2) => day1_2(s.map(_.toInt).toList).toString
val out = day match {
case 1 => day1(s.map(_.toInt).toList)
case 2 => day2(s.toList)
}
println(out)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment