From: -j b- Date: 2008-07-14T21:49:02+09:00 Subject: Re: Symbolify (#169) > > ## Symbolify (#169) > Fairly straightforward; handles negative and positive. I tried for the shortest resulting encoding but fell a little short compared to some of the other results . Thats likely due to my use of addition instead of multiplication. def symbolify(j) i = j.abs add = "--" unless $nums code = {?? => "??", ?- => "?-", ?) => "?)", ?( => "?(", ?* => "?*"} $nums = {} code.keys.each do |x| code.keys.each do |y| $nums[x-y] = "%s-%s" % [code[x], code[y]] $nums[x*y] = "%s*%s" % [code[x], code[y]] $nums[x**y] = "%s**%s" % [code[x], code[y]] end end end if $nums[i] eq = "%s%s%s" % [j < 0 ? "-(" : "", $nums[i], j < 0 ? ")" : ""] return eq end values = {} remove = 0 $nums.keys.sort.reverse.each do |num| next unless num > 1 if num < i and i % num == 0 return "%s(%s)*(%s)" % [j<0 ? "-" : "",$nums[num],symbolify(i/num)] end pow = 0 pow += 1 while num**pow <= i values[num**(pow-1)] = [num,pow-1] remove = num**(pow-1) if remove < num**(pow-1) end base,pow = values[remove] equation = "(%s)**(%s)" % [$nums[base], symbolify(pow)] equation << add + symbolify(i-remove) if i - remove > 0 j < 0 ? "-(" + equation + ")" : equation end -- Posted via http://www.ruby-forum.com/.