diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-08-18 18:46:37 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-18 18:46:37 +0100 |
| commit | 508e81e421234181cff7b32f3363fcbbedf458eb (patch) | |
| tree | 082f7e32cae64c5c36ba8102671077ee067193d3 | |
| parent | 705ed43a5672c26fc43e1f761becace0de33a898 (diff) | |
| parent | f7b1ddbb311bb50ce1d642dd18401b5f2e846057 (diff) | |
| download | perlweeklychallenge-club-508e81e421234181cff7b32f3363fcbbedf458eb.tar.gz perlweeklychallenge-club-508e81e421234181cff7b32f3363fcbbedf458eb.tar.bz2 perlweeklychallenge-club-508e81e421234181cff7b32f3363fcbbedf458eb.zip | |
Merge pull request #2105 from choroba/ech074
Solve 074: Majority Element and FNR Character by E. Choroba
| -rwxr-xr-x | challenge-074/e-choroba/perl5/ch-1.pl | 26 | ||||
| -rwxr-xr-x | challenge-074/e-choroba/perl5/ch-2.pl | 29 |
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'; |
