Skip to content

Instantly share code, notes, and snippets.

@knishioka
Last active August 29, 2015 14:07
Show Gist options
  • Save knishioka/8a61026c105be51ef763 to your computer and use it in GitHub Desktop.
Save knishioka/8a61026c105be51ef763 to your computer and use it in GitHub Desktop.
四則演算を組み合わせて100なる組み合わせを抽出するプログラム
# 左から計算できるものしか抽出できない
## 実行例
# ruby sample.rb 1 2 8 8 8
# ((((1) + 8) / 2) + 8) * 8
# ((((8) + 1) / 2) + 8) * 8
require 'rational'
numbers = ARGV.map(&:to_r)
operators = ["+", "-", "*", "/"]
possible_operator_combination = operators.product(*([operators]*(numbers.size-2)))
numbers.permutation(numbers.size).to_a.uniq.each do |target|
possible_operator_combination.each do |ops|
if 100 == target[1..-1].each_with_index.inject(target[0]){ |res, (v, i)| res.send(ops[i], v) }
puts "(" * (target.size-1) + target.map(&:to_i).zip(ops.map{ |e| ") #{e} " }).flatten.join("")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment