One of n lines in a file: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: add) |
|||
Line 20: | Line 20: | ||
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. |
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. |
||
=={{header|C}}== |
|||
<lang c>#include <stdio.h> |
|||
#include <stdlib.h> |
|||
inline int irand(int n) |
|||
{ |
|||
int r, randmax = RAND_MAX/n * n; |
|||
while ((r = rand()) >= randmax); |
|||
return r / (randmax / n); |
|||
} |
|||
inline int of_n(int n) |
|||
{ |
|||
int i, r = 0; |
|||
for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; |
|||
return r; |
|||
} |
|||
int main(void) |
|||
{ |
|||
int i, r[10] = {0}; |
|||
for (i = 0; i < 1000000; i++, r[of_n(10)]++); |
|||
for (i = 0; i < 10; i++) |
|||
printf("%d%c", r[i], i == 9 ? '\n':' '); |
|||
return 0; |
|||
}</lang>output<lang>100561 99814 99816 99721 99244 99772 100790 100072 99997 100213</lang> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
Line 37: | Line 65: | ||
Output: |
Output: |
||
<pre>100288 100047 99660 99773 100256 99633 100161 100483 99789 99910</pre> |
<pre>100288 100047 99660 99773 100256 99633 100161 100483 99789 99910</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
<lang python>from random import random as rnd |
<lang python>from random import random as rnd |