day01.nim (1654B)
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/math import sum 16 from std/algorithm import sorted 17 from std/sequtils import map, zip 18 from std/strutils import parseInt, splitWhitespace 19 from std/tables import getOrDefault, toCountTable 20 21 # Read input file 22 23 func splitInt(line: string): seq[int] = 24 line.splitWhitespace().map(parseInt) 25 26 proc allLines(f: File): seq[string] = 27 var line: string 28 while readLine(f, line): 29 result.add(line) 30 31 let data = stdin.allLines().map(splitInt) 32 33 # First puzzle 34 35 func nth[T](n: int): proc(s: seq[T]): T {.noSideEffect.} = 36 proc(s: seq[T]): T {.noSideEffect.} = s[n] 37 38 let 39 line1 = data.map(nth[int](0)).sorted() 40 line2 = data.map(nth[int](1)).sorted() 41 42 func dist(l: (int, int)): int = abs(l[0] - l[1]) 43 44 echo "Puzzle 1: ", sum(zip(line1, line2).map(dist)) 45 46 # Second puzzle 47 48 let counts = toCountTable(line2) 49 50 echo "Puzzle 2: ", 51 sum(line1.map(proc (i: int): int = i * counts.getOrDefault(i)))