From 8bdd97e3fea3291fbc5eea1f20cafb1a7624ab81 Mon Sep 17 00:00:00 2001 From: "Jan \"Yenya\" Kasprzak" Date: Tue, 20 Dec 2022 10:18:17 +0100 Subject: [PATCH] Day 20: alternative solution wit list of pairs - slower but prettier --- 2022/39.pl | 25 +++++++++++-------------- 2022/40.pl | 26 +++++++++++--------------- 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/2022/39.pl b/2022/39.pl index b60d35f..7f673d7 100755 --- a/2022/39.pl +++ b/2022/39.pl @@ -3,27 +3,24 @@ use v5.36; use strict; -chomp(my @list = <>); -my @perm = ( 0 .. $#list ); +my $i = 0; +my @list = map { chomp; [$i++, $_] } <>; for my $idx (0 .. $#list) { - my $move = $list[$idx]; - my $pos = 0; - $pos++ while $perm[$pos] != $idx; - splice(@perm, $pos, 1); - my $dst = ($pos + $move) % @perm; - splice(@perm, $dst, 0, $idx); + my $i = 0; + $i++ while $list[$i][0] != $idx; + my $item = splice @list, $i, 1; + my $dest = ($item->[1] + $i) % @list; + splice @list, $dest, 0, $item; } -my @ordered = map { $list[$perm[$_]] } 0 .. $#list; - -my $i = 0; -$i++ while $ordered[$i] != 0; +$i = 0; +$i++ while $list[$i][1] != 0; my $sum; for (1 .. 3) { $i += 1000; - $i %= @ordered; - $sum += $ordered[$i]; + $i %= @list; + $sum += $list[$i][1]; } say $sum; diff --git a/2022/40.pl b/2022/40.pl index b6e9ff4..5451455 100755 --- a/2022/40.pl +++ b/2022/40.pl @@ -4,30 +4,26 @@ use v5.36; use strict; my $key = 811589153; -my @list = map { $key * $_ } <>; -my @perm = ( 0 .. $#list ); +my $i = 0; +my @list = map { [$i++, $key * $_] } <>; for (1 .. 10) { for my $idx (0 .. $#list) { - my $move = $list[$idx]; - my $pos = 0; - $pos++ while $perm[$pos] != $idx; - splice(@perm, $pos, 1); - my $dst = ($pos + $move) % @perm; - splice(@perm, $dst, 0, $idx); + my $i = 0; + $i++ while $list[$i][0] != $idx; + my $item = splice @list, $i, 1; + my $dest = ($item->[1] + $i) % @list; + splice @list, $dest, 0, $item; } } -my @ordered = map { $list[$perm[$_]] } 0 .. $#list; - -my $i = 0; -$i++ while $ordered[$i] != 0; - +$i = 0; +$i++ while $list[$i][1] != 0; my $sum; for (1 .. 3) { $i += 1000; - $i %= @ordered; - $sum += $ordered[$i]; + $i %= @list; + $sum += $list[$i][1]; } say $sum; -- 2.43.5