[CoLoCo] dice rolls in C

Jim Hutchinson jim at ubuntu-rocks.org
Sat Feb 9 04:28:19 GMT 2008


On Feb 5, 2008 1:30 PM, Dale K. Hawkins <dkhawk at gmail.com> wrote:
> The Ruby version FWIW:
>
> ============================8<================================
>
> # seed the random number generator
> srand
>
> # create the output array initialized to zeros (too big because 0 and 1 are
> invalid input; so sue me)
>  totals = Array.new(13) { 0 }
>
> # run 100,000 times (this number can be much larger if you want; Ruby
> supports automatically grow a number.  Speed does start to be an issue
> however.
> # The underscores help readability, but are unnecessary
>  # the code inside the {}'s is repeatedly run
> # rand(6) returns a result in the range 0..5 inclusive so we add 1
> # (rand(6) + 1) is one die, we need two
> 100_000.times { totals[(rand(6) + 1) + (rand(6) + 1) ] += 1 }
>
> # show some output....
> totals.each_with_index { | t, i | puts "#{t}: #{i}" }
>
> ============================8<================================
>
> -Dale
>

Thanks for sharing this. I finally had a chance to try it. Much easier
to work with than the C program. No compiling or anything. However, it
does seem a bit slower. 10 million rolls in the C program took about a
second. I changed this to 10 million and it took about 15 seconds. 10
billion rolls in the C program took about 15 mins. I'm assuming then
that 10 billion in the ruby program would take around 15 times as
long.

Also, if i wanted to roll 10 sided dice (number 0-9 for totals of
0-18) what would I change? I tried changing the 6s to 10s but got
errors.

-- 
Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html



More information about the Ubuntu-us-co mailing list