aoc-all

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

commit b7a2baf0e8efee1f2774ea4072e0b364645a5e9d
parent 8c887336f84a815fb7594fd1d9f6ed8256371d61
Author: Natasha Kerensikova <natgh@instinctive.eu>
Date:   Sun,  1 Dec 2024 09:15:58 +0000

Day 1 reference and solutions
Diffstat:
A2024/day01.nim | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
A2024/ref/day01.txt | 6++++++
2 files changed, 57 insertions(+), 0 deletions(-)

diff --git a/2024/day01.nim b/2024/day01.nim @@ -0,0 +1,51 @@ +# Copyright (c) 2024, Natacha Porté +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +from std/math import sum +from std/algorithm import sorted +from std/sequtils import map, zip +from std/strutils import parseInt, splitWhitespace +from std/tables import getOrDefault, toCountTable + +# Read input file + +func splitInt(line: string): seq[int] = + line.splitWhitespace().map(parseInt) + +proc allLines(f: File): seq[string] = + var line: string + while readLine(f, line): + result.add(line) + +let data = stdin.allLines().map(splitInt) + +# First puzzle + +func nth[T](n: int): proc(s: seq[T]): T {.noSideEffect.} = + proc(s: seq[T]): T {.noSideEffect.} = s[n] + +let + line1 = data.map(nth[int](0)).sorted() + line2 = data.map(nth[int](1)).sorted() + +func dist(l: (int, int)): int = abs(l[0] - l[1]) + +echo "Puzzle 1: ", sum(zip(line1, line2).map(dist)) + +# Second puzzle + +let counts = toCountTable(line2) + +echo "Puzzle 2: ", + sum(line1.map(proc (i: int): int = i * counts.getOrDefault(i))) diff --git a/2024/ref/day01.txt b/2024/ref/day01.txt @@ -0,0 +1,6 @@ +3 4 +4 3 +2 5 +1 3 +3 9 +3 3