From: Rick DeNatale Date: 2008-07-14T10:45:20+09:00 Subject: Re: [QUIZ] Symbolify (#169) ------=_Part_48592_12496891.1216000183615 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Here's a fairly straightforward solution, this passes the tests and works for both positive and negative integers: def symbolify(i) digits = [ "?(-?(", "?)-?(", "?*-?(", "?--?*", "(?*-?()*(?*-?()", "?--?(", "(?--?*)*(?*-?()", "(((?*-?()*(?*-?())*(?*-?())-(?)-?()", "((?*-?()*(?*-?())*(?*-?()", "((?*-?()*(?--?())-(?)-?()", "(?*-?()*(?--?()" ] if i < 0 "-(#{symbolify(-i)})" else if i < 9 digits[i] else i.abs.to_s.split(//).map {|digit| digits[digit.to_i]}.inject(nil) { |answer, rep| answer ? "((#{rep})--(#{answer})*(#{digits[10]}))": rep } end end end The basic approach is to generate an expression which works like a lexical scan of the decimal representation of the (positive) integer, i.e. it's the closed form of val = 0 i.to_s(10).split(//).each |digit| val = val * 10 + digit.to_i end except the the digits are represented by expressions following the rules. For the positive integers <= 1000 the longest string generated was 157 characters for i = 777. For the negative integers >= 1000 the longest string generate was 160 characters for i = -777 (i.e) the same string wrapped in parentheses preceded by a - -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_48592_12496891.1216000183615--