From: Ken Bloom Date: 2007-04-09T03:40:07+09:00 Subject: Re: [QUIZ] Getting to 100 (#119) On Mon, 09 Apr 2007 01:39:19 +0900, Christian Neukirchen wrote: > =begin >> The quiz, then, is to solve this problem without thinking, instead >> letting the computer think for you. > > I did not intent to seriously submit this solution, but it can be > helpful as an example of how to use Ruby to solve a problem quickly > without thinking too much or locating Knuth on the bookshelve. Writing > this code took maybe ten minutes and happened step-by-step with checking > the immediate results. > > Since there are only 168 solutions (254 if you allow a sign before the > first digit), brute-forcing is the simplest thing one can do. Additional > operations can be added by changing the base and mapping the digits onto > further operations. (Different digit order is not that easy to > implement and maybe be futile to do with brute-forcing.) =end > > (00000000..'22222222'.to_i(3)).map { |x| x.to_s(3).rjust(8, "0"). > tr('012', '-+ ') }. > find_all { |x| x.count("-") == 2 and x.count("+") == 1 }. A less ram-intensive version of this would swap the map and find_all calls as follows: (00000000..'22222222'.to_i(3)). find_all { |x| x.to_s(3).count("0") == 2 and x.to_s(3).count("1") == 1 }. map { |x| x.to_s(3).tr('012', '-+ ').rjust(8," ")}. (It doesn't keep maintain references to the bad combinations of operators, allowing the GC to reclaim them earlier.) > map { |x| > t = "1" + x.split(//).zip((2..9).to_a).join.delete(" ") [eval(t), t] > }.sort.each { |s, x| > puts "*****************" if s == 100 > puts "#{x}: #{s}" > puts "*****************" if s == 100 > } > > __END__ > > 2#787lilith:~/mess/current$ ruby quiz119.rb |grep -C4 100$ > 123-456-7+89: -251 > 123+45-67-89: 12 > 123-45+67-89: 56 > ***************** > 123-45-67+89: 100 > ***************** > 12+345-67-89: 201 > 1-234+567-89: 245 > 1-23-456+789: 311 > I like this answer a lot. Think you could generalize it to the extra credit? -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/