Skip to content

Instantly share code, notes, and snippets.

@Samda
Last active December 8, 2021 08:50
Show Gist options
  • Save Samda/2cbc2bd1e6b9d623eff00ded2c1e8981 to your computer and use it in GitHub Desktop.
Save Samda/2cbc2bd1e6b9d623eff00ded2c1e8981 to your computer and use it in GitHub Desktop.
Calculation Reverse Polish Notation with Ruby
#jurias from codewars
def calc(expr)
expr
.split(' ')
.reduce([0]) { |s, i| s << (i =~ /[0-9.]/ ? i.to_f : s.pop(2).reduce(i.to_sym)) }
.pop
end
#my code -_-
def calc1(expression)
values = expression.split(" ")
return 0 if expression.empty?
math_operator = /[\+\-\*\/]/.match(expression).to_s
numbers = []
check_value = ->(val){/(\d+[.]\d+)/.match(val) ? val.to_f : val.to_i}
if math_operator && !math_operator.empty?
values.each{ |i|
if i.to_i > 0
numbers << i.to_i
else
last = numbers.pop
first = numbers.pop
numbers << first.send(i, last)
end
}
numbers.last
else
value = expression.split(' ').last
check_value.call(value)
end
end
RSpec.describe "Challenge" do
it "should work for an empty string" do
expect(calculate("")).to eq(0)
end
it "should parse numbers" do
expect(calculate("1 2 3")).to eq(3)
end
it "should parse floats" do
expect(calculate("1 2 3.5")).to eq(3.5)
end
it "should support addition" do
expect(calculate("1 3 +")).to eq(4)
end
it "should support multiplication" do
expect(calculate("1 3 *")).to eq(3)
end
it "should support subtraction" do
expect(calculate("1 3 -")).to eq(-2)
end
it "should support division" do
expect(calculate("4 2 /")).to eq(2)
end
it "should support complexity expression" do
expect(calculate("1 2 3 * +").to eq(7))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment