diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d669de9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +notes.txt \ No newline at end of file diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..250540f 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -1,9 +1,27 @@ -# A method named `binary_to_decimal` that receives as input an array of size 8. -# The array is randomly filled with 0’s and 1’s. -# The most significant bit is at index 0. -# The least significant bit is at index 7. -# Calculate and return the decimal value for this binary number using -# the algorithm you devised in class. + def binary_to_decimal(binary_array) - raise NotImplementedError + decimal = 0 + exponent = 7 + binary_array.each do |digit| + decimal += (digit * (2**exponent)) + exponent -= 1 + end + return decimal end + + +def decimal_to_binary(num) + binary_number = (num % 2).to_s + num /= 2 + until num == 0 + modulo = (num % 2).to_s + num /= 2 + binary_number = modulo+binary_number + end + binary_array = binary_number.split(//) + return binary_array.map! {|digit| digit = digit.to_i} + + + +end + diff --git a/test/binary_to_decimal_test.rb b/test/binary_to_decimal_test.rb index ba17713..ade1ba7 100644 --- a/test/binary_to_decimal_test.rb +++ b/test/binary_to_decimal_test.rb @@ -1,33 +1,52 @@ require 'minitest/autorun' require 'minitest/reporters' require_relative '../lib/binary_to_decimal' +require 'minitest/pride' describe "binary to decimal" do it "From 10011001 to 153" do binary_array = [1, 0, 0, 1, 1, 0, 0, 1] expected_decimal = 153 - - binary_to_decimal(binary_array).must_equal expected_decimal + + expect(binary_to_decimal(binary_array)).must_equal expected_decimal end - + it "From 00001101 to 13" do binary_array = [0, 0, 0, 0, 1, 1, 0, 1] expected_decimal = 13 - - binary_to_decimal(binary_array).must_equal expected_decimal + + expect(binary_to_decimal(binary_array)).must_equal expected_decimal end - + it "From 10000000 to 128" do binary_array = [1, 0, 0, 0, 0, 0, 0, 0] expected_decimal = 128 - - binary_to_decimal(binary_array).must_equal expected_decimal + + expect(binary_to_decimal(binary_array)).must_equal expected_decimal end - + it "From random binary to decimal" do binary_array = Array.new(8) { rand(0..1) } expected_decimal = binary_array.join.to_s.to_i(2) - - binary_to_decimal(binary_array).must_equal expected_decimal + + expect(binary_to_decimal(binary_array)).must_equal expected_decimal end end + + +describe "decimal to binary" do + it "Converts a decimal to its corresponding binary number" do + number = 13 + expect(decimal_to_binary(number)).must_equal [1, 1, 0, 1] + end + + it "Converts 0 to its corresponding binary number" do + number = 0 + expect(decimal_to_binary(number)).must_equal [0] + end + + it "Handles a large number" do + number = 1_000 + expect(decimal_to_binary(number)).must_equal [1, 1, 1, 1, 1, 0, 1, 0, 0, 0] + end +end \ No newline at end of file