diff options
Diffstat (limited to 'challenge-074')
| -rw-r--r-- | challenge-074/cheok-yin-fung/perl/ch-1.pl | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/challenge-074/cheok-yin-fung/perl/ch-1.pl b/challenge-074/cheok-yin-fung/perl/ch-1.pl new file mode 100644 index 0000000000..feb190e26c --- /dev/null +++ b/challenge-074/cheok-yin-fung/perl/ch-1.pl @@ -0,0 +1,54 @@ +#!/usr/bin/perl +# ref: +# https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm +# Perl Weekly Challenge #074 Task 1 Majority Element +# task statement: +# Write a script to find the majority element. +# If none found then print -1. +# Usage: ch-1.pl [ARRAY] +use strict; +use warnings; +#use Test::More tests => 3; + + +sub verify { + my @array = @{$_[0]}; + my $m = $_[1]; + my $c = 0; + for (@array) { + if ($m==$_) { + $c++; + } + } + return ($c > (scalar @array)/2.0 ? 1 : undef); +} + +sub bm_majority_vote_alg { + my @array = @{$_[0]}; + my $i = 0; + my $m; + for (@array) { + if ($i == 0) { + $m = $_; + $i++ + } + elsif ($m == $_) { + $i++; + } + else { + $i--; + } + } + + + return ( verify(\@array, $m) ? $m : -1 ); +} + + +print bm_majority_vote_alg(\@ARGV); + +=pod +is_deeply( bm_majority_vote_alg( [1, 2, 2, 3, 2, 4, 2] ) , "2", "example1 provided"); +is_deeply( bm_majority_vote_alg( [1, 3, 1, 2, 4, 5] ) , "-1", "example2 provided"); +is_deeply( bm_majority_vote_alg( [2, 2, 2, 3, 1, 3, 4] ) , "-1", "array: 2223134"); +=cut |
