Advent of Code - Day 1 to Day 5

coding
Author

Kurian Benoy

Published

December 20, 2020

Advent of Code is a yearly contest for programming puzzles which is being held every year. I would like to thank Eric Wastl for making Advent of Code quite awesoeme.

PS: Spoilers ahead, please don’t read ahead if haven’t solved puzzles Day 1-5 already 🤞.

I would be trying to write and optimise my code for readability, and avoid use of any external libraries(except python standard library).

Day 1

## Part1
input = []
with open('input1.txt') as f:
    for k in f.readlines():
        input.append(int(k.strip()))

for i in input:
    for j in input:
            print(i,j)
            if (i+j)==2020:
                print(i*j)
                exit()  

## Part 2

for i in input:
    for j in input:
        for k in input:
            print(i,j,k)
            if (i+j+k)==2020:
                print(i*j*k)

The part 2 is super slow and takes a lot of time to run

day2

from collections import Counter

texts = []
valid = 0
with open('input/input2.txt') as f:
    for k in f.readlines():
        text = (k.split(':')[1]).strip()
        texts.append(text)
        a = k.split(':')[0]
        key = a.split()[1]
        ans = a.split()[0]
        start = a.split('-')[0]
        end = ans.split('-')[1]

        ans_counter = Counter(text)

        if int(start)<=ans_counter[key]<=int(end):
            # if (text[int(start)-1]==key)^(text[int(end-1]==key):
                valid += 1

    print(f"No of valid passwords: {valid}")

day3

lines = []

with open('input/input3.txt') as f:
    for data in f.readlines():
        lines.append(data)

print(len(lines), len(lines[0]))
SLOPES = [3, 1]
trees = 0
i,j = 0,0
l = 0
for _ in range(len(lines)-1):
    i = i +1
    j = j+3
    print(j%len(lines[i]))
    if lines[i][j%len(lines[i])-1]=="#":
        trees += 1

print("No of trees", trees)
## Part 2
import fileinput
from utils import aoc_timer

# def solution():
slopes = [(1,1), (3,1), (5,1), (7,1), (1,2)]

pattern = []
for line in fileinput.input("input/input3.txt"):
    pattern.append(list(line.strip()))

ans =1 
for (dc, dr) in slopes:
    r = 0
    c = 0
    score = 0
    while r< len(pattern):
        c += dc
        r += dr

        if r<len(pattern) and pattern[r][c%len(pattern[r])] == "#":
            score +=1 

    ans *= score

    print(f"Tree with slope:{dc,dr} with {score}")

print(f"part2 answer: {ans}")

day4

import re
from utils import aoc_timer

def textinput():
    with open("input/input4.txt") as file:
        line = [x.strip() for x in file.readlines()]
        return line

@aoc_timer(4,1,2020)
def solve_valid_passport(passport_dump):
    p1 = 0
    p2 = 0
    passport = {}
    count = 0
    
    for x in passport_dump:
        if x != "":
            for p in x.split():
                key, value = p.split(":")
                passport[key] = value
        else:
            count += 1
            valid = True

            for field in ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']:
                if field not in passport:
                    valid = False

            if valid:
                p1 +=1
            
            # print(f"Pass1: all fields {valid}")
            if not (1920<=int(passport['byr'])<=2002):
                valid = False
            
            if not (2010<=int(passport['iyr'])<=2020):
                valid = False

            if not (2020<=(int(passport['eyr']))<=2030):
                valid = False
             
            # print(passport['hgt']) # check for cm/inch

            if passport['hgt']:
                if passport['hgt'].endswith('cm'):
                    val = int(passport['hgt'][0:passport['hgt'].find('cm')])
                    if not (150<=val<=193):
                        valid = False

                elif passport['hgt'].endswith('in'):
                    val = int(passport['hgt'][0:passport['hgt'].find('in')])
                    if (val<59) and (val>76):
                        valid = False

            # print(f"Pass2 - height & eyr&byr&iry: {valid}")

            if(passport['ecl'] not in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']):
                valid = False

            if(passport['hcl'].startswith("#")==False) or (len(passport['hcl'])!=7):
                valid = False

            elif(passport['hcl'].startswith("#")==True):
                p = re.compile("[0-9a-f]")
                if p.match(passport['hcl'].strip("#"))==None:
                    valid =False

            # print(f"Pass3 - after Eye colour & Hair colour:{valid}")
            pid = passport['pid']
            if len(pid) != 9 or any([c not in '0123456789' for c in pid]):
                valid = False
            # print(f"Pass4 - after pid:{valid}")
            if valid:
                p2 += 1
    print("Answer:1", p1)
    print("Answer: 2", p2)
    
    return p1,p2


if __name__ == "__main__":
    passport_dump = textinput()
    print(solve_valid_passport(passport_dump))

Day 5

import fileinput
from utils import aoc_timer


def seat_matrix_transform(seat_matrix):
    seat_ids = []
    for seat in seat_matrix:
        b1 = str.replace(seat[:7], "F", "0")
        b2 = str.replace(b1, "B", "1")
        row = int(b2, 2)

        b3 = str.replace(seat[7:], "R", "1")
        b4 = str.replace(b3, "L", "0")
        col = int(b4, 2)

        seatid = row * 8 + col
        seat_ids.append(seatid)

    return seat_ids


@aoc_timer(day=5, part=1, year=2020)
def solve1():
    seat_matrix = list(x.strip("\n") for x in fileinput.input("input/input5.txt"))
    seat_ids = seat_matrix_transform(seat_matrix)
    print("Maximum seat id:", max(seat_ids))


@aoc_timer(day=5, part=2, year=2020)
def solve_part2():
    seat_matrix = list(x.strip("\n") for x in fileinput.input("input/input5.txt"))
    seat_ids = seat_matrix_transform(seat_matrix)
    # print(seat_ids)
    seat_ids.sort()

    for i, d in enumerate(seat_ids):
        if(seat_ids[i]-seat_ids[i-1]==2):
            print("Our seat", d-1)




if __name__ == "__main__":
    solve1()
    solve_part2()