diff options
| author | E. Choroba <choroba@matfyz.cz> | 2023-03-27 22:44:35 +0200 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2023-03-27 22:44:35 +0200 |
| commit | d7023365540262ba297d70f52bff97caea7a97c5 (patch) | |
| tree | 4ca1a93a130476fd4bb01288821a38c8b7468102 | |
| parent | 8915a66de2cb2a724aee5e55ddfc15580cfdf1d5 (diff) | |
| download | perlweeklychallenge-club-d7023365540262ba297d70f52bff97caea7a97c5.tar.gz perlweeklychallenge-club-d7023365540262ba297d70f52bff97caea7a97c5.tar.bz2 perlweeklychallenge-club-d7023365540262ba297d70f52bff97caea7a97c5.zip | |
Add solutions to 210: Kill and Win & Number Collision by E. Choroba
| -rwxr-xr-x | challenge-210/e-choroba/perl/ch-1.pl | 14 | ||||
| -rwxr-xr-x | challenge-210/e-choroba/perl/ch-2.pl | 41 |
2 files changed, 55 insertions, 0 deletions
diff --git a/challenge-210/e-choroba/perl/ch-1.pl b/challenge-210/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..4603fed9c1 --- /dev/null +++ b/challenge-210/e-choroba/perl/ch-1.pl @@ -0,0 +1,14 @@ +#! /usr/bin/perl +use warnings; +use strict; + +# In the end, all the numbers must be exhausted (easy to prove by +# contradiction), so their total is just the sum of all the numbers. + +use Importer 'List::Util' => + sum => {-as => 'kill_and_win'}; + +use Test::More tests => 2; + +is kill_and_win(2, 3, 1), 6, 'Example 1'; +is kill_and_win(1, 1, 2, 2, 2, 3), 11, 'Example 2'; diff --git a/challenge-210/e-choroba/perl/ch-2.pl b/challenge-210/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..766b505064 --- /dev/null +++ b/challenge-210/e-choroba/perl/ch-2.pl @@ -0,0 +1,41 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +# What happens to zeroes? They don't move, but I interpret the rules +# in the following way: if any number tries to move into a zero, the +# zero explodes (see the additional tests). + +sub number_collision(@list) { + while (1) { + my $changed; + my @new = @list; + for (my $i = 0; $i <= $#list; ++$i) { + if ($list[$i] > 0 && $i < $#list && $list[ $i + 1 ] <= 0) { + @new[$i, $i + 1] = ( + undef, + (undef, @list[$i, $i + 1])[ + abs $list[$i] <=> abs $list[ $i + 1 ]]); + ++$i; + $changed = 1; + } elsif ($list[$i] == 0 && $i < $#list && $list[ $i + 1 ] < 0) { + @new[$i, $i + 1] = (undef, $list[ $i + 1 ]); + } + } + @list = grep defined, @new; + last unless $changed + } + return \@list +} + +use Test2::V0; +plan 3 + 3; + +is number_collision(2, 3, -1), [2, 3], 'Example 1'; +is number_collision(3, 2, -4), [-4], 'Example 2'; +is number_collision(1, -1), [], 'Example 3'; + +is number_collision(0, 0), [0, 0], 'Only zeroes'; +is number_collision(1, 0), [1], "Zeroes don't move positive"; +is number_collision(0, -1), [-1], "Zeroes don't move negative"; |
