Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Enumerable
- def repeated_permutation(size, &blk)
- f = proc do |memo, &blk|
- if memo.size == size
- blk.call memo
- else
- self.each do |i|
- f.call memo + [i], &blk
- end
- end
- end
- if block_given?
- f.call [], &blk
- else
- Enumerator.new(f, :call, [])
- end
- end
- end
- def calc(exps)
- if exps.size == 1
- Ops.repeated_permutation(exps.first.scan(OpMark).size) do |ordered_ops|
- expr = "#{exps.first}"
- ordered_ops.each do |op|
- expr.sub!(OpMark, op.to_s)
- end
- result = eval(expr.gsub(/[0-9]+/){|s| "Rational(#{s})" }) rescue "Error"
- puts "#{expr} = #{result}"
- end
- else
- for i in 0..exps.size - 2
- calc exps[0, i] + ["(#{exps[i]}#{OpMark}#{exps[i + 1]})"] + exps[(i + 2)..-1]
- end
- end
- end
- require "rational"
- Ops = [:+, :-, :*, :/]
- OpMark = "<op>"
- nums = ARGV.map &:to_i
- calc nums
Advertisement
Add Comment
Please, Sign In to add comment