From 1f8891368ac1d4b863eb1eb59bfe7d576eac6e92 Mon Sep 17 00:00:00 2001 From: Bitaman Date: Wed, 27 Feb 2019 08:01:15 -0800 Subject: [PATCH 1/3] binary_to_decimal code is done --- lib/binary_to_decimal.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..12eb650 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -5,5 +5,15 @@ # 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 + n = binary_array.length - 1 + binary_array.each_with_index do |item, index| + dec_digit = item * 2 ** n + decimal += dec_digit + n -= 1 + end + puts "Decimal number for the binary you entered is #{decimal}" end + +a = [0, 0, 0, 0, 1, 1, 1, 1] +puts binary_to_decimal(a) From be7bcaaa387c9c00aefd2dec3de6da1fb795442f Mon Sep 17 00:00:00 2001 From: Bitaman Date: Thu, 28 Feb 2019 05:37:40 -0800 Subject: [PATCH 2/3] Fixed the program to pass the test --- lib/binary_to_decimal.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 12eb650..b45769f 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -5,15 +5,12 @@ # Calculate and return the decimal value for this binary number using # the algorithm you devised in class. def binary_to_decimal(binary_array) - decimal = 0 + expected_decimal = 0 n = binary_array.length - 1 binary_array.each_with_index do |item, index| dec_digit = item * 2 ** n - decimal += dec_digit + expected_decimal += dec_digit n -= 1 end - puts "Decimal number for the binary you entered is #{decimal}" + return expected_decimal end - -a = [0, 0, 0, 0, 1, 1, 1, 1] -puts binary_to_decimal(a) From e31505c3e7a7be2c820d2a630ad720afc465b68d Mon Sep 17 00:00:00 2001 From: Bitaman Date: Thu, 28 Feb 2019 21:12:10 -0800 Subject: [PATCH 3/3] Realized that I was not allowed to itterate with index, changed the code --- lib/binary_to_decimal.rb | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index b45769f..12a6a9f 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -5,12 +5,11 @@ # Calculate and return the decimal value for this binary number using # the algorithm you devised in class. def binary_to_decimal(binary_array) - expected_decimal = 0 - n = binary_array.length - 1 - binary_array.each_with_index do |item, index| - dec_digit = item * 2 ** n - expected_decimal += dec_digit - n -= 1 + decimal_number = 0 + index = -1 + binary_array.length.times do |i| + decimal_number += binary_array[index] * 2 ** i + index -= 1 end - return expected_decimal + return decimal_number end