DEV Community

DoctorLai
DoctorLai

Posted on

Avent of Code - Day 03 - Rucksack Reorganization

Advent of Code occurs at Dec 01 to 25 where each day, you will need to solve a puzzle. It is Festival and the problem statement is mostly related to Christmas.

Day 3 -Rucksack Reorganization

https://adventofcode.com/2022/day/3

image.png

Q1

file1 = open("0.txt", "r")
ans = 0

while True:
        line = file1.readline()
        if not line:
                break
        line = line.strip()
        if not line:
                break
        n = len(line)
        a, b = line[:n//2], line[n//2:]
        c = list((set(a) & set(b)))[0]
        if 'a' <= c <= 'z':
                ans += ord(c) - 97 + 1
        else:
                ans += ord(c) - 65 + 27

print(ans)
Enter fullscreen mode Exit fullscreen mode

Q2

file1 = open("0.txt", "r")
ans = 0

groups = []
while True:
        line = file1.readline()
        if not line:
                break
        line = line.strip()
        if not line:
                break
        groups.append(line)
        if len(groups) == 3:
                c = list(set(groups[0]) & set(groups[1]) & set(groups[2]))[0]
                if 'a' <= c <= 'z':
                        ans += ord(c) - 97 + 1
                else:
                        ans += ord(c) - 65 + 27
                groups = []

print(ans)
Enter fullscreen mode Exit fullscreen mode

Here is an interesting read: Check If N and Its Double Exist (Hash Map)


Steem to the Moon!

Top comments (0)