Skip to content

Instantly share code, notes, and snippets.

@janlimpens
Created January 4, 2022 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janlimpens/3d53179d9f4dfd4733fb0863ee79e64a to your computer and use it in GitHub Desktop.
Save janlimpens/3d53179d9f4dfd4733fb0863ee79e64a to your computer and use it in GitHub Desktop.
package AreBelongToUs;
use strict;
use warnings;
# use feature 'signatures';
# use feature ':5.34';
use experimental qw(signatures);
## no critic (:signatures)
use Exporter qw<import>;
use Test2::V0;
my @alphanumerics =
qw(0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
sub index_of($dig) {
return index join('', @alphanumerics), $dig;
}
subtest index_of => sub {
is index_of(0), 0, 'zero';
is index_of('Z'), 35, 'z';
};
sub next_digit($curr_digit) {
my $idx = index_of($curr_digit) + 1;
$idx = $idx >= scalar @alphanumerics ? 0 : $idx;
return $alphanumerics[$idx];
}
subtest next_digit => sub {
is next_digit('A'), 'B', 'A->B';
is next_digit('Z'), 0, 'Z->0';
};
sub up_one($curr, $idx, $base){
my $dig = $curr->[$idx];
my $alpha_index = index_of($dig);
if ($alpha_index < $base-1) {
$curr->[$idx] = next_digit($dig);
} else {
$curr->[$idx] = 0;
$idx--;
if ($idx < 0 or not defined $curr->[$idx]){
unshift $curr->@*, 1;
} else {
up_one($curr, $idx, $base);
}
}
return $curr;
}
sub numbers($base) {
my @current_state = (-1);
return sub {
return join '', up_one(\@current_state, scalar (@current_state) -1, $base)->@*;
};
}
subtest 'generate decimal' => sub {
my $decimals = numbers(10);
for my $i (0..120) {
my $d = $decimals->();
is ($d, $i, "$d != $i");
}
};
subtest 'generate binary' => sub {
my $binary_numbers = numbers(2);
for my $i (0..100) {
my $b = sprintf("%b", $i);
my $d = $binary_numbers->();
is ($d, $b, "$d != $b");
}
};
sub convert($input_base, $output_base, $input) {
my $i = numbers($input_base);
my $o = numbers($output_base);
$o->() while $i->() ne $input;
return $o->();
}
subtest convert => sub {
is (convert(4, 7, 102303), 3336, 'base 4 -> base 7' );
is (convert(8, 3, 23447), 111202020, 'base 8 -> base 3' );
is (convert(10, 16, 1000), '3E8', 'base 10 -> base 16');
is (convert(16, 10, '3E8'), 1000, 'base 10 -> base 16');
};
done_testing();
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment