From e9d5c7373130bb0785d6c7147e0dcbb05605db59 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Tue, 7 Dec 2021 10:34:10 +0100 Subject: [PATCH] 2021: d07: ex2: add solution --- 2021/d07/ex2/ex2.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100755 2021/d07/ex2/ex2.py diff --git a/2021/d07/ex2/ex2.py b/2021/d07/ex2/ex2.py new file mode 100755 index 0000000..2b01e78 --- /dev/null +++ b/2021/d07/ex2/ex2.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +import itertools +import sys +from math import ceil, floor +from typing import List, Tuple + + +def solve(input: List[str]) -> int: + def fuel(dist: int) -> int: + return dist * (dist + 1) // 2 + + nums = list(int(n) for n in input[0].split(",")) + mean = sum(nums) / len(nums) + + upper = sum(fuel(abs(n - ceil(mean))) for n in nums) + lower = sum(fuel(abs(n - floor(mean))) for n in nums) + + return min(upper, lower) + + +def main() -> None: + input = [line.strip() for line in sys.stdin.readlines()] + print(solve(input)) + + +if __name__ == "__main__": + main()