aoc-all

My solutions to all Advent of Code
git clone https://git.instinctive.eu/aoc-all.git
Log | Files | Refs | README | LICENSE

day03.nim (1522B)


      1 # Copyright (c) 2024, Natacha Porté
      2 #
      3 # Permission to use, copy, modify, and distribute this software for any
      4 # purpose with or without fee is hereby granted, provided that the above
      5 # copyright notice and this permission notice appear in all copies.
      6 #
      7 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      8 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      9 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     10 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     11 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     12 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     13 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     14 
     15 from std/re       import findAll, re
     16 from std/sequtils import foldl, map, toSeq
     17 from std/strutils import parseInt, split
     18 
     19 # Read input file
     20 
     21 let data = stdin.lines().toSeq()
     22 
     23 # Puzzle 1
     24 
     25 func summul(s: string): int =
     26   for subs in findAll(s, re"mul\(\d+,\d+\)"):
     27     let n = split(subs[4 .. ^2], ",").map(parseInt)
     28     result += foldl(n, a * b)
     29 
     30 echo "Puzzle 1: ", data.map(summul).foldl(a + b)
     31 
     32 # Puzzle 2
     33 
     34 func dosummul(s: string): int =
     35   var active = true
     36   for subs in findAll(s, re"mul\(\d+,\d+\)|do\(\)|don't\(\)"):
     37     case subs[0 .. 3]
     38     of "do()":
     39       active = true
     40     of "don'":
     41       active = false
     42     of "mul(":
     43       if active:
     44         result += subs[4 .. ^2].split(",").map(parseInt).foldl(a * b)
     45 
     46 echo "Puzzle 2: ", data.foldl(a & b).dosummul()