Skip to content

Commit 98e3486

Browse files
committed
feat: day 3 part 2
1 parent 77cacd1 commit 98e3486

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

day03.sc

+30-12
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,41 @@ import common.loadPackets
33
val input = loadPackets(List("day03.txt"))
44
.map(_.split("").map(_.toInt))
55

6-
val frequencies = input.head.indices
7-
.map(i =>
8-
input.map(_.apply(i))
6+
def frequencies: List[Array[Int]] => IndexedSeq[Map[Int, Int]] =
7+
rows => rows.head.indices.map(i =>
8+
rows.map(_.apply(i))
99
.groupBy(x => x)
1010
.view
1111
.mapValues(_.size)
1212
.toMap)
1313

1414
def toInteger(bits: Seq[Int]): Int = bits
15-
.reverse
16-
.zipWithIndex
17-
.map {
18-
case (0, _) => 0
19-
case (_, index) => Math.pow(2, index).toInt
20-
}.sum
15+
.reverse
16+
.zipWithIndex
17+
.map {
18+
case (0, _) => 0
19+
case (_, index) => Math.pow(2, index).toInt
20+
}.sum
2121

22-
val gammaRate = toInteger(frequencies.map(x => x.maxBy(_._2)._1))
23-
val epsilonRate = toInteger(frequencies.map(x => x.minBy(_._2)._1))
22+
val mostCommon = frequencies(input).map(x => x.maxBy(_._2)._1)
23+
val gammaRate = toInteger(mostCommon)
24+
val leastCommon = frequencies(input).map(x => x.minBy(_._2)._1)
25+
val epsilonRate = toInteger(leastCommon)
2426

25-
val part1 = gammaRate * epsilonRate
27+
val part1 = gammaRate * epsilonRate
28+
29+
val filterRows: (Int, List[Array[Int]], List[Array[Int]] => IndexedSeq[Int]) => Array[Int] = {
30+
case (_, rows, _) if rows.size == 1 => rows.head
31+
case (index, rows, bits) => filterRows(
32+
index + 1,
33+
rows.filter(row => row(index) == bits(rows)(index)),
34+
bits
35+
)
36+
}
37+
38+
val oxygenGeneratorRating = toInteger(filterRows(0, input,
39+
rows => frequencies(rows).map(x => if (x.getOrElse(0, 0) == x.getOrElse(1, 0)) 1 else x.maxBy(_._2)._1)))
40+
val co2Rating = toInteger(filterRows(0, input,
41+
rows => frequencies(rows).map(x => if (x.getOrElse(0, 0) == x.getOrElse(1, 0)) 0 else x.minBy(_._2)._1)))
42+
43+
val part2 = oxygenGeneratorRating * co2Rating

0 commit comments

Comments
 (0)