One of n lines in a file: Difference between revisions

Content deleted Content added
No longer draft as people seem able to follow the requirements OK.
No edit summary
Line 113: Line 113:
let rec aux i r =
let rec aux i r =
if i >= n then r else
if i >= n then r else
if (Random.float 1.0) < (1.0 /. float (i + 1))
if Random.int (i + 1) = 0
then aux (succ i) i
then aux (succ i) i
else aux (succ i) r
else aux (succ i) r
Line 121: Line 121:
let test ~n ~trials =
let test ~n ~trials =
let ar = Array.make n 0 in
let ar = Array.make n 0 in
for i = 0 to pred trials do
for i = 1 to trials do
let d = one_of_n n in
let d = one_of_n n in
ar.(d) <- succ ar.(d)
ar.(d) <- succ ar.(d)
Line 159: Line 159:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from random import random as rnd
<lang python>from random import randrange


def one_of_n(n):
def one_of_n(n):
Line 165: Line 165:
choice = 0
choice = 0
for i in range(1, n):
for i in range(1, n):
if rnd() < 1. / (i + 1.):
if randrange(i+1) == 0:
choice = i
choice = i
return choice
return choice