------art_7276_18935211.1182100665776
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

Hello,

here is my solution for the arithmetic quiz. I am a ruby beginner and this
is my first ruby program (ok, my second one, the first was "puts 'hello
world'").
So please forgive me the dirty trick using eval (why build an own parser if
ruby provides such a fine solution?). I build in a brute force search
algorithm
via an iterative method for permutations. Therefore, any valid ruby
expression is allowed, e.g.

verbal_arithmetic.rb 'a+b
&& a+c -b && a*c ' solving a*b*c*d!&& a+b
&& a+c -b && a*c -- Solution --- a: 2 b: 1 c: 3 d: 6 Please feel free to send any comments. Regards Holger #!/usr/bin/ruby -w # # Solution to ruby quiz #128 # http://www.rubyquiz.com/quiz128.html # by Holger # # Usage: # verbal_arithmetic.rb <equation> # # Examples: # verbal_arithmetic.rb 'send+moreney' # verbal_arithmetic.rb 'a+b
&& a+c -b && a*c ' # #********************************************************************* # Permutator which gives all combinations of <m> elements out of # array <n> # # usage: # perms(m, n) { |x| ... } # #********************************************************************* def perms(m, n) p nil] * m t -1] * m k while k > if k yield p k -1 end n[t[k]] [k] if t[k]> while(t[k]<n.length()) t[k] [k]+1 if n[t[k]] p[k] [t[k]] n[t[k]] il k +1 t[k] 1 break end end k -1 if t[k].length() end end # Read from command line and make valid ruby expression ( > if not already present) puzzle RGV[0].gsub(/,") # Extract all letters and all first letters digits uzzle.gsub(/\W/,"").split(//).uniq starts uzzle.gsub(/(\w)\w*|\W/,"\\1").split(//).uniq if digits.length()> 0 puts "oops, too much letters" else # String containing all digits digitss igits.join # Build "first digit must not be zero" condition cond0 tarts.join("*") + "! # And now perform an exhaustive search puts "solving #{cond0} && #{puzzle}" perms(digits.length(), (0...10).to_a) { |v| p0 ond0.tr(digitss, v.join) p1 uzzle.tr(digitss, v.join) if eval(p0) && eval(p1) # Hint: first evaluate p0 as p1 may not be a valid expression puts '-- Solution ---' [digits, v].transpose.each do |x,y| puts "#{x}: #{y}" end end } end ------art_7276_18935211.1182100665776--