diff options
| author | Fung Cheok Yin <61836418+E7-87-83@users.noreply.github.com> | 2020-08-19 10:24:43 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-19 10:24:43 +0800 |
| commit | 3a85a00c68fe0718ec916493826ea63e0f8a7066 (patch) | |
| tree | 2ff800bee5f112891e7effbdded474202c951567 /ch-1.pl | |
| parent | 00576254dae94b522130208c0ac3e19167827ddd (diff) | |
| download | perlweeklychallenge-club-3a85a00c68fe0718ec916493826ea63e0f8a7066.tar.gz perlweeklychallenge-club-3a85a00c68fe0718ec916493826ea63e0f8a7066.tar.bz2 perlweeklychallenge-club-3a85a00c68fe0718ec916493826ea63e0f8a7066.zip | |
Add files via upload
Diffstat (limited to 'ch-1.pl')
| -rw-r--r-- | ch-1.pl | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/ch-1.pl b/ch-1.pl new file mode 100644 index 0000000000..feb190e26c --- /dev/null +++ b/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 |
