ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Jul 13 2018
·
6 comments

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`

.

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

```
gem install minitest
```

If you would like color output, you can `require 'minitest/pride'`

in
the test file, or note the alternative instruction, below, for running
the test file.

Run the tests from the exercise directory using the following command:

```
ruby binary_test.rb
```

To include color from the command line:

```
ruby -r minitest/pride binary_test.rb
```

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.

```
require 'minitest/autorun'
require_relative 'binary'
# Common test data version: 1.0.0 969717d
class BinaryTest < Minitest::Test
def test_binary_0_is_decimal_0
# skip
assert_equal 0, Binary.to_decimal('0')
end
def test_binary_1_is_decimal_1
skip
assert_equal 1, Binary.to_decimal('1')
end
def test_binary_10_is_decimal_2
skip
assert_equal 2, Binary.to_decimal('10')
end
def test_binary_11_is_decimal_3
skip
assert_equal 3, Binary.to_decimal('11')
end
def test_binary_100_is_decimal_4
skip
assert_equal 4, Binary.to_decimal('100')
end
def test_binary_1001_is_decimal_9
skip
assert_equal 9, Binary.to_decimal('1001')
end
def test_binary_11010_is_decimal_26
skip
assert_equal 26, Binary.to_decimal('11010')
end
def test_binary_10001101000_is_decimal_1128
skip
assert_equal 1128, Binary.to_decimal('10001101000')
end
def test_binary_ignores_leading_zeros
skip
assert_equal 31, Binary.to_decimal('000011111')
end
def test_2_is_not_a_valid_binary_digit
skip
assert_raises(ArgumentError) { Binary.to_decimal('2') }
end
def test_a_number_containing_a_non_binary_digit_is_invalid
skip
assert_raises(ArgumentError) { Binary.to_decimal('01201') }
end
def test_a_number_with_trailing_non_binary_characters_is_invalid
skip
assert_raises(ArgumentError) { Binary.to_decimal('10nope') }
end
def test_a_number_with_leading_non_binary_characters_is_invalid
skip
assert_raises(ArgumentError) { Binary.to_decimal('nope10') }
end
def test_a_number_with_internal_non_binary_characters_is_invalid
skip
assert_raises(ArgumentError) { Binary.to_decimal('10nope10') }
end
def test_a_number_and_a_word_whitespace_spearated_is_invalid
skip
assert_raises(ArgumentError) { Binary.to_decimal('001 nope') }
end
# Problems in exercism evolve over time, as we find better ways to ask
# questions.
# The version number refers to the version of the problem you solved,
# not your solution.
#
# Define a constant named VERSION inside of the top level BookKeeping
# module, which may be placed near the end of your file.
#
# In your file, it will look like this:
#
# module BookKeeping
# VERSION = 1 # Where the version number matches the one in the test.
# end
#
# If you are curious, read more about constants on RubyDoc:
# http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html
def test_bookkeeping
skip
assert_equal 3, BookKeeping::VERSION
end
end
```

```
class Binary
def initialize(binary_string)
@bits = binary_string
end
def to_decimal
bits.reverse.map.with_index { |bit, position| bit * 2**position }.inject(:+)
end
def bits
@bits.chars.map { |x| Integer(x) }
rescue
[0]
end
end
```

A huge amount can be learned 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 you could read more about to improve your understanding?

Level up your programming skills with 3,394 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments

Should probably have made bits private... I also don't like the rescue statment in the there. I think it's valid to have an empty array of bits if there are none, but it works.

You should at a minimum rescue exactly what you want to react to.

Arrays return nil if the index is not found, representing "nothing" which is appropriate. So this seems like it is idiomatically incorrect for Ruby in relation to how Array is expected to work.

You should at a minimum rescue exactly what you want to react to.

Yes, that would have been better.

Arrays return nil if the index is not found, representing "nothing" which is appropriate. So this seems like it is idiomatically incorrect for Ruby in relation to how Array is expected to work.

I am not sure what you mean by this. I am not indexing anywhere. I should have specified a default value with inject in case the array is empty. Is that what you are referring to?

Yes, though perhaps it does not matter so much, since it an error would be raised by Integer method early in the call.

Yes, though perhaps it does not matter so much, since it an error would be raised by Integer method early in the call.

I think that was my original idea, but an empty string will still return nil, not 0.