From ae583ef458dd44698f1743aead7b771fb410d282 Mon Sep 17 00:00:00 2001 From: Ailbhe Tweedie Date: Tue, 2 Apr 2019 18:16:12 +0200 Subject: 002-p5-02: document & clean-up script --- challenge-002/ailbhe-tweedie/perl5/ch-02.pl | 37 +++++++++++++++++++---------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/challenge-002/ailbhe-tweedie/perl5/ch-02.pl b/challenge-002/ailbhe-tweedie/perl5/ch-02.pl index 05826d4efc..84d904ee09 100755 --- a/challenge-002/ailbhe-tweedie/perl5/ch-02.pl +++ b/challenge-002/ailbhe-tweedie/perl5/ch-02.pl @@ -12,6 +12,8 @@ # # Test with: # > echo {0..99} | ./ch-02.pl to | awk '{print $3}' | ./ch-02.pl from +# +# TODO: add tests use strict; use warnings; @@ -20,6 +22,7 @@ use Data::Dump; use v5.10; +# TODO: split the string right here into an array and don't keep the $BASE variable my $BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXY"; exit 1 unless @ARGV == 1; @@ -47,45 +50,55 @@ exit 0; sub toBase35 { my $input = shift; + my @base = split "", $BASE; my @convert; - my $baseNum = @base; my $max = 0; + + # Figure out the highest power of the base we need by incrementing + # base^power until it is bigger than the input. The exponent we're + # looking for is 1 less. while (1) { - last unless $baseNum ** ++$max <= $input; + last unless @base ** ++$max <= $input; } + + # Figure out the number's place values in a similar way by subtracting + # base^power from the input until the input is smaller than the value + # we're subtracting from it. The place values are saved in the array @convert. while ($max > 0) { my $exp = $max - 1; - #print "$baseNum to the $exp is ", $baseNum ** $exp, " which is smaller than $input\n"; - my $pow = $baseNum ** $exp; - my $place = 0; + my $pow = @base ** $exp; + my $place; while ($pow <= $input) { $input -= $pow; $place++; - #print "input $input; place $place\n"; } push @convert, $place; $max--; } - #print "@convert: "; - #dd @convert; - #print "\n"; + + # Return our number in the new base, by indexing the @base array with + # the @convert array. + # TODO: figure out if this implict return is `bad style' my $output = join "", @base[@convert]; } sub fromBase35 { - my $input = shift; # APX + my $input = shift; - # create a hash converting a base35 alphanumeric character to a base10 value + # We create a hash converting an alphanumeric character in the new base to + # a base10 value + # TODO: move this out of the function my %hash; my @base = split "", $BASE; for my $i (0..@base-1) { $hash{$base[$i]} = $i; } - my @based = split "", $input; # (A, P, X) + my @based = split "", $input; # bad variable name my $max = @based - 1; my $output; + # TODO: A for loop would probably be more clear at this point. while ($max >= 0) { $output += ( @base ** $max ) * $hash{@based[@based - $max - 1]}; $max--; -- cgit