VladikOtez

Yandex interview First example

Sep 6th, 2017
184
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def calculate(string)
  2.   splitted = split_string_by_operators(string)
  3.   parsed = parse_to_nums(splitted)
  4.   splitted = split_by_minus_or_plus(parsed)
  5.   splitted.map!
  6. end
  7.  
  8. def split_string_by_operators(string)
  9.   string.split(%r{(\+|\-|\/|\*)}).map do |x|
  10.     unless x =~ /(\+|\-|\/|\*)/
  11.       x.to_f
  12.     else
  13.       x
  14.     end
  15.   end
  16. end
  17.  
  18. def split_by_minus_or_plus(array)
  19.   result = []
  20.   second_prior_operators = array.count("+") + array.count('-')
  21.   (second_prior_operators+1).times do
  22.     result << []
  23.   end
  24.   ind = 0
  25.   array.each do |token|
  26.     if token != "+" || token != '-'
  27.       result[ind].push(token)
  28.       p result
  29.     else
  30.       result.insert(ind, token)
  31.       #puts result
  32.       ind += 1
  33.     end
  34.   end
  35.   result
  36.  
  37. end
  38.  
  39.  
  40. def eval_each_three(ary)
  41.   result = 0
  42.   while ary.size != 1
  43.     result = calc(ary[0], ary[1], ary[2])
  44.     3.times do
  45.       ary.shift
  46.     end
  47.     ary.unshift(result)
  48.   end
  49.   ary
  50. end
  51.  
  52. #[982.0, "*", 5.0, "+", 3.0, "/", 5.0, "-", 1.0]
  53.  
  54. def calc(num1, operator, num2)
  55.   case operator
  56.     when  "*"
  57.       num1 * num2
  58.     when  "-"
  59.       num1 - num2
  60.     when  "/"
  61.       num1.to_f / num2
  62.     when  "+"
  63.       num1 + num2
  64.   end
  65. end
  66.  
  67. def parse_to_nums(ary)
  68.   ary.map! do |token|
  69.     if token =~ /\d/
  70.       token.to_i
  71.     else
  72.       token
  73.     end
  74.   end
  75. end
RAW Paste Data