Commit f5992c2d authored by Germain Clavier's avatar Germain Clavier 😺
Browse files

Added solution to day 4

parent 43052b1a
Loading
Loading
Loading
Loading

2023/day4/code.py

0 → 100644
+78 −0
Original line number Diff line number Diff line
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''
Solutions for day 4 2023
'''

import time
import argparse as ap

class Card:
    def __init__(self, line):
        (label, full) = line.split(':')
        self.id = ''.join([x for x in filter(lambda y: y.isdigit(), label)])
        (win, num) = full.split('|')
        win, num = win.split(), num.split()
        win, num = set(win), set(num)
        self.res = len(win&num)
        self.points = int(2**(self.res-1))

def solve1(file=None, verbose=False, solution=0):
    # You don't even have to make a list and operate
    # on it, but this makes solution 1 more consistent
    # with solution 2.
    try:
        deck = []
        with open(file, 'r') as f:
            for line in f.readlines():
                card = Card(line)
                deck.append(card)
        solution = sum([x.points for x in deck])
    except FileNotFoundError:
        pass

    return solution

def solve2(file=None, verbose=False, solution=0):
    try:
        deck = []
        with open(file, 'r') as f:
            for line in f.readlines():
                card = Card(line)
                deck.append([card, 1])
        for i, (card, mult) in enumerate(deck):
            for j in range(1, card.res+1):
                deck[i+j][1] += deck[i][1]
        solution = sum([x[1] for x in deck])
    except FileNotFoundError:
        pass

    return solution

def main():
    parser = ap.ArgumentParser()
    parser.add_argument('-i', dest='input', action='store_true')
    parser.add_argument('-v', dest='verbose', action='store_true')
    args = parser.parse_args()
    infile = 'input' if args.input else 'test'
    verbose = args.verbose

    t0 = time.time()
    sol1 = solve1(infile, verbose)
    dt = time.time() - t0
    print(f"Solution 1: {sol1}, Time: {dt}")

    t0 = time.time()
    sol2 = solve2(infile, verbose)
    dt = time.time() - t0
    print(f"Solution 2: {sol2}, Time: {dt}")

    return


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        raise SystemExit("User interruption.")

2023/day4/input

0 → 100644
+199 −0

File added.

Preview size limit exceeded, changes collapsed.

2023/day4/test

0 → 100644
+6 −0
Original line number Diff line number Diff line
Card 1: 41 48 83 86 17 | 83 86  6 31 17  9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3:  1 21 53 59 44 | 69 82 63 72 16 21 14  1
Card 4: 41 92 73 84 69 | 59 84 76 51 58  5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11