From: James Coglan Date: 2008-09-21T18:54:10+09:00 Subject: Re: One-Liners Mashup (#177 again) ------=_Part_3621_9902161.1221991327967 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline 2008/9/21 Sebastian Hungerecker > James Coglan wrote: > > def per(n, p = 16) > > (1..(p/2)).detect { |x| ("%.#{p}f" % > > (1.0/n)).split(".").last.scan(%r{.{#{x}}}).uniq.size == 1 } || 0 > > end > > > > This produces correct output for the numbers you specified. > > It produces 0 for 6 though (because printf rounds instead of truncating so > you > get a 7 at the end). > Here's one that should always be accurate and it's even in 1 line and > handles > different bases: > def per(n, b = 10) > i=1;x=b;h={};loop {x=x%n*b;break 0 if x==0;h[x]?(break i-h[x]):h[x]=i; > i+=1} > end Would be interested to see if you could produce a version with no assignments or semicolons. With Ruby's functional and OO capabilities, it's always more satisfying if you can solve a problem with a single statement, and I think these little one-liner problems are great for getting you thinking in functional style. ------=_Part_3621_9902161.1221991327967--