Knuth's algorithm S: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 251: | Line 251: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
<lang python>from random import |
<lang python>from random import randrange |
||
def s_of_n_creator(n): |
def s_of_n_creator(n): |
||
Line 262: | Line 262: | ||
# Keep first n items |
# Keep first n items |
||
sample.append(item) |
sample.append(item) |
||
elif |
elif randrange(i) < n: |
||
# Keep item |
# Keep item |
||
sample[randrange(n)] = item |
sample[randrange(n)] = item |
||
Line 325: | Line 325: | ||
# Keep first n items |
# Keep first n items |
||
sample.append(item) |
sample.append(item) |
||
elif |
elif randrange(i) < n: |
||
# Keep item |
# Keep item |
||
del sample[randrange(n)] |
del sample[randrange(n)] |
||
Line 342: | Line 342: | ||
if i <= n |
if i <= n |
||
sample << item |
sample << item |
||
elsif rand < |
elsif rand(i) < n |
||
sample[rand(n)] = item |
sample[rand(n)] = item |
||
end |
end |