0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

四則演算のみを用いて4つの数字で10を作ることはできますか。

Last updated at Posted at 2021-12-07

電車の広告で見かけたので解いてみた。
逆ポーランド記法を用いた。
簡易な電卓機能を作れるかを試すような問題だった。
例は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
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?