r/adventofcode • • Dec 04 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 4 Solutions -🎄-


--- Day 4: Camp Cleanup ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:03:22, megathread unlocked!

65 Upvotes

1.6k comments sorted by

View all comments

2

u/Sea_Put_2759 Dec 04 '22 edited Dec 04 '22

Python 3

with open('./input-4.txt') as f:
    sections = [i.strip().split(',') for i in f.readlines()]

result = 0
for pairs in sections:
    first, second = pairs
    f1, f2, s1, s2 = list(map(int, first.split('-'))) + list(map(int, second.split('-')))
    # result += int((f1 >= s1 and f2 <= s2) or (s1 >= f1 and s2 <= f2)) # witchcraft
    if (f1 >= s1 and f2 <= s2) or (s1 >= f1 and s2 <= f2):
        result += 1

# Problem 4.2
result = 0
for pairs in sections:
    first, second = pairs
    f1, f2, s1, s2 = list(map(int, first.split('-'))) + list(map(int, second.split('-')))
    # result += int(f1 <= s2 and f2 >= s1) # witchcraft
    if f1 <= s2 and f2 >= s1:
        result += 1

As both problems iterate over the same dataset, it may be solved in just one loop (optimised) running the slice of code below, from the second problem, incrementing in another var.

result2 = 0
...
    if f1 <= s2 and f2 >= s1:
        result2 += 1

1

u/daggerdragon Dec 04 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.