diff options
| author | Lars Balker <balker@adapt.dk> | 2019-04-07 18:01:23 +0200 |
|---|---|---|
| committer | Lars Balker <balker@adapt.dk> | 2019-04-07 18:01:23 +0200 |
| commit | b4614546f7edf91b4aaca4f0a8762aac480a4eb3 (patch) | |
| tree | 0f3768ca50360c21c46b8312837b92181fda98cc | |
| parent | 08913a81f095479b2733bb3ff236d88497ae47e3 (diff) | |
| download | perlweeklychallenge-club-b4614546f7edf91b4aaca4f0a8762aac480a4eb3.tar.gz perlweeklychallenge-club-b4614546f7edf91b4aaca4f0a8762aac480a4eb3.tar.bz2 perlweeklychallenge-club-b4614546f7edf91b4aaca4f0a8762aac480a4eb3.zip | |
misread challenge 2, so left out half the solution!
| -rw-r--r-- | challenge-002/lars-balker/perl5/ch-2.pl | 30 | ||||
| -rw-r--r-- | challenge-002/lars-balker/perl6/ch-2.pl6 | 12 |
2 files changed, 36 insertions, 6 deletions
diff --git a/challenge-002/lars-balker/perl5/ch-2.pl b/challenge-002/lars-balker/perl5/ch-2.pl index 97846efdfb..393a66a152 100644 --- a/challenge-002/lars-balker/perl5/ch-2.pl +++ b/challenge-002/lars-balker/perl5/ch-2.pl @@ -5,20 +5,35 @@ use v5.10; use strict; use warnings; +my @glyphs = (0..9, 'A'..'Y'); + sub to_base35 { my $num = shift; my $res = ""; - my @val = (0..9, 'A'..'Y'); - do { - $res .= $val[$num % 35]; - $num = int($num / 35); + do { + $res .= $glyphs[$num % @glyphs]; + $num = int($num / @glyphs); } while $num; $res = reverse $res; $res; } +sub to_base10 { + my $num = shift; + my %val = map { $glyphs[$_] => $_ } 0 .. $#glyphs; + my $base = 1; + my $res = 0; + for my $char (reverse split //, $num) { + $res += $val{$char} * $base; + $base *= @glyphs; + } + $res; +} + if (@ARGV) { - say to_base35 shift; + my $num = shift; + say "base35($num) -> ", to_base35($num) unless $num =~ /\D/; + say "base10($num) -> ", to_base10($num); } else { eval "use Test::More"; @@ -27,5 +42,10 @@ else { is(to_base35(35), "10"); is(to_base35(1337), "137"); is(to_base35(20190401), "DFVXL"); + is(to_base10("0"), "0"); + is(to_base10("A"), "10"); + is(to_base10("10"), "35"); + is(to_base10("137"), "1337"); + is(to_base10("DFVXL"), "20190401"); done_testing(); } diff --git a/challenge-002/lars-balker/perl6/ch-2.pl6 b/challenge-002/lars-balker/perl6/ch-2.pl6 index 719b8cebc7..2cca57c3f8 100644 --- a/challenge-002/lars-balker/perl6/ch-2.pl6 +++ b/challenge-002/lars-balker/perl6/ch-2.pl6 @@ -8,8 +8,13 @@ sub to_base35(Int $num) { return $num.base(35); } +sub to_base10(Str $base35) { + return :35($base35); +} + multi sub MAIN($num) { - say to_base35($num); + say "base35($num) -> ", to_base35($num) unless $num ~~ /\D/; + say "base10($num) -> ", to_base10($num); } # kinda love this ARGV multi method dispatching in perl6 @@ -19,5 +24,10 @@ multi sub MAIN() { is(to_base35(35), "10"); is(to_base35(1337), "137"); is(to_base35(20190401), "DFVXL"); + is(to_base10("0"), "0"); + is(to_base10("A"), "10"); + is(to_base10("10"), "35"); + is(to_base10("137"), "1337"); + is(to_base10("DFVXL"), "20190401"); done-testing(); } |
