aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2020-08-18 19:22:31 +0200
committerE. Choroba <choroba@matfyz.cz>2020-08-18 19:22:31 +0200
commitf7b1ddbb311bb50ce1d642dd18401b5f2e846057 (patch)
tree082f7e32cae64c5c36ba8102671077ee067193d3
parent705ed43a5672c26fc43e1f761becace0de33a898 (diff)
downloadperlweeklychallenge-club-f7b1ddbb311bb50ce1d642dd18401b5f2e846057.tar.gz
perlweeklychallenge-club-f7b1ddbb311bb50ce1d642dd18401b5f2e846057.tar.bz2
perlweeklychallenge-club-f7b1ddbb311bb50ce1d642dd18401b5f2e846057.zip
Solve 074: Majority Element and FNR Character by E. Choroba
-rwxr-xr-xchallenge-074/e-choroba/perl5/ch-1.pl26
-rwxr-xr-xchallenge-074/e-choroba/perl5/ch-2.pl29
2 files changed, 55 insertions, 0 deletions
diff --git a/challenge-074/e-choroba/perl5/ch-1.pl b/challenge-074/e-choroba/perl5/ch-1.pl
new file mode 100755
index 0000000000..6506429d1a
--- /dev/null
+++ b/challenge-074/e-choroba/perl5/ch-1.pl
@@ -0,0 +1,26 @@
+#! /usr/bin/perl
+use warnings;
+use strict;
+
+# int can be used instead of floor as
+# floor($x) == int($x) for $x >= 0,
+# and size of an array can never be negative.
+
+sub majority_element {
+ my @arr = @_;
+ my %count;
+ for my $e (@arr) {
+ return $e if ++$count{$e} > int(@arr / 2);
+ }
+ return -1
+}
+
+use Test::More tests => 2;
+
+is majority_element(1, 2, 2, 3, 2, 4, 2),
+ 2,
+ 'example 1';
+
+is majority_element(1, 3, 1, 2, 4, 5),
+ -1,
+ 'example 2';
diff --git a/challenge-074/e-choroba/perl5/ch-2.pl b/challenge-074/e-choroba/perl5/ch-2.pl
new file mode 100755
index 0000000000..05055a1061
--- /dev/null
+++ b/challenge-074/e-choroba/perl5/ch-2.pl
@@ -0,0 +1,29 @@
+#! /usr/bin/perl
+use warnings;
+use strict;
+
+sub fnr_character {
+ my ($s) = @_;
+ my $r;
+ my %count;
+ my @order;
+ for my $i (0 .. length($s) - 1) {
+ my $ch = substr $s, $i, 1;
+ my $first;
+ if (1 == ++$count{$ch}) {
+ unshift @order, $first = $ch;
+ } else {
+ $first = '#';
+ for my $o (@order) {
+ $first = $o, last if 1 == $count{$o};
+ }
+ }
+ $r .= $first;
+ }
+ return $r
+}
+
+use Test::More tests => 2;
+
+is fnr_character('ababc'), 'abb#c', 'example 1';
+is fnr_character('xyzzyx'), 'xyzyx#', 'example 2';