Skip to content

Commit

Permalink
Restore binary and trinary
Browse files Browse the repository at this point in the history
  • Loading branch information
m-dango committed Jan 1, 2024
1 parent 944dbcd commit f8c4e1e
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 0 deletions.
13 changes: 13 additions & 0 deletions exercises/practice/binary/.meta/solutions/Binary.rakumod
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Binary is export {
method to_decimal ($binary) {
return 0 if $binary ~~ /<-[^01]>/;

my $decimal = 0;
my $index = $binary.chars;

for $binary.split('',:skip-empty) -> $bit {
$decimal += $bit * 2 ** --$index;
}
return $decimal;
}
}
1 change: 1 addition & 0 deletions exercises/practice/binary/.meta/solutions/binary.rakutest
Empty file.
23 changes: 23 additions & 0 deletions exercises/practice/binary/binary.rakutest
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env raku
use Test;
use lib $?FILE.IO.dirname;
use Binary;

plan 9;

ok Binary.can('to_decimal'), 'Class Binary has to_decimal method';

my %results = (
1 => 1,
10 => 2,
11 => 3,
100 => 4,
1001 => 9,
11010 => 26,
10001101000 => 1128,
'carrot23' => 0,
);

for %results.sort {
is Binary.to_decimal($_.key), $_.value, '"' ~ $_.key ~ '" returns ' ~ $_.value;
}
6 changes: 6 additions & 0 deletions exercises/practice/trinary/.meta/solutions/Trinary.rakumod
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
sub to-decimal($num) is export {

return 0 if $num ~~ /<-[012]>/;

return reduce { 3 * $^a + $^b }, 0, |$num.comb;
}
Empty file.
52 changes: 52 additions & 0 deletions exercises/practice/trinary/trinary.rakutest
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env raku

use Test;
use lib $?FILE.IO.dirname;
use Trinary;

my @cases = (
{
input => 1,
expected => 1,
},
{
input => 2,
expected => 2,
},
{
input => 10,
expected => 3,
},
{
input => 11,
expected => 4,
},
{
input => 100,
expected => 9,
},
{
input => 10,
expected => 3,
},
{
input => 112,
expected => 14,
},
{
input => 222,
expected => 26,
},
{
input => 1122000120,
expected => 32091,
},
{
input => "carrot",
expected => 0,
}
);

plan @cases.elems;

is to-decimal( .<input> ), .<expected>, .<input> for @cases;

0 comments on commit f8c4e1e

Please sign in to comment.