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?(break i-h):h=i; i+=1}
end
I don't think that your method rolls the dice s times.
def roll(n, s)
a=(1..n).map{|x|"#{x}|"};s.times{a[rand(n)]<<?#};puts a
end
--
Chanoch (Ken) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/
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.
···
2008/9/21 Sebastian Hungerecker <sepp2k@googlemail.com>
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?(break i-h):h=i;
i+=1}
end
> def per(n, b = 10)
> i=1;x=b;h={};loop {x=x%n*b;break 0 if x==0;h?(break i-h):h=i;
> i+=1}
> end
Would be interested to see if you could produce a version with no
assignments or semicolons.
def per(n, b=10)
(1..1.0/0).inject([b,{}]) { |(x,h),i| if x==0 then break 0 elsif h[x%n*b]
then break i-h[x%n*b] else [x%n*b, h.merge(x%n*b=>i)] end}
end
But frankly, I like my first solution better. And this one clearly does not
fit in one line.