aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2020-12-07 15:44:39 +0000
committerdrbaggy <js5@sanger.ac.uk>2020-12-07 15:44:39 +0000
commit3ba9a510b320260dda112c82a404c6b33c2958cd (patch)
treeda7902358b80b9a4f807e77857fcc190be324590
parentfd8e32585a0b9d3abcc7c22c3f30e19354a039ef (diff)
downloadperlweeklychallenge-club-3ba9a510b320260dda112c82a404c6b33c2958cd.tar.gz
perlweeklychallenge-club-3ba9a510b320260dda112c82a404c6b33c2958cd.tar.bz2
perlweeklychallenge-club-3ba9a510b320260dda112c82a404c6b33c2958cd.zip
added verbose mode to show workings
-rw-r--r--challenge-090/james-smith/perl/ch-2.pl23
1 files changed, 19 insertions, 4 deletions
diff --git a/challenge-090/james-smith/perl/ch-2.pl b/challenge-090/james-smith/perl/ch-2.pl
index 618a88f999..a8227b59f2 100644
--- a/challenge-090/james-smith/perl/ch-2.pl
+++ b/challenge-090/james-smith/perl/ch-2.pl
@@ -8,23 +8,38 @@ use Test::More;
## This is ripe for bit operators - as it is about multiplying/diving by 2...
## and checking for the value of the "1s" bit....
+#
+# To execute as a quiet test - use `perl ch-2.pl`
+#
+# To show workings run `perl ch-2.pl 1`
+my $flag = @ARGV && $ARGV[0] eq '1' ? 1 : 0;
foreach(1..10) {
- my $x = int rand(40);
- my $y = int rand(40);
- is( eth_mult( $x , $y ), $x*$y );
+ my $x = 100 + int rand(400);
+ my $y = 100 + int rand(400);
+ is( eth_mult( $x , $y, $flag ), $x*$y );
}
done_testing();
sub eth_mult {
- my( $n, $m ) = @_;
+ my( $n, $m, $verbose ) = @_;
+ $verbose ||= 0;
+ my $calc = $n*$m;
my $res = 0;
+ say q() if $verbose;
while($n) {
+ printf "%7d x %7d | %7s\n", $n, $m, $n&1 ? $m : q(.) if $verbose;
+ # The meat - use binary and
$res += $m if $n&1;
$m<<=1;
$n>>=1;
}
+ if( $verbose ) {
+ say q(------------------+--------);
+ printf " | %7d (%7d)\n", $res, $calc;
+ say q();
+ }
return $res;
}