aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-228/e-choroba/perl/ch-1.pl18
-rwxr-xr-xchallenge-228/e-choroba/perl/ch-2.pl56
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% --