Instructions

Test suite

Solution

Convert a binary number, represented as a string (e.g. '101010'), to its decimal equivalent using first principles.

Implement binary to decimal conversion. Given a binary input string, your program should produce a decimal output. The program should handle invalid inputs.

- Implement the conversion yourself. Do not use something else to perform the conversion for you.

Decimal is a base-10 system.

A number 23 in base 10 notation can be understood as a linear combination of powers of 10:

- The rightmost digit gets multiplied by 10^0 = 1
- The next number gets multiplied by 10^1 = 10
- ...
- The
*n*th number gets multiplied by 10^*(n-1)*. - All these values are summed.

So: `23 => 2*10^1 + 3*10^0 => 2*10 + 3*1 = 23 base 10`

Binary is similar, but uses powers of 2 rather than powers of 10.

So: `101 => 1*2^2 + 0*2^1 + 1*2^0 => 1*4 + 0*2 + 1*1 => 4 + 1 => 5 base 10`

.

Remember to check out the Perl 6 documentation and resources pages for information, tips, and examples if you get stuck.

There is a test suite and module included with the exercise.
The test suite (a file with the extension `.t`

) will attempt to run routines
from the module (a file with the extension `.pm6`

).
Add/modify routines in the module so that the tests will pass! You can view the
test data by executing the command `perl6 --doc *.t`

(* being the name of the
test suite), and run the test suite for the exercise by executing the command
`prove . --exec=perl6`

in the exercise directory.
You can also add the `-v`

flag e.g. `prove . --exec=perl6 -v`

to display all
tests, including any optional tests marked as 'TODO'.

All of Computer Science http://www.wolframalpha.com/input/?i=binary&a=*C.binary-_*MathWorld-

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
#!/usr/bin/env perl6
use v6;
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;
}
```

```
unit class Binary;
method to_decimal(Str $bin --> Int) {
$bin.comb(/0|1/).reverse.kv.map({ $^b * 2 ** $^a }).sum
}
```

A huge amount can be learnt from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that I could read more about to develop my understanding?