From ace8b9fce16eac6cb23f848f0392f5288026ddfb Mon Sep 17 00:00:00 2001 From: drbaggy Date: Tue, 29 Jun 2021 07:13:31 +0100 Subject: tidied up object code - and fixed index code to be shorter --- challenge-119/james-smith/perl/ch-2.pl | 49 +++++++++++----------------------- 1 file changed, 15 insertions(+), 34 deletions(-) diff --git a/challenge-119/james-smith/perl/ch-2.pl b/challenge-119/james-smith/perl/ch-2.pl index ffa5b6c22f..a99e0de0a5 100644 --- a/challenge-119/james-smith/perl/ch-2.pl +++ b/challenge-119/james-smith/perl/ch-2.pl @@ -10,11 +10,10 @@ use Data::Dumper qw(Dumper); my @TESTS = ( [5,13],[10,32],[60,2223] ); -is( no_11_fr($_->[0]), $_->[1] ) foreach @TESTS; -is( no_11_filter($_->[0]), $_->[1] ) foreach @TESTS; -is( no_11_filter_regex($_->[0]), $_->[1] ) foreach @TESTS; -is( no_11_array( $_->[0]), $_->[1] ) foreach @TESTS; -is( no_11_object( $_->[0]), $_->[1] ) foreach @TESTS; +is( no_11_filter( $_->[0] ), $_->[1] ) foreach @TESTS; +is( no_11_filter_regex( $_->[0] ), $_->[1] ) foreach @TESTS; +is( no_11_array( $_->[0] ), $_->[1] ) foreach @TESTS; +is( no_11_object( $_->[0] ), $_->[1] ) foreach @TESTS; cmpthese(10_000,{ 'filter' => sub { no_11_filter($_->[0]) foreach @TESTS; }, @@ -45,25 +44,13 @@ sub no_11_filter { while(1){ return $v unless $n; $v++; - $n-- if 0 > index( $v,'4') - && 0 > index( $v,'0') - && 0 > index( $v,'5') - && 0 > index( $v,'6') - && 0 > index( $v,'7') - && 0 > index( $v,'8') - && 0 > index( $v,'9') - && 0 > index( $v,'11'); - } -} -sub no_11_fr { - my $n = shift; - my $v = 0; - while(1) { - return $v unless $n; - $v++; - $n-- if $v =~ m{\A(?:12|13|2|3)*1?\Z}; + $n-- if 0 > index( $v,'0') && 0 > index( $v,'4') + && 0 > index( $v,'5') && 0 > index( $v,'6') + && 0 > index( $v,'7') && 0 > index( $v,'8') + && 0 > index( $v,'9') && 0 > index( $v,'11'); } } + sub no_11_filter_regex { my $n = shift; my $v = 0; @@ -88,28 +75,22 @@ use overload '++' => 'incr'; use overload '""' => 'str'; sub new { - my $x = []; - bless $x, 'Three'; - return $x; + return bless [], 'Three'; } sub has_double_one { -## Does number contain "11" - my($f,@v) = @{$_[0]}; - while(@v) { - return 1 if $f == 1 && $v[0] == 1; - $f = shift @v; - } + ## Does number contain "11" + my( $f, @v ) = @{$_[0]}; + ( $f == 1 && $v[0] == 1 ) ? ( return 1 ) : ( $f = shift @v ) while @v; return 0; } sub incr { ## Override for "++" get next element in sequence - my $v = shift; - my $ptr = -1; + my($v,$ptr) = (shift,-1); ## This is just a case of adding 1 to the last number ## and rolling carries... - for( $ptr = @{$v}-1; $ptr>-1 && ++$v->[$ptr]>3; $ptr--) { + for( $ptr = $#$v; $ptr>-1 && ++$v->[$ptr]>3; $ptr--) { $v->[$ptr]=1; } ## And finally add a "1" to the start if we have rolled -- cgit