電車の広告で見かけたので解いてみた。
逆ポーランド記法を用いた。
簡易な電卓機能を作れるかを試すような問題だった。
例は1,3,3,7の場合。
class Calculator
OPERATORS = %w[+ - * /]
def exec
answer_formulas = []
OPERATORS.each do |l|
first_ope = l
OPERATORS.each do |m|
second_ope = m
OPERATORS.each do |n|
third_ope = n
[1.0, 3.0, 3.0, 7.0, first_ope, second_ope, third_ope].permutation.to_a.each do |formula|
result = _calc(formula.dup)
if result == 10.0
answer_formulas << formula
end
end
end
end
end
p answer_formulas.uniq
p answer_formulas.uniq.count
end
private
def _calc(formula)
stack = []
while formula.size > 0
item = formula.shift
if OPERATORS.include? item
if stack.size < 2 || OPERATORS.include?(stack[-1]) || OPERATORS.include?(stack[-2])
stack.unshift "failure"
break
end
case item
when '+'
right = stack.pop
left = stack.pop
stack << left + right
when '-'
right = stack.pop
left = stack.pop
stack << left - right
when '*'
right = stack.pop
left = stack.pop
stack << left * right
when '/'
right = stack.pop
left = stack.pop
stack << left / right
end
else
stack << item
end
end
stack[0]
end
end
Calculator.new.exec