@@ -3,23 +3,41 @@ import common.loadPackets
3
3
val input = loadPackets(List (" day03.txt" ))
4
4
.map(_.split(" " ).map(_.toInt))
5
5
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))
9
9
.groupBy(x => x)
10
10
.view
11
11
.mapValues(_.size)
12
12
.toMap)
13
13
14
14
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
21
21
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)
24
26
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