Knuth's algorithm S: Difference between revisions
Content added Content deleted
No edit summary |
m (added whitespace to task's preamble, changed the .C.f. to Related tasks) |
||
Line 2: | Line 2: | ||
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. |
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. |
||
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). |
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). |
||
;The algorithm: |
;The algorithm: |
||
Line 7: | Line 8: | ||
# For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. |
# For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. |
||
# Repeat #2 for any subsequent items. |
# Repeat #2 for any subsequent items. |
||
;The Task: |
;The Task: |
||
Line 14: | Line 16: | ||
:# Use the s_of_n_creator with n == 3 to generate an s_of_n. |
:# Use the s_of_n_creator with n == 3 to generate an s_of_n. |
||
:# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. |
:# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. |
||
Note: A class taking n and generating a callable instance/function might also be used. |
Note: A class taking n and generating a callable instance/function might also be used. |
||
;Reference: |
;Reference: |
||
* The Art of Computer Programming, Vol 2, 3.4.2 p.142 |
* The Art of Computer Programming, Vol 2, 3.4.2 p.142 |
||
;Cf. |
|||
;Related tasks: |
|||
* [[One of n lines in a file]] |
* [[One of n lines in a file]] |
||
* [[Accumulator factory]] |
* [[Accumulator factory]] |
||
<br><br> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |