commit 28a0de7bbdbc5c77b0d35c106d030e097fa56690 (patch)
parent 94d6acb1df097d280e1405d008bc70da9156f374
Author: Alex Karle <alex@alexkarle.com>
Date: Tue, 7 Dec 2021 10:54:13 -0500
day7: Fix averaging in pt b -- round instead of floor
Without this, the example they give is slightly off:
16,1,2,0,4,2,7,1,2,14 -> 168
This intuitively makes sense, as the closest you can get to the average
is the round()!
Diffstat:
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/7/b.py b/7/b.py
@@ -9,14 +9,16 @@
# give us 3300 instead, which is significantly better.
import sys
+
def cost(a, b):
# Distance 3 = 1 + 2 + 3 = sum(range(abs)))
return sum(range(abs(a - b) + 1))
+
crabs = []
for l in sys.stdin:
crabs = [int(x) for x in l.split(",")]
-avg = int(sum(crabs) / len(crabs))
+avg = round(sum(crabs) / len(crabs))
print(sum([cost(x, avg) for x in crabs]))