-
-
Save anonymous/380443582e8c47941bd44939fb9ccf07 to your computer and use it in GitHub Desktop.
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 calc numbers, ops | |
expression = numbers.zip(ops).flatten.compact | |
# need some bodmas action | |
while expression.include?(:/) | |
result = [expression[expression.index(:/) - 1].to_f,expression[expression.index(:/) + 1].to_f].inject :/ | |
expression.delete(expression[expression.index(:/) - 1]) | |
expression.delete(expression[expression.index(:/) + 1]) | |
expression[expression.index(:/)] = result | |
end | |
while expression.include?(:*) | |
result = [expression[expression.index(:*) - 1].to_f,expression[expression.index(:*) + 1].to_f].inject :* | |
expression.delete(expression[expression.index(:*) - 1]) | |
expression.delete(expression[expression.index(:*) + 1]) | |
expression[expression.index(:*)] = result | |
end | |
while expression.include?(:+) | |
result = [expression[expression.index(:+) - 1].to_f,expression[expression.index(:+) + 1].to_f].inject :+ | |
expression.delete(expression[expression.index(:+) - 1]) | |
expression.delete(expression[expression.index(:+) + 1]) | |
expression[expression.index(:+)] = result | |
end | |
while expression.include?(:-) | |
result = [expression[expression.index(:-) - 1].to_f,expression[expression.index(:-) + 1].to_f].inject :- | |
expression.delete(expression[expression.index(:-) - 1]) | |
expression.delete(expression[expression.index(:-) + 1]) | |
expression[expression.index(:-)] = result | |
end | |
result | |
end | |
p calc [1, 2, 3], [:/, :/] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment