From 25f7a5e5bc80c699d9538aed0d3f31b9406e0a74 Mon Sep 17 00:00:00 2001 From: Christian Segundo Date: Thu, 5 Dec 2024 12:41:57 +0100 Subject: add day 5 --- 5.pl | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 5.pl (limited to '5.pl') diff --git a/5.pl b/5.pl new file mode 100644 index 0000000..1c8db1a --- /dev/null +++ b/5.pl @@ -0,0 +1,49 @@ +#!/usr/bin/env perl + +$ordering_rules = []; +$updates = []; +open($fh, "5-input.txt") or die ; +while (<$fh>) { + chomp; + if (m/(\d+)\|(\d+)/) { push @$ordering_rules, [$1, $2]; } + elsif (m/^\d+,\d+/) { push @$updates, [split(/,/, $_)]; } +} +close($fh); + +$sum_no_order = 0; +$sum_order = 0; + +for($x=0; $x[$x])) { + $sum_no_order=$sum_no_order+@{$updates->[$x]}[scalar @{$updates->[$x]} / 2]; + } else { + @{$updates->[$x]} = sort { + foreach (@$ordering_rules) { + if ($_->[0] == $a and $_->[1] == $b) { return -1; } + elsif ($_->[1] == $a and $_->[0] == $b) { return 1; } + } + return 0; + } @{$updates->[$x]}; + $sum_order=$sum_order+@{$updates->[$x]}[scalar @{$updates->[$x]} / 2]; + } +} + +print "puzzle 1: $sum_no_order\n"; +print "puzzle 2: $sum_order\n"; + +sub in_order { + my ($i, $j) = @_; + for(my $k=0; $k < scalar @$j; $k++) { return 0 if not in_order_idx($i, $j, $k); } + return 1; +} + +sub in_order_idx { + my ($i, $j, $k) = @_; + for (my $x=$k+1; $x[$z]}[0] eq $j->[$x] and @{$i->[$z]}[1] eq $j->[$k]; + } + } + + return 1; +} -- cgit v1.2.3