From 9646029feaa07d3ad84b743de42ce57ae34004ad Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Mon, 4 Dec 2023 19:41:29 +0100 Subject: [PATCH] Day 4 - Solved --- days/04/part1.pl | 41 +++++++++++++++++++++++++++++++++++++++++ days/04/part2.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 days/04/part1.pl create mode 100644 days/04/part2.py diff --git a/days/04/part1.pl b/days/04/part1.pl new file mode 100644 index 0000000..d14c638 --- /dev/null +++ b/days/04/part1.pl @@ -0,0 +1,41 @@ +#!/usr/bin/env perl +use warnings; +use strict; +use List::Util; + +my $filename = "./data/input.txt"; + +open(FH, '<', $filename) or die $!; + +my $score = 0; +while () { + my $card = $_; + my $points = 0; + my @parts = split /:/, $card; + my @lists = split /\|/, $parts[1]; + my @winning = split ' ', $lists[0]; + my @numbers = split ' ', $lists[1]; + my @previous = (); + foreach my $number (@numbers) { + if ($number eq " ") { + print $_; + } + if ((List::Util::any { $_ eq $number } @winning) && (List::Util::all { $_ ne $number } @previous)) { + push(@previous, $number); + if ($points == 0) { + $points = 1; + } else { + $points *= 2; + } + # print $number . ", "; + } + } + #if ($points == 0) { + # print "no points" . "\n"; + #} else { + # print $points . " points\n"; + #} + $score += $points; +} + +print $score . "\n"; diff --git a/days/04/part2.py b/days/04/part2.py new file mode 100644 index 0000000..87bd6e7 --- /dev/null +++ b/days/04/part2.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +import queue + +with open("data/input.txt", "r") as f: + data = f.read() + +q = queue.Queue() + +def winning_copies(card): + lists = card.split(":")[1].split("|") + winning = lists[0].split() + numbers = lists[1].split() + matching = 0 + for number in numbers: + if number in winning: + matching += 1 + return matching + +cards = data.split("\n") +cards.remove("") +for i, card in enumerate(cards): + q.put((i, card)) + +counter = 0 +while not q.empty(): + i, card = q.get() + copies = winning_copies(card) + if copies > 0: + for j in range(1, copies+1): + copy = cards[i+j] + q.put((i+j, copy)) + counter += 1 + +print(counter)