From 2664d8150b7c772e05cde6b87b7700f2dc2865b4 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Tue, 7 Dec 2021 10:04:40 +0100 Subject: [PATCH] 7 --- 2021/07/README.md | 13 ++++++++++ 2021/07/python/main.py | 58 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 2021/07/README.md create mode 100644 2021/07/python/main.py diff --git a/2021/07/README.md b/2021/07/README.md new file mode 100644 index 0000000..fbba1cf --- /dev/null +++ b/2021/07/README.md @@ -0,0 +1,13 @@ +# 07 + +The first ist quite east, just find the median, and then calculate cost. + +For the second exercise we need triangle numbers. And the median won't work anymore. + +
+ Solutions +
    +
  1. 349769
  2. +
  3. 99540554
  4. +
+
diff --git a/2021/07/python/main.py b/2021/07/python/main.py new file mode 100644 index 0000000..05def8d --- /dev/null +++ b/2021/07/python/main.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +from os.path import join, dirname + +# Day 07 + +# Common + + +def read_input(filename): + data = join(dirname(__file__), '..', filename) + with open(data) as f: + return f.read().strip() + + +test = read_input('test.txt') +data = read_input('input.txt') + +# 1 + + +def get_cheapest_alignment(raw: str) -> int: + crabs = [int(x) for x in raw.split(',')] + median = sorted(crabs)[len(crabs) // 2] + costs = [abs(x - median) for x in crabs] + return sum(costs) + + +print('1.') +result = get_cheapest_alignment(test) +print(result) +result = get_cheapest_alignment(data) +print(result) + +# 2 + + +def triangle_number(distance: int) -> int: + return distance * (distance + 1) // 2 + + +def get_cheapest_alignment_complex(raw: str) -> int: + crabs = [int(x) for x in raw.split(',')] + lower = min(crabs) + upper = max(crabs) + lowest = -1 + for target in range(lower, upper + 1): + cost = sum([triangle_number(abs(x - target)) for x in crabs]) + if lowest == -1 or cost < lowest: + lowest = cost + return lowest + + +print('2.') +result = get_cheapest_alignment_complex(test) +print(result) +result = get_cheapest_alignment_complex(data) +print(result)