From 0c02cda6300b4f09f8139c5f8ebaf75fe546f02b Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 31 Jul 2023 21:53:47 +0200 Subject: Add solutions to 228: Unique Sum & Empty Array by E. Choroba --- challenge-228/e-choroba/perl/ch-1.pl | 18 ++++++++++++ challenge-228/e-choroba/perl/ch-2.pl | 56 ++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100755 challenge-228/e-choroba/perl/ch-1.pl create mode 100755 challenge-228/e-choroba/perl/ch-2.pl 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% -- -- cgit