summaryrefslogtreecommitdiff
path: root/5.pl
diff options
context:
space:
mode:
Diffstat (limited to '5.pl')
-rw-r--r--5.pl49
1 files changed, 49 insertions, 0 deletions
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<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;
+}