Day3.scala (1498B)
1 def day3_pt1(input: Iterator[String]): Int = 2 val line = input.next(); 3 List.range(0, line.size) 4 .flatMap(n => try_mul(line.substring(n))) 5 .sum 6 7 def day3_pt2(input: Iterator[String]): Int = 8 val line = input.next() 9 val (_, res) = List.range(0, line.size) 10 .foldLeft[(Boolean,Int)]((true, 0)) { (z: (Boolean, Int), n: Int) => 11 val (enabled, sum) = z 12 val l1 = line.substring(n) 13 if enabled then 14 if try_dont(l1) then 15 (false, sum) 16 else 17 (true, sum + try_mul(line.substring(n)).getOrElse(0)) 18 else 19 if try_do(l1) then 20 (true, sum) 21 else 22 (false, sum) 23 } 24 res 25 26 27 def try_do(s: String): Boolean = 28 return s.startsWith("do()") 29 30 def try_dont(s: String): Boolean = 31 return s.startsWith("don't()") 32 33 def try_mul(s: String): Option[Int] = 34 if s.startsWith("mul(") then 35 val ix = s.indexOf(")") 36 if ix > 0 then 37 val sl = s.substring(4,ix).split(",") 38 if sl.size == 2 && sl.forall(p => p.forall(c => c.isDigit)) && sl.forall(p => p.size >= 1 && p.size <= 3) then 39 val il = sl.map(p => Integer.parseInt(p)) 40 val i1 = il(0) 41 val i2 = il(1) 42 //println(s"mul($i1,$i2)") 43 Some(i1 * i2) 44 else 45 None 46 else 47 None 48 else 49 None