てきとうなメモ

本の感想とか技術メモとか

与えられた整数のリストで四則演算を使ってxを作る

問3が気になったのでRubyで解いてみた。

require 'mathn'

def four_op(numbers, result)
  if numbers.size == 1 and numbers[0] == result
    return numbers[0].to_s
  end
    
  for i in 0..numbers.size-1
    selected = numbers[i]
    nums = numbers.dup
    nums.slice!(i)
    
    if res = four_op(nums, result - selected)
      # selected + res
      return selected.to_s + '+(' + res + ')'
    elsif res = four_op(nums, result / selected)
      # selected * res
      return selected.to_s + '*(' + res + ')'
    elsif res = four_op(nums, selected - result)
      # selected - res
      return selected.to_s + '-(' + res + ')'
    elsif res = four_op(nums, result + selected)
      # res - selected
      return res + '-(' + selected.to_s + ')'
    elsif result != 0 && res = four_op(nums, selected / result)
      # selected / res
      return selected.to_s + '/(' + res + ')'
    elsif res = four_op(nums, selected * result)
      # res / selected
      return '(' + res + ')/' + selected.to_s
    end
  end
  return nil
end

puts four_op([9,9,9,9], 10)
puts four_op([1,1,9,9], 10)
puts four_op([3,4,7,8], 10)
puts four_op([1,1,5,8], 10)
$ ruby four_op.rb
(9+(9*(9)))/9
9*(1+(1/(9)))
8*(3-((7)/4))
8/(1-(1/(5)))