55 lines
1.1 KiB
Python
55 lines
1.1 KiB
Python
import shared
|
|
import itertools
|
|
import functools
|
|
from collections import defaultdict
|
|
|
|
|
|
# @shared.profile
|
|
def part1(rows):
|
|
left = []
|
|
right = []
|
|
for row in rows:
|
|
r = row.split()
|
|
left.append(int(r[0]))
|
|
right.append(int(r[1]))
|
|
left = list(sorted(left))
|
|
right = list(sorted(right))
|
|
pairs = list(zip(left,right))
|
|
diffs = []
|
|
for l, r in pairs:
|
|
diffs.append(abs(r - l))
|
|
print(sum(diffs))
|
|
|
|
|
|
# @shared.profile
|
|
def part2(rows):
|
|
left = []
|
|
right = []
|
|
for row in rows:
|
|
r = row.split()
|
|
left.append(int(r[0]))
|
|
right.append(int(r[1]))
|
|
right_hist = defaultdict(int)
|
|
for r in right:
|
|
right_hist[r] += 1
|
|
tot = 0
|
|
for l in left:
|
|
tot += l * right_hist[l]
|
|
print(tot)
|
|
|
|
|
|
def main():
|
|
rows = [row for row in shared.load_rows(1)]
|
|
with shared.elapsed_timer() as elapsed:
|
|
part1(rows)
|
|
print("🕒", elapsed())
|
|
|
|
rows = [row for row in shared.load_rows(1, True)]
|
|
with shared.elapsed_timer() as elapsed:
|
|
part2(rows)
|
|
print("🕒", elapsed())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|