From 73b17cafb9cdbcb2cbbbfa94afbc59f74d1d6c98 Mon Sep 17 00:00:00 2001 From: Semret Nicodimos Date: Sun, 19 Aug 2018 13:20:52 -0700 Subject: [PATCH 1/2] Create method for binary to decimal conversion for CS Homework --- 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..49f018e 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 + #raise NotImplementedError + decimal = 0 + count = 0 + binary_array.reverse.each do |num| + # puts "#{decimal}, #{count}, #{num}" + decimal += (num * (2**count)) + count += 1 + end + + return decimal + end From 8a38bb6c4fb10ccce02791c5e701437c21c45c7a Mon Sep 17 00:00:00 2001 From: Semret Nicodimos Date: Tue, 21 Aug 2018 20:46:03 -0700 Subject: [PATCH 2/2] Modified verion of the binary conversion method --- lib/binary_to_decimal.rb | 27 ++++++++++++++++++++------- specs/binary_to_decimal_spec.rb | 1 + 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 49f018e..f1edc80 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -4,16 +4,29 @@ # 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. + +# first way to do it taking out reverse +# def binary_to_decimal(binary_array) +# decimal = 0 +# count = 7 +# +# binary_array.each do |num| +# decimal += (num * (2**count)) +# count -= 1 +# end +# +# return decimal +# end + +# Using times loop and count + def binary_to_decimal(binary_array) - #raise NotImplementedError decimal = 0 - count = 0 - binary_array.reverse.each do |num| - # puts "#{decimal}, #{count}, #{num}" - decimal += (num * (2**count)) - count += 1 + count = binary_array.length + + count.times do |index| + decimal += (binary_array[index] * (2**(count-1-index))) end return decimal - end diff --git a/specs/binary_to_decimal_spec.rb b/specs/binary_to_decimal_spec.rb index ba17713..521fa9f 100644 --- a/specs/binary_to_decimal_spec.rb +++ b/specs/binary_to_decimal_spec.rb @@ -1,5 +1,6 @@ require 'minitest/autorun' require 'minitest/reporters' +require 'minitest/pride' require_relative '../lib/binary_to_decimal' describe "binary to decimal" do