diff options
| author | E. Choroba <choroba@matfyz.cz> | 2023-07-31 21:53:47 +0200 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2023-07-31 21:53:47 +0200 |
| commit | 0c02cda6300b4f09f8139c5f8ebaf75fe546f02b (patch) | |
| tree | aa6bb397f7f5fdec1983085d34640c604ee7036f /challenge-228 | |
| parent | e511966ce2280dbedb2c916d9e6254708800639e (diff) | |
| download | perlweeklychallenge-club-0c02cda6300b4f09f8139c5f8ebaf75fe546f02b.tar.gz perlweeklychallenge-club-0c02cda6300b4f09f8139c5f8ebaf75fe546f02b.tar.bz2 perlweeklychallenge-club-0c02cda6300b4f09f8139c5f8ebaf75fe546f02b.zip | |
Add solutions to 228: Unique Sum & Empty Array by E. Choroba
Diffstat (limited to 'challenge-228')
| -rwxr-xr-x | challenge-228/e-choroba/perl/ch-1.pl | 18 | ||||
| -rwxr-xr-x | challenge-228/e-choroba/perl/ch-2.pl | 56 |
2 files changed, 74 insertions, 0 deletions
diff --git a/challenge-228/e-choroba/perl/ch-1.pl b/challenge-228/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..8bbd2f73d3 --- /dev/null +++ b/challenge-228/e-choroba/perl/ch-1.pl @@ -0,0 +1,18 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +use List::Util qw{ sum0 }; + +sub unique_sum(@int) { + my %seen; + ++$seen{$_} for @int; + return sum0(grep 1 == $seen{$_}, keys %seen) +} + +use Test::More tests => 3; + +is unique_sum(2, 1, 3, 2), 4, 'Example 1'; +is unique_sum(1, 1, 1, 1), 0, 'Example 2'; +is unique_sum(2, 1, 3, 4), 10, 'Example 3'; diff --git a/challenge-228/e-choroba/perl/ch-2.pl b/challenge-228/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..e37f5ab601 --- /dev/null +++ b/challenge-228/e-choroba/perl/ch-2.pl @@ -0,0 +1,56 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub empty_array(@int) { + my $steps = 0; + my @sorted = sort { $a <=> $b } @int; + while (@int) { + if ($sorted[0] == $int[0]) { + shift @sorted; + shift @int; + } else { + push @int, shift @int; + } + ++$steps; + } + return $steps +} + +use List::Util qw{ min }; +sub empty_array_min(@int) { + my $steps = 0; + while (@int) { + if (min(@int) == $int[0]) { + shift @int; + } else { + push @int, shift @int; + } + ++$steps; + } + return $steps +} + +use Test::More tests => 2 * 2 + 1; + +is empty_array(3, 4, 2), 5, 'Example 1'; +is empty_array(1, 2, 3), 3, 'Example 2'; +is empty_array_min(3, 4, 2), 5, 'Example 1 min'; +is empty_array_min(1, 2, 3), 3, 'Example 2 min'; + +use Benchmark qw{ cmpthese }; +my %input; +@input{ map int rand 50, 1 .. 50 } = (); +my @input = keys %input; + +is empty_array(@input), empty_array_min(@input), 'same'; +cmpthese(-3, { + min => sub { empty_array_min(@input) }, + sort => sub { empty_array(@input) }, +}); + +__END__ + Rate min sort +min 3297/s -- -39% +sort 5425/s 65% -- |
