aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Barrett <john@jbrt.org>2019-04-01 23:05:45 +0100
committerJohn Barrett <john@jbrt.org>2019-04-01 23:05:45 +0100
commitb6d10413a6a81c95f44ba5df5fbf5284e8ed1f7f (patch)
treed454c1e519e782ac4eff71c0628f50f04a2d8f75
parentf572002dfb9a3a01778dbecbfa44a22c5198a325 (diff)
downloadperlweeklychallenge-club-b6d10413a6a81c95f44ba5df5fbf5284e8ed1f7f.tar.gz
perlweeklychallenge-club-b6d10413a6a81c95f44ba5df5fbf5284e8ed1f7f.tar.bz2
perlweeklychallenge-club-b6d10413a6a81c95f44ba5df5fbf5284e8ed1f7f.zip
From base35
-rwxr-xr-xchallenge-002/john-barrett/perl5/ch-2.pl19
1 files changed, 16 insertions, 3 deletions
diff --git a/challenge-002/john-barrett/perl5/ch-2.pl b/challenge-002/john-barrett/perl5/ch-2.pl
index 3293529824..f18215e4f0 100755
--- a/challenge-002/john-barrett/perl5/ch-2.pl
+++ b/challenge-002/john-barrett/perl5/ch-2.pl
@@ -2,7 +2,7 @@
use strict;
use warnings;
-use feature 'say';
+use feature qw/ say /;
# Usage, e.g.
# ./ch-2.pl -to-base35 123
@@ -13,7 +13,21 @@ my @charset = ( 0..9, 'A'..'Y' );
my $base = @charset;
say to_base35( $args{'-to-base35'} ) if $args{'-to-base35'};
-#say to_base35( $args{'-to-base35'} ) if $args{'-to-base35'};
+say from_base35( $args{'-from-base35'} ) if $args{'-from-base35'};
+
+sub from_base35 {
+ my ( $base35 ) = @_;
+ my $sign = $base35 =~ s/-//g ? '-' : '';
+ my @digits = split '', $base35;
+ my $idx = join '', @charset;
+ my $pos = 0;
+ my $val;
+ while ( my $char = pop @digits ) {
+ $val += index( $idx, $char ) * ( $base ** $pos );
+ $pos++;
+ }
+ $sign . $val;
+}
sub to_base35 {
my ( $int ) = @_;
@@ -23,7 +37,6 @@ sub to_base35 {
do {
push @digits, $charset[ $int % $base ];
$int = int( $int / $base );
- say $int;
} while ( $int > 0 );
$sign . join '', reverse @digits;
}