From 28e71ae69e07d6e3b2fb2b6c952f4281fac374a6 Mon Sep 17 00:00:00 2001 From: James Smith Date: Fri, 25 Nov 2022 23:17:27 +0000 Subject: Update README.md --- challenge-192/james-smith/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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; +} +``` + -- cgit From 0b7b82018ea2351ea9e141ffcbc74595f277a83e Mon Sep 17 00:00:00 2001 From: James Smith Date: Fri, 25 Nov 2022 23:18:04 +0000 Subject: Update ch-2.pl --- challenge-192/james-smith/perl/ch-2.pl | 10 ++++++++++ 1 file changed, 10 insertions(+) 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; +} -- cgit