diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-11-26 09:02:58 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-26 09:02:58 +0000 |
| commit | 2f7d443e14eb43f029e44647ee7b0ae739fd0e1f (patch) | |
| tree | 10cf2cf105abbd92c0ca903459acd7f09e394126 | |
| parent | 7160c6fd2ad52dc7c7e117c1e59ff7de4821603e (diff) | |
| parent | 0b7b82018ea2351ea9e141ffcbc74595f277a83e (diff) | |
| download | perlweeklychallenge-club-2f7d443e14eb43f029e44647ee7b0ae739fd0e1f.tar.gz perlweeklychallenge-club-2f7d443e14eb43f029e44647ee7b0ae739fd0e1f.tar.bz2 perlweeklychallenge-club-2f7d443e14eb43f029e44647ee7b0ae739fd0e1f.zip | |
Merge pull request #7152 from drbaggy/master
updated with speed up
| -rw-r--r-- | challenge-192/james-smith/README.md | 16 | ||||
| -rw-r--r-- | challenge-192/james-smith/perl/ch-2.pl | 10 |
2 files changed, 26 insertions, 0 deletions
diff --git a/challenge-192/james-smith/README.md b/challenge-192/james-smith/README.md index 76dac905f8..e509b7da91 100644 --- a/challenge-192/james-smith/README.md +++ b/challenge-192/james-smith/README.md @@ -118,3 +118,19 @@ So first thing we do is work out the sum and see if it is divisible by the lengt Second is how to work out the number of steps. This is easier than you think. We only have to consider the case where we move numbers right to left or left to right, starting at the left. We are not bothered whether any number becomes negative. So (1) how much do we need to move? This is simply `$av - $A[$p]`. So we borrow it from the next number so `$A[$p+1] = $A[$p+1] - $av + $A[$p]` and the number of steps is just `abs($av-$A[$p])`. Giving the code above. + +### A minor optimization + +We can do away with the array - and just use a scalar for the "size" of the next bin - giving us: + +```perl +sub equal_dis2 { + my($av,$k,$f) = (0,0,$_[0]); + $av+=$_ for @_; + return -1 if $av%@_; + $av/=@_; + $k+=abs($av-$f),$f=$_[$_]-$av+$f for 1..$#_; + $k; +} +``` + diff --git a/challenge-192/james-smith/perl/ch-2.pl b/challenge-192/james-smith/perl/ch-2.pl index 36b2dc27dc..88e2152047 100644 --- a/challenge-192/james-smith/perl/ch-2.pl +++ b/challenge-192/james-smith/perl/ch-2.pl @@ -11,6 +11,7 @@ use Data::Dumper qw(Dumper); my @TESTS = ( [ [1,0,5], 4 ], [ [0,2,0],-1], [ [0,3,0], 2 ] ); is( equal_dis( @{$_->[0]} ), $_->[1] ) for @TESTS; +is( equal_dis2( @{$_->[0]} ), $_->[1] ) for @TESTS; done_testing(); sub equal_dis { @@ -21,3 +22,12 @@ sub equal_dis { $k+=abs($av-$_[0]),$_[1]-=$av-shift while @_>1; $k; } + +sub equal_dis2 { + my($av,$k,$f) = (0,0,$_[0]); + $av+=$_ for @_; + return -1 if $av%@_; + $av/=@_; + $k+=abs($av-$f),$f+=$_[$_]-$av,warn ">$_,$f,$k" for 1..$#_; + $k; +} |
