diff options
| author | Bob Lied <boblied+github@gmail.com> | 2024-03-29 11:50:53 -0500 |
|---|---|---|
| committer | Bob Lied <boblied+github@gmail.com> | 2024-03-29 11:50:53 -0500 |
| commit | b799acf6961c45e0cf7a7c18ef0104e6bd5ab8f6 (patch) | |
| tree | 30a2d610ca64558a5e08a5e6b1eb7460e546eb61 | |
| parent | 6011d27049b57999587539fa9e3276712553651c (diff) | |
| download | perlweeklychallenge-club-b799acf6961c45e0cf7a7c18ef0104e6bd5ab8f6.tar.gz perlweeklychallenge-club-b799acf6961c45e0cf7a7c18ef0104e6bd5ab8f6.tar.bz2 perlweeklychallenge-club-b799acf6961c45e0cf7a7c18ef0104e6bd5ab8f6.zip | |
OO variation ch-1.pl
| -rw-r--r-- | challenge-262/bob-lied/perl/ch-1.pl | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/challenge-262/bob-lied/perl/ch-1.pl b/challenge-262/bob-lied/perl/ch-1.pl index a040ad1f6f..01fe3e4b32 100644 --- a/challenge-262/bob-lied/perl/ch-1.pl +++ b/challenge-262/bob-lied/perl/ch-1.pl @@ -24,6 +24,45 @@ use v5.38; use builtin qw/true false/; no warnings "experimental::builtin"; +use feature 'class'; no warnings "experimental::class"; + +use List::Util qw/max/; + +class Bucket { + my $id = 0; + ADJUST { ++$id } + + field $name :param = "Bucket$id"; + field $condition :param = sub() { true }; + field $_count = 0; + + method contains($n) { + $_count++ if $condition->($n); + } + method count() { return $_count } +} + +class BucketCollection { + field @coll; + + method add($bucket) { push @coll, $bucket; return $self; } + + method place($n) { $_->contains($n) for @coll; return $self } + method biggestNum() { return List::Util::max map { $_->count } @coll } +} + +sub mpn(@ints) +{ + my $buckets = BucketCollection->new() + ->add( Bucket->new(name => "positive", condition => sub($n) { $n > 0 } ) ) + ->add( Bucket->new(name => "negative", condition => sub($n) { $n < 0 } ) ); + + $buckets->place($_) foreach @ints; + return $buckets->biggestNum(); +} + +say mpn(-3, 0, 1, 9, 11); + use Getopt::Long; my $Verbose = 0; my $DoTest = 0; @@ -33,6 +72,7 @@ exit(!runTest()) if $DoTest; say maxPosNeg(@ARGV); + sub maxPosNeg(@ints) { my ($pos, $neg) = (0, 0); @@ -44,14 +84,36 @@ sub maxPosNeg(@ints) return ( $pos > $neg ) ? $pos : $neg; } +# Return -1, 0, or 1 for negative, zero, or positive +sub sign($n) { return ( $n < 0 ? -1 : ( $n > 0 ? 1 : 0 ) ) } + +sub maxPN2(@ints) +{ + use List::Util qw/max/; + + my @range = ( 0, 0, 0 ); + + $range[ sign($_) ]++ foreach @ints; + + return max( @range[1,2] ); +} + sub runTest { use Test2::V0; + is( sign(-3), -1, "Sign negative"); + is( sign( 7), 1, "Sign positive"); + is( maxPosNeg(-3, 1, 2, -1, 3, -2, 4), 4, "Example 1"); is( maxPosNeg(-1, -2, -3, 1 ), 3, "Example 2"); is( maxPosNeg(1, 2 ), 2, "Example 3"); is( maxPosNeg(), 0, "Empty list"); + is( maxPN2(-3, 1, 2, -1, 3, -2, 4), 4, "Example 1"); + is( maxPN2(-1, -2, -3, 1 ), 3, "Example 2"); + is( maxPN2(1, 2 ), 2, "Example 3"); + is( maxPN2(), 0, "Empty list"); + done_testing; } |
