One of n lines in a file: Difference between revisions
Added Easylang
No edit summary |
(Added Easylang) |
||
(7 intermediate revisions by 6 users not shown) | |||
Line 16:
;Task:
# Create a function/method/routine called <code>one_of_n</code> that given <code>n</code>, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. <br>The number returned can vary, randomly, in each run.
# Use <code>one_of_n</code> in a ''simulation'' to find what
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Line 28:
{{trans|Python}}
<
V choice = 0
L(line) lines
Line 42:
R bins
print(one_of_n_test())</
;Sample output:
Line 50:
=={{header|Ada}}==
<
procedure One_Of_N is
Line 83:
Ada.Text_IO.Put(Integer'Image(Results(R)));
end loop;
end One_Of_N;</
Example output:<pre> 100104 100075 99761 99851 100457 100315 100101 99557 99678 100101</pre>
=={{header|Aime}}==
<
{
integer i, r;
Line 114:
0;
}</
{{Out}}
<pre> 99804 100236 99846 100484 99888 99639 99886 99810 99923 100484</pre>
=={{header|ALGOL 68}}==
<
INT max lines = 10; CO Should be read from a file. CO
[max lines]INT stats;
Line 133:
print (("Line Number times chosen", newline));
FOR i TO max lines DO printf (($g(0)7xg(0)l$, i, stats[i])) OD
END</
{{out}}
<pre>
Line 151:
=={{header|Applesoft BASIC}}==
A million iterations will take a very very long time to run. I suggest cranking the end value of J down to 1000 or less in line 20, and run this at full speed in a modern Apple II emulator. Initializing with RND(0) in line 10, seeds the RND function to be random, otherwise you may see the same results every time.
<
20 FOR J = 1 TO 1000000 : REMMAYBE TRY 100 ON A 1MHZ APPLE II
Line 167:
120 IF INT(RND(1) * I) = 0 THEN C = I
130 NEXT I
140 RETURN</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">oneOfN: function [n][
result: 0
loop 0..dec n 'x [
if zero? random 0 x ->
result: x
]
return result
]
oneOfNTest: function [n,trials][
ret: array.of:n 0
if n > 0 [
loop 1..trials 'i [
oon: oneOfN n
ret\[oon]: ret\[oon] + 1
]
]
return ret
]
print oneOfNTest 10 1000000</syntaxhighlight>
{{out}}
<pre>100120 100126 99975 99847 100235 100238 99528 99956 100038 99937</pre>
=={{header|AutoHotkey}}==
{{trans|Python}}
This simulation is for 100,000 repetitions.
<
; One based line numbers
choice = 1
Line 193 ⟶ 221:
Loop 10
out .= A_Index ": " b[A_Index] "`n"
MsgBox % out</
Output:
<pre>---------------------------
Line 214 ⟶ 242:
=={{header|AWK}}==
<
#
# Usage:
Line 229 ⟶ 257:
END {
print line;
}</
Test randomness
<
for i in `seq 1 10000`; do seq 1 10 | awk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk; done |sort|uniq -c
</syntaxhighlight>
<pre>
Line 252 ⟶ 280:
{{works with|QBasic}}
<
DIM L0 AS LONG, c AS LONG
Line 275 ⟶ 303:
NEXT
oneofN& = choice
END FUNCTION</
Sample output:
Line 296 ⟶ 324:
'''Batch file to call one_of_n'''
<
@echo off
Line 308 ⟶ 336:
del output.txt
pause>nul
</syntaxhighlight>
'''one_of_n'''
<
setlocal enabledelayedexpansion
Line 326 ⟶ 354:
endlocal
exit /b
</syntaxhighlight>
Line 344 ⟶ 372:
=={{header|BBC BASIC}}==
<
DIM cnt%(10)
FOR test% = 1 TO 1000000
Line 360 ⟶ 388:
IF RND(1) <= 1/i% l% = i%
NEXT
= l%</
'''Output:'''
<pre>
Line 367 ⟶ 395:
=={{header|C}}==
<
#include <stdlib.h>
Line 393 ⟶ 421:
return 0;
}</
<pre>100561 99814 99816 99721 99244 99772 100790 100072 99997 100213</pre>
=={{header|C sharp|C#}}==
<
class Program
{
Line 431 ⟶ 459:
}
}
</syntaxhighlight>
<pre>
1 99777
Line 447 ⟶ 475:
=={{header|C++}}==
{{works with|C++11}}
<
#include <iostream>
#include <iterator>
Line 474 ⟶ 502:
cout << '\n';
}
</
<pre>99981 99806 100190 99831 99833 100291 99356 100165 100279 100268</pre>
=={{header|Chapel}}==
<
proc one_of_n(n) {
Line 492 ⟶ 520:
return keep;
}</
=={{header|Clojure}}==
The function ''rand-seq-elem'' actually implements the algorithm; ''one-of-n'' uses it to select a random element from the sequence (1 ... n). (Though they weren't automatically highlighted when I wrote this, ''rand-int'', ''second'', and ''frequencies'' and ''println'' are also standard functions)
<
(let [f (fn [[k old] new]
[(inc k) (if (zero? (rand-int k)) new old)])]
Line 506 ⟶ 534:
(let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))]
(doseq [[n cnt] (sort countmap)]
(println n cnt)))</
Sample output
<syntaxhighlight lang="text">1 99350
2 99933
3 99820
Line 518 ⟶ 546:
8 100020
9 100342
10 99382</
To actually get a randomly selected line from a file:
<
(defn rand-line [filename]
(with-open [reader (io/reader filename)]
(rand-seq-elem (line-seq reader)))</
=={{header|Common Lisp}}==
Great place to use closures.
<
(let ((cur 0) (sel nil))
#'(lambda (v)
Line 547 ⟶ 575:
(let* ((sel (funcall fnt 9)))
(setf (aref counts sel) (+ 1 (aref counts sel)))))))
</syntaxhighlight>
Output:
<syntaxhighlight lang="text">#(100104 100144 100004 99593 100049 99706 100612 99481 100029 100278)</
=={{header|D}}==
<
// Zero-based line numbers.
Line 570 ⟶ 598:
bins.writeln;
writeln("Total of bins: ", bins[].sum);
}</
{{out}}
<pre>[100091, 99940, 100696, 99799, 100234, 99419, 100225, 99716, 99942, 99938]
Line 576 ⟶ 604:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/One_of_n_lines_in_a_file#Pascal Pascal].
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight>
n = 10
trials = 1000000
func one n .
for i = 1 to n
if randomf < 1 / i
chosen = i
.
.
return chosen
.
len results[] n
for i = 1 to trials
r = one n
results[r] += 1
.
print "Value Occurrences"
print "-------------------"
for i to n
print i & "\t" & results[i]
.
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 611 ⟶ 664:
end
</syntaxhighlight>
<syntaxhighlight lang="eiffel">
class
ONE_OF_N_LINES
Line 652 ⟶ 705:
end
</syntaxhighlight>
{{out}}
<pre>
Line 669 ⟶ 722:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def task do
dict = Enum.reduce(1..1000000, %{}, fn _,acc ->
Line 686 ⟶ 739:
end
One_of_n_lines_in_file.task</
{{out}}
Line 703 ⟶ 756:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( one_of_n_lines_in_file ).
Line 720 ⟶ 773:
update_counter( _N, Dict ) -> dict:update_counter( one_of_n(10), 1, Dict ).
</syntaxhighlight>
{{out}}
<pre>
Line 737 ⟶ 790:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ONE_OF_N
Line 761 ⟶ 814:
PRINT
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 768 ⟶ 821:
=={{header|Euphoria}}==
<
include std/rand.e
include std/math.e
Line 795 ⟶ 848:
main()
</syntaxhighlight>
Sample Output:
<pre>
Line 812 ⟶ 865:
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
Line 834 ⟶ 887:
test 10 1000000
0</
Output
<pre>99721 100325 99939 99579 100174 100296 99858 99910 100192 100006</pre>
Line 841 ⟶ 894:
''random-line'' uses an input stream. <code>"/etc/passwd" ascii [ random-line . ] with-file-reader</code> would print a random line from /etc/passwd.
<
USING: io kernel locals math random ;
IN: rosettacode.random-line
Line 851 ⟶ 904:
[ choice! ] [ drop ] if
] while drop
choice ;</
''one-of-n'' wants to use the same algorithm. Factor has duck typing, so ''one-of-n'' creates a mock object that quacks like an input stream. This mock object only responds to ''stream-readln'', not the other methods of stream protocol. This works because ''random-line'' only needs ''stream-readln''. The mock response is a line number instead of a real line.
<
USING: accessors io kernel math rosettacode.random-line ;
IN: rosettacode.one-of-n
Line 885 ⟶ 938:
] each ;
PRIVATE>
MAIN: test-one-of-n</
<pre>$ ./factor -run=rosettacode.one-of-n
Line 905 ⟶ 958:
=={{header|Forth}}==
{{works with|GNU Forth}}for random.fs and 1/f
<
: frnd
Line 917 ⟶ 970:
: .hist cr 10 0 do i 1+ 2 .r ." : " i hist @ . cr loop ;
simulate .hist bye</
{{out}}
<pre>> gforthamd64 rosetta_one_of_n.fs
Line 932 ⟶ 985:
10: 100452</pre>
=={{header|Fortran}}==
Task description is contradictory in that it states number of lines
in file is unknown, and then that it is passed in as "n", and exercise
Line 944 ⟶ 991:
(at least when using Fortran, even on an old laptop) it only takes a
few seconds to run the 1 000 000, cases so actually ran them.
<
!> read lines one at a time and randomly choose one
!! using a Reservoir Sampling algorithm:
Line 999 ⟶ 1,046:
end subroutine one_of_n
end program reservoir_sample
}</
{{out}}
<pre>
Line 1,010 ⟶ 1,057:
sys 0m1.465s
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Declare Function one_of_n (n As Long) As Long
Dim As Long L0, c, elegido(1 To 10)
Function one_of_n (n As Long) As Long
'asume que la primera línea es 1
Line 1,030 ⟶ 1,084:
Next L0
Sleep</
=={{header|Go}}==
<
import (
Line 1,115 ⟶ 1,169:
// task item 3. show frequencies.
fmt.Println(freq)
}</
Output:
<pre>
Line 1,124 ⟶ 1,178:
The function selItem will operate on any list, whether a lazy list of strings from a file or a list of numbers, as in the test.
<
import System.Random
import Data.List
Line 1,156 ⟶ 1,210:
else putStrLn.(\(l, n, _, _) -> "Line " ++
show n ++ ": " ++ l)
.selItem g.lines =<< (readFile $ head a)</
Running without any args runs the test:
Line 1,179 ⟶ 1,233:
=={{header|Icon}} and {{header|Unicon}}==
{{trans|Python}}
<
one_of_n_test(10,1000000)
end
Line 1,195 ⟶ 1,249:
every writes(bins[i := 1 to n]," ")
return bins
end</
Sample output:<pre>99470 99806 99757 99921 100213 100001 99778 100385 100081 100588</pre>
Line 1,203 ⟶ 1,257:
This implementation also implements line buffering, since the built-in line handling does not work quite how I want it to work. That said, if a line is too large (many gigabytes, for example), the system will crawl to a halt when the line is read.
<
file=. boxopen y
r=. ''
Line 1,222 ⟶ 1,276:
end.
r
)</
Usage: randLineBig 'filename'
Line 1,228 ⟶ 1,282:
Testing:
<
20
(#;~.)/.~ /:~ <@randLineBig"0]1e6#<'seq.txt'
Line 1,251 ⟶ 1,305:
├──────┼───┤
│99583 │9 │
└──────┴───┘</
=={{header|Java}}==
{{trans|Python}}
<
import java.util.Random;
Line 1,286 ⟶ 1,340:
}
}
</syntaxhighlight>
Sample output:
Line 1,299 ⟶ 1,353:
of entropy such as /dev/random. The output shown below
is from a run of the following:
<syntaxhighlight lang="sh">
export LC_ALL=C
< /dev/random tr -cd '0-9' | fold -w 4 | jq -Mnr -f program.jq
</syntaxhighlight>
'''program.jq'''
<
# of 4-digit PRNs uniformly distributed on [0-9999]
def oneOfN:
Line 1,317 ⟶ 1,371:
(n|oneOfN) as $num
| .[$num-1] += 1 )) as $freqs
| range(1; 1+n) | "Line\(.) \($freqs[.-1] )"</
{{out}}
<pre>
Line 1,334 ⟶ 1,388:
=={{header|Julia}}==
<syntaxhighlight lang="julia">
const N = 10
const GOAL = 10^6
Line 1,357 ⟶ 1,411:
println(@sprintf " %2d => %6d" i nhist[i])
end
</syntaxhighlight>
{{out}}
Line 1,375 ⟶ 1,429:
=={{header|Kotlin}}==
<
import java.util.Random
Line 1,398 ⟶ 1,452:
}
for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 1]}")
}</
Sample output:
Line 1,415 ⟶ 1,469:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
DIM chosen(10)
Line 1,434 ⟶ 1,488:
NEXT
END FUNCTION
</syntaxhighlight>
{{Out}}
<pre>
Line 1,450 ⟶ 1,504:
=={{header|Lua}}==
<syntaxhighlight lang="lua">
math.randomseed(os.time())
Line 1,482 ⟶ 1,536:
print(k,v)
end
</syntaxhighlight>
{{Out}}
<pre>
Line 1,500 ⟶ 1,554:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
with(RandomTools[MersenneTwister]);
one_of_n_lines_in_a_file := proc(fn)
Line 1,521 ⟶ 1,575:
return(n);
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
rec = selected = Read[strm];
While[rec =!= EndOfFile,
Line 1,531 ⟶ 1,585:
If[RandomReal[] < 1/n, selected = rec]];
Close[strm];
selected]</
=={{header|MATLAB}} / {{header|Octave}}==
<
fid = fopen(fn,'r');
if fid<0, return; end;
Line 1,548 ⟶ 1,602:
end;
end
fclose(fid);</
test
<
for k = 1:1e6;
n = one_of_n_lines_in_a_file('f1');
x(n) = x(n) + 1;
end;
[1:10;x]</
<pre> 1 2 3 4 5 6 7 8 9 10
105973 105715 106182 106213 105443 105255 106048 105999 105366 106070</pre>
=={{header|Nim}}==
<
randomize()
Line 1,575 ⟶ 1,629:
inc result[oneOfN(n)]
echo oneOfNTest()</
{{out}}
Line 1,581 ⟶ 1,635:
=={{header|OCaml}}==
<
let rec aux i r =
if i >= n then r else
Line 1,601 ⟶ 1,655:
let () =
Random.self_init ();
test ~n:10 ~trials:1_000_000</
Executing:
Line 1,613 ⟶ 1,667:
=={{header|PARI/GP}}==
gp can't read individual lines from a file (PARI would be needed for that) but it can do the simulation easily. The <code>random()</code> function produces high-quality pseudorandom numbers (via Brent's [http://maths-people.anu.edu.au/~brent/pub/pub224.html XORGEN]) so the output passes a chi-square test easily (p = 0.848).
<
my(chosen=1);
for(k=2,n,
Line 1,620 ⟶ 1,674:
chosen;
}
v=vector(10); for(i=1,1e6, v[one_of_n(10)]++); v</
{{out}}
<pre>%1 = [99933, 100021, 100125, 100071, 99876, 99485, 100108, 100183, 99861, 100337]</pre>
Line 1,626 ⟶ 1,680:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
{$IFDEF FPC}
Line 1,668 ⟶ 1,722:
writeln('Number of times line ', i, ' was selected: ', lines[i]);
writeln('Total number selected: ', sum(lines));
end.</
Output:
<pre>% ./OneOfNLines
Line 1,685 ⟶ 1,739:
===using int-random===
int-random needn't the calculation of (1.0 /i).That is 3-times faster.I implemented the use of reading a random line of a textfile as discribed.In that case, there is no need to use the functoin one_of_n .
<
Program OneOfNLines(InPut,Output);
{$h+} //use Ansistring
Line 1,771 ⟶ 1,825:
inc(LnCnt,cntLns[i]);
writeln('Total number selected: ', LnCnt);
end.</
;Output:
<pre>
Line 1,788 ⟶ 1,842:
=={{header|Perl}}==
<
use warnings;
use strict;
Line 1,806 ⟶ 1,860:
my @freq;
++$freq[ one_of_n($size) - 1 ] for 1 .. $repeat;
print "@freq\n";</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">one_of_n</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">line_num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">()<</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">i</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">line_num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">line_num</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">counts</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1000000</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">one_of_n</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">counts</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,830 ⟶ 1,888:
=={{header|PicoLisp}}==
<
(let R 1
(for I N
Line 1,840 ⟶ 1,898:
(do 1000000
(inc (nth L (one-of-n 10))) )
L )</
Output:
<pre>-> (99893 100145 99532 100400 100263 100229 99732 100116 99709 99981)</pre>
Line 1,846 ⟶ 1,904:
=={{header|PowerShell}}==
'''Translation''' of: '''C#'''
<syntaxhighlight lang="powershell">
function Get-OneOfN ([int]$Number)
{
Line 1,879 ⟶ 1,937:
[PSCustomObject]$table
</syntaxhighlight>
{{Out}}
<pre>
Line 1,894 ⟶ 1,952:
</pre>
The above version runs in ~650 seconds, because of the large overhead of calling PowerShell functions and binding their parameters. With a small change to move the function into a class method, the parameter binding becomes faster, and swapping Get-Random for System.Random, the overall code runtime drops to ~20 seconds. Changing the ordered hashtable to a Generic Dictionary reduces it again to ~15 seconds:
<
[System.Random]$rng
Line 1,934 ⟶ 1,992:
}
[PSCustomObject]$table</
=={{header|PureBasic}}==
<
ProcedureReturn Random(1000000) / 1000000
EndProcedure
Line 1,969 ⟶ 2,027:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>99959 100011 100682 100060 99834 99632 100083 99817 99824 100098</pre>
Line 1,975 ⟶ 2,033:
=={{header|Python}}==
To be more in line with the spirit of the problem, <code>one_of_n</code> will take the "lines" as an iterator, guaranteeing that it only traverses the lines one time, and does not know the length until the end.
<
try:
range = xrange
Line 1,994 ⟶ 2,052:
return bins
print(one_of_n_test())</
;Sample output:
Line 2,000 ⟶ 2,058:
=={{header|R}}==
<
{
choice <- 1L
Line 2,013 ⟶ 2,071:
}
table(sapply(1:1000000, function(i) one_of_n(10)))</
Sample output:
Line 2,020 ⟶ 2,078:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 2,084 ⟶ 2,142:
|#
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Python}}
<syntaxhighlight lang="raku"
my $choice;
$choice = $_ if .rand < 1 for 1 .. $n;
Line 2,101 ⟶ 2,159:
}
say one_of_n_test();</
Output:
<pre>100288 100047 99660 99773 100256 99633 100161 100483 99789 99910</pre>
=={{header|REXX}}==
<
N= 10 /*the number of lines in pseudo-file. */
@.= 0 /*zero all the (ten) "buckets". */
Line 2,119 ⟶ 2,177:
do j=1 for N /*display randomness counts (buckets). */
say "number of times line" right(j, 2) "was selected:" right(@.j, 9)
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the internal default input:}}
<pre>
Line 2,135 ⟶ 2,193:
=={{header|Ring}}==
<
cnt = list(10)
for nr = 1 to 10000
Line 2,150 ⟶ 2,208:
next
return d
</syntaxhighlight>
<pre>
1 : 15
Line 2,165 ⟶ 2,223:
=={{header|Ruby}}==
<
# # Get a random line from /etc/passwd
# line = open("/etc/passwd") {|f| random_line(f) }
Line 2,193 ⟶ 2,251:
chosen.keys.sort.each do |key|
puts "#{key} chosen #{chosen[key]} times"
end</
<pre>$ ruby one-of-n.rb
Line 2,208 ⟶ 2,266:
=={{header|Run BASIC}}==
<
c = oneOfN(10)
chosen(c) = chosen(c) + 1
Line 2,222 ⟶ 2,280:
next
oneOfN = choice
END FUNCTION</
<pre>1 99034
2 98462
Line 2,237 ⟶ 2,295:
{{libheader|rand}}
You could also use `rand::seq::sample_iter` which uses a more general version of this problem, Reservoir Sampling: https://en.wikipedia.org/wiki/Reservoir_sampling.
<
use rand::{Rng, thread_rng};
Line 2,265 ⟶ 2,323:
println!("{:?}", dist);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,272 ⟶ 2,330:
=={{header|Scala}}==
<
if (n < 1) i else one_of_n(n - 1, if (scala.util.Random.nextInt(j) == 0) n else i, j + 1)
Line 2,281 ⟶ 2,339:
}
println(simulate(10, 1000000) mkString "\n")</
{{out}}
<pre>100014
Line 2,295 ⟶ 2,353:
=={{header|Seed7}}==
<
const func integer: one_of_n (in integer: n) is func
Line 2,322 ⟶ 2,380:
end for;
writeln;
end func;</
Output:
Line 2,331 ⟶ 2,389:
=={{header|Sidef}}==
{{trans|Raku}}
<
var choice
n.times { |i|
Line 2,347 ⟶ 2,405:
}
say one_of_n_test()</
{{out}}
Line 2,353 ⟶ 2,411:
=={{header|Swift}}==
<
var result = 1
for i in 2...n {
Line 2,368 ⟶ 2,426:
}
println(counts)</
{{Output|Sample Output}}
Line 2,374 ⟶ 2,432:
=={{header|Tcl}}==
<
proc 1ofN {n} {
for {set line 1} {$line <= $n} {incr line} {
Line 2,387 ⟶ 2,445:
incr count([1ofN 10])
}
parray count; # Alphabetic order, but convenient</
Sample output:
<pre>
Line 2,403 ⟶ 2,461:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Dim chosen(10)
Line 2,423 ⟶ 2,481:
Next
End Function
</syntaxhighlight>
{{Out}}
Line 2,442 ⟶ 2,500:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var rand = Random.new()
Line 2,462 ⟶ 2,520:
freqs[num-1] = freqs[num-1] + 1
}
for (i in 1..n) Fmt.print("Line $-2d = $,7d", i, freqs[i-1])</
{{out}}
Line 2,479 ⟶ 2,537:
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">func One_of_n(N);
int N, Choice, Line;
[Choice:= 1;
for Line:= 2 to N do
if Ran(1_000_000) < 1_000_000/Line then Choice:= Line;
return Choice;
];
int Counters(1+10), I, N;
[for I:= 1 to 10 do Counters(I):= 0;
for I:= 1 to 1_000_000 do
[N:= One_of_n(10);
Counters(N):= Counters(N)+1;
];
for I:= 1 to 10 do
[IntOut(0, Counters(I));
ChOut(0, ^ );
];
]</syntaxhighlight>
{{out}}
<pre>
99477 99885 99826 100174 99902 99766 100287 100125 100386 100172 </pre>
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">
dim elegido(10)
Line 2,503 ⟶ 2,584:
next L0
end</
=={{header|zkl}}==
{{trans|Python}}
<
#if 0 // iterative
choice:=Void;
Line 2,527 ⟶ 2,607:
}
println(one_of_n_test());</
A Ref is a strong reference to a value, Ref.set(value) sets the Ref, Ref.value gets the value. A pump pumps data through a list of functions into a sink, Void.Skip skips this value (ie same as continue in a loop).
{{out}}
|