diff options
author | Christian Segundo | 2024-12-05 12:41:57 +0100 |
---|---|---|
committer | Christian Segundo | 2024-12-05 12:41:57 +0100 |
commit | 25f7a5e5bc80c699d9538aed0d3f31b9406e0a74 (patch) | |
tree | ae46b552dd1ea048410cf486d151f96355fe56af /5.pl | |
parent | 773b37cfb0211a65d3a05bc60b7b70e79db5b881 (diff) | |
download | advent-of-code-2024-25f7a5e5bc80c699d9538aed0d3f31b9406e0a74.tar.gz |
add day 5
Diffstat (limited to '5.pl')
-rw-r--r-- | 5.pl | 49 |
1 files changed, 49 insertions, 0 deletions
@@ -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<scalar @$updates; $x++) { + if (in_order($ordering_rules, $updates->[$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<scalar @$j; $x++) { + for(my $z=0; $z<scalar @$i; $z++) { + return 0 if @{$i->[$z]}[0] eq $j->[$x] and @{$i->[$z]}[1] eq $j->[$k]; + } + } + + return 1; +} |