Guest User

Untitled

a guest
Dec 7th, 2010
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.85 KB | None | 0 0
  1. module Enumerable
  2.     def repeated_permutation(size, &blk)
  3.         f = proc do |memo, &blk|
  4.             if memo.size == size
  5.                 blk.call memo
  6.             else
  7.                 self.each do |i|
  8.                     f.call memo + [i], &blk
  9.                 end
  10.             end
  11.         end
  12.  
  13.         if block_given?
  14.             f.call [], &blk
  15.         else
  16.             Enumerator.new(f, :call, [])
  17.         end
  18.     end
  19. end
  20.  
  21. def calc(exps)
  22.     if exps.size == 1
  23.         Ops.repeated_permutation(exps.first.scan(OpMark).size) do |ordered_ops|
  24.             expr = "#{exps.first}"
  25.             ordered_ops.each do |op|
  26.                 expr.sub!(OpMark, op.to_s)
  27.             end
  28.             result = eval(expr.gsub(/[0-9]+/){|s| "Rational(#{s})" }) rescue "Error"
  29.             puts "#{expr} = #{result}"
  30.         end
  31.     else
  32.         for i in 0..exps.size - 2
  33.             calc exps[0, i] + ["(#{exps[i]}#{OpMark}#{exps[i + 1]})"] + exps[(i + 2)..-1]
  34.         end
  35.     end
  36. end
  37.  
  38. require "rational"
  39. Ops = [:+, :-, :*, :/]
  40. OpMark = "<op>"
  41. nums = ARGV.map &:to_i
  42. calc nums
Advertisement
Add Comment
Please, Sign In to add comment