Last active
January 23, 2017 23:30
-
-
Save ryanveroniwooff/cff28d14dd1235bf201f320d1c39e4e2 to your computer and use it in GitHub Desktop.
Find the sum of an array with mixed data types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def iterative_sum(array) | |
array.map{|e| is_num?(e) ? e : string_value(e)}.inject(:+) | |
end | |
def recursive_sum(array, sum) | |
return sum if array.empty? | |
sum += is_num?(array[0]) ? array.shift : string_value(array.shift) | |
recursive_sum(array, sum) | |
end | |
def string_value(string) | |
string_values = {"a" => 1,"b" => 2,"c" => 3,"d" => 4,"e" => 5,"f" => 6,"g" => 7,"h" => 8,"i" => 9,"j" => 10,"k" => 11,"l" => 12,"m" => 13,"n" => 14,"o" => 15,"p" => 16,"q" => 17,"r" => 18,"s" => 19,"t" => 20,"u" => 21,"v" => 22,"w" => 23,"x" => 24,"y" => 25,"z" => 26,"A" => 27,"B" => 28,"C" => 29,"D" => 30,"E" => 31,"F" => 32,"G" => 33,"H" => 34,"I" => 35,"J" => 36,"K" => 37,"L" => 38,"M" => 39,"N" => 40,"O" => 41,"P" => 42,"Q" => 43,"R" => 44,"S" => 45,"T" => 46,"U" => 47,"V" => 48,"W" => 49,"X" => 50,"Y" => 51,"Z" => 52,} | |
string.split('').map { |e| string_values[e].to_i }.inject(:+) | |
end | |
def run(expected, array, sum=0) | |
puts "-- Iterative --" | |
answer = iterative_sum(array) | |
puts expected == answer ? "Success!\n> expected: #{expected}, got: #{answer}" : "Failure!\n> expected: #{expected}, got: #{answer}" | |
puts "\n-- Recursive --" | |
answer = recursive_sum(array, sum) | |
puts expected == answer ? "Success!\n> expected: #{expected}, got: #{answer}" : "Failure!\n> expected: #{expected}, got: #{answer}" | |
end | |
def is_num?(e) | |
e.to_f == e | |
end | |
value_array = [1, 'all', 4, 53, 'Cats', 24, 'Bilbo Swaggins', 12, 74, 'Wowwie', 23, 60, 13, 46, 'That is amazing'] | |
expected = 893 | |
run(expected, value_array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment