From 1af52e0bc147a86348636f39f9826e50b889b9d9 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 7 Dec 2021 07:22:57 +0000 Subject: day 7: nim --- d7.nim | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 d7.nim diff --git a/d7.nim b/d7.nim new file mode 100644 index 0000000..536897d --- /dev/null +++ b/d7.nim @@ -0,0 +1,35 @@ +import std/algorithm, std/os, std/sugar, std/strutils, std/math + +proc read_crabs(filename: string): seq[int] = + let f = open(filename) + defer: f.close() + result = collect: + for crab in f.read_all().split(','): + parse_int(crab.strip()) + +func part1(crabs: seq[int]): int = + let median = sorted(crabs)[len(crabs) div 2] + for crab in crabs: + result += abs(crab - median) + +func part2_fuel(crabs: seq[int], pos: int): int = + for crab in crabs: + let dist = abs(crab - pos) + result += dist * (dist + 1) div 2 + +func part2(crabs: seq[int]): int = + let + l = len(crabs) + s = sum(crabs) + var c = 0 + for crab in crabs: + if crab * l > s: inc c + return part2_fuel(crabs, (s + c) div l) + +when is_main_module: + var filename: string = "7.in" + if param_count() == 1: + filename = param_str(1) + let crabs = read_crabs(filename) + echo part1(crabs) + echo part2(crabs) -- cgit v1.2.3-54-g00ecf