Sha256: 744a6ef7cfb7ab07ca85bff493cca76ce22771ae9389653a1f05daeb35de0b37

Contents?: true

Size: 720 Bytes

Versions: 83

Compression:

Stored size: 720 Bytes

Contents

unit module AllYourBase:ver<4>;

sub convert-base (
  :%bases! where all(.keys ~~ <from to>.Set, .values.all > 1),
  :@digits! where %bases<from> > .all ~~ UInt:D,
  --> Array[UInt:D]
) is export {
  from-decimal %bases<to>, to-decimal(%bases<from>, @digits);
}

sub to-decimal ($input-base, @input-digits) {
  my $elems = @input-digits.elems;
  $_ == 0 ?? $elems-- !! last for @input-digits;
  (loop (my $i = 0; $i < $elems; $i++) {
    @input-digits.reverse[$i] * $input-base ** $i;
  }).sum;
}

sub from-decimal ($output-base, $num is copy) {
  my UInt:D @output-digits;
  while $num >= $output-base {
    unshift @output-digits, $num % $output-base;
    $num div= $output-base;
  }
  @output-digits.unshift: $num;
}

Version data entries

83 entries across 83 versions & 1 rubygems

Version Path
trackler-2.2.1.98 tracks/perl6/exercises/all-your-base/Example.pm6
trackler-2.2.1.97 tracks/perl6/exercises/all-your-base/Example.pm6
trackler-2.2.1.96 tracks/perl6/exercises/all-your-base/Example.pm6