Anonymous user
Knuth's algorithm S: Difference between revisions
m
→{{header|REXX}}: added/changed comments and whitespace, used a template for the output, used a simpler function for COMMAS, added a header separator.
(Added Rust) |
m (→{{header|REXX}}: added/changed comments and whitespace, used a template for the output, used a simpler function for COMMAS, added a header separator.) |
||
Line 1,331:
=={{header|REXX}}==
<lang rexx>/*REXX program using Knuth's algorithm S (a random sampling N of M items). */
parse arg trials size . /*obtain optional arguments from the CL*/
if trials==''
if size==''
#.=0 /*initialize frequency counter array. */
do trials /*OK, now let's light this candle. */
call s_of_n_creator size /*create an initial list of N items. */
do gener=0 for 10
call s_of_n gener /*call s_of_n with a single decimal dig*/
end
do
end
@= ' trials, and with a size
say hdr; say copies("═", length(hdr) ) /*display the header and its separator.*/
end /*dig*/▼
exit /*stick a fork in it, we're all done. */▼
do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _▼
c=random(1, items) /* [↓] should replace a previous item?*/▼
return /* ··· item to replace with ITEM.*/▼
s_of_n_creator: parse arg item 1 items /*generate ITEM number of items. */▼
!.k=random(0, 9) /*set the Kth item with random digit.*/▼
end /*k*/▼
return /*the piddly stuff is done (for now). */</lang>▼
'''output''' when using the default input of: <tt> 100000 2 </tt>▼
<pre>▼
Using Knuth's algorithm S for 100,000 trials, and with size=3:▼
do dig=0 to 9
say left('', 20) "frequency of the"
▲ end /*dig*/
frequency of the 2 digit is: 29,966▼
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
frequency of the 4 digit is: 30,137▼
frequency of the 5 digit is: 29,833▼
/*──────────────────────────────────────────────────────────────────────────────────────*/
frequency of the 6 digit is: 30,160▼
s_of_n: parse arg item; items=items + 1 /*get "item",
c=random(1, items)
if c>size then return
▲
▲ return /* ··· item to replace with ITEM.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
▲s_of_n_creator: parse arg item 1 items /*generate ITEM number of items. */
▲ !.k=random(0, 9) /*set the Kth item with random digit.*/
▲ end /*k*/
▲ return /*the piddly stuff is done (for now). */</lang>
▲
▲<pre>
═════════════════════════════════════════════════════════════════════════
frequency of the 1 digit is: 29,869
frequency of the 3 digit is: 30,076
frequency of the 4 digit is: 29,996
frequency of the 7 digit is: 30,099
frequency of the 8 digit is: 30,036
frequency of the 9 digit is: 30,134
</pre>
|