Last active
August 29, 2015 14:25
-
-
Save Zkuns/1be6fbef399424dda8d5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 main str | |
nums = str.scan(/\d+/) | |
marks = str.scan(/[+,\-,*,\/]/) | |
analyze nums, marks | |
end | |
def find_match_index arr, regx | |
arr.each_with_index do |e, index| | |
return index if e.match(regx) | |
end | |
return nil | |
end | |
def cal num1, num2, mark | |
case mark | |
when '+' | |
num1 + num2 | |
when '-' | |
num1 - num2 | |
when '*' | |
num1 * num2 | |
when '/' | |
num1 / num2 | |
end | |
end | |
def analyze nums, marks | |
index = find_match_index(marks, /[*, \/]/) | |
index = find_match_index(marks, /[+, \-]/) unless index | |
mark = marks.delete_at index | |
num1 = nums.delete_at index | |
num2 = nums.delete_at index | |
result = cal num1.to_i, num2.to_i, mark | |
return result if marks == [] | |
nums.insert(index, result) | |
analyze nums, marks | |
end | |
def split_str str | |
return (main str) unless str.index('(') | |
index_l = str.rindex('(') | |
str1 = str[index_l, str.length] | |
index_r = str1.index(')') | |
formula = str[index_l, index_r] | |
result = main formula | |
str.gsub! formula, result.to_s | |
split_str str | |
end | |
p split_str "3*(12+1)" | |
p split_str "2*(1+1)*(199+1)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment