From e88a8681653e202128234610384e74b42f62ed89 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Tue, 7 Dec 2021 10:09:52 -0600 Subject: [PATCH] Day 7 part 2 bruteforced --- 2021/seven.nim | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/2021/seven.nim b/2021/seven.nim index dce1e78..2763ff5 100644 --- a/2021/seven.nim +++ b/2021/seven.nim @@ -1,6 +1,9 @@ import std/[strutils, sequtils, tables, strformat] import ./common +proc f(n: int): int = toSeq(0..abs(n)).foldl(a + b, 0) + + proc crabsDistance(input: string): int = result = int.high() var max_try = 0 @@ -11,10 +14,22 @@ proc crabsDistance(input: string): int = let fuel = dists.foldl(a + abs(b - t), 0) if fuel < result: result = fuel +proc crabsBigDistance(input: string): int = + result = int.high() + var max_try = 0 + let dists = input.split(',').map(parseInt) + for d in dists: + if d > max_try: max_try = d + for t in 0..max_try: + let fuel = dists.foldl(a + f(b - t), 0) + if fuel < result: result = fuel + let input = 7.loadInputText() time("day 7 part 1"): echo input.crabsDistance() +time("day 7 part 2"): echo input.crabsBigDistance() # time("day 7 part 2"): echo "?" when not defined(release): let testInput = "16,1,2,0,4,2,7,1,2,14" doAssert testInput.crabsDistance() == 37 + doAssert testInput.crabsBigDistance() == 168