#solution for Ruby Quiz to translate from digits to english wording of numbers #assumes good formatting of numbers with commas in correct placement. see examples DIGITS = { '1' => 'one', '2' => 'two', '3' => 'three','4' => 'four', '5' => 'five','6' => 'six', '7' => 'seven', '8' => 'eight', '9' => 'nine', '10' => 'ten', '11' => 'eleven', '12' => 'twelve', '13' => 'thirteen', '14' => 'fourteen', '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen', '18' => 'eighteen', '19' => 'nineteen'} TWO_PLACES = { '2' => 'twenty ', '3' => 'thirty ', '4' => 'fourty ', '5' => 'fifty ', '6' => 'sixty ', '7' => 'seventy ', '8' => 'eighty ', '9' => 'ninety ' } PLACES = { 2 => ' thousand ', 3 => ' million ', 4 => ' billion ', 5 => ' trillion ' } #section to handle general translation. def translate(value) get_english(value.split(',')) end #translates from array of sections of the full value def get_english(values) if values.length == 1 return eval_section(values[0]) else to_eval = values.delete_at(0) return eval_section(to_eval) + PLACES[values.length+1].to_s + get_english(values) end end #translate single section (3 digits worth) of a number def eval_section(num) digit_array = num.split(//) if digit_array.length == 3 if val = DIGITS[digit_array[0]] return val + " hundred " + eval_section(digit_array[1] + digit_array[2]) else return eval_section(digit_array[1] + digit_array[2]) end elsif digit_array.length == 2 if val = DIGITS[digit_array[0] + digit_array[1]] return val else return TWO_PLACES[digit_array[0]].to_s + DIGITS[digit_array[1]].to_s end else return DIGITS[digit_array[0]].to_s end end #examples #puts translate("30,003,050") #puts translate("30") #puts translate("1") #puts translate("999,999,999,999") #This section is for the second part of the quiz. 'the_puzzle' translates all numbers #up to 1000000 and sorts the result printing out the first number in the resulting sorted array. def to_good_string(str) ret_str = '' str = str.split(//) 1.upto(str.length) { |i| cur_char = str.pop if (i-1) % 3 == 0 and i != 1 ret_str = cur_char+ ',' + ret_str else ret_str = cur_char + ret_str end } ret_str end def the_puzzle nums = [] 1.upto(1000000) {|i| nums << translate(to_good_string(i.to_s)) puts nums[i-1] } nums.sort! puts nums[0] end #the_puzzle