perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 386 - Task 1: Reverse Base

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-386/#TASK1
 3 #
 4 # Task 1: Reverse Base
 5 # ====================
 6 #
 7 # You are given a string representing a number, and an integer specifying the
 8 # base of that representation.
 9 #
10 # Write a function to convert this string to an integer. (For bases greater
11 # than 10, use characters A-Z, a-z, + and / in that order.)
12 #
13 ## Example 1
14 ##
15 ## Input: $num = "101010", $base = 2
16 ## Output: 42
17 #
18 ## Example 2
19 ##
20 ## Input: $num = "EEADEE", $base = 16
21 ## Output: 15642094
22 #
23 ## Example 3
24 ##
25 ## Input: $num = "755", $base = 8
26 ## Output: 493
27 #
28 ## Example 4
29 ##
30 ## Input: $num = "1BRJB", $base = 36
31 ## Output: 2228519
32 #
33 ## Example 5
34 ##
35 ## Input: $num = "7MyqL", $base = 64
36 ## Output: 123456789
37 #
38 #
39 ############################################################
40 ##
41 ## discussion
42 ##
43 ############################################################
44 #
45 # We create a list of possible digits. Then we calculate the number digit
46 # for digit:
47 # - multiply the current result by $base
48 # - look for the current character in the possible digits and add the
49 #   corresponding number to the result
50 # - we are done once we have handled all digits
51 #
52 
53 use v5.36;
54 
55 my $possible_digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\+/";
56 my @digits = split //, $possible_digits;
57 
58 reverse_base("101010", 2);
59 reverse_base("EEADEE", 16);
60 reverse_base("755", 8);
61 reverse_base("1BRJB", 36);
62 reverse_base("7MyqL", 64);
63 
64 sub reverse_base($num, $base) {
65     say "Input: \$num = \"$num\", \$base = $base";
66     my @num_digits = split //, $num;
67     my $result = 0;
68     foreach my $d (@num_digits) {
69         foreach my $idx (0..$#digits) {
70             if( $digits[$idx] eq $d ) {
71                 $result *= $base;
72                 $result += $idx;
73                 last;
74             }
75         }
76     }
77     say "Output: $result";
78 }