[QUIZ] a very late SOLUTION

  • Thread starter Kroeger Simon (ext)
  • Start date
K

Kroeger Simon (ext)

Hi all,

I know I'm too late, but reading through the past quizes, I came across
http://www.rubyquiz.com/quiz39.html and had an idea i couldn't spot in
the
summary. As there is no quiz this week, perhaps someone has some time to
spare and would like to share his/her thoughts with me.

----------------------------------------------------------
def sample members, lower, upper
$size =3D upper - lower
if $size =3D=3D members
(lower...upper).each {|i| puts i}
return
end
$range =3D $size / 2
distribution =3D ($range < members) ? $range - rand($size - members =
+
1) : rand(members+1)
=20
sample(distribution, lower, lower + $range) if distribution > 0=20
sample(members-distribution, lower + ((upper-lower) / 2), upper) if
members-distribution > 0
end

sample(ARGV[0].to_i, 0, ARGV[1].to_i)
----------------------------------------------------------

As one can easily see this is an recursive approach, the range is split=20
in half each recursion and it is randomly choosen how many of the
reminding
members are in each of the two halfes. This is nearly as fast as the
hash approach and doesn't need a sort and even eats up a lot less
memory.

What I'm not sure about is if the members are spread evenly - is there
some theoretician that can help me?

Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top