Jump to content

One of n lines in a file: Difference between revisions

Adding Lua
m (→‎{{header|REXX}}: changed the REXX program description comment.)
(Adding Lua)
Line 1,112:
9 1002
10 1040
</pre>
 
=={{header|Lua}}==
<lang Lua>
math.randomseed(os.time())
 
local n = 10
local trials = 1000000
 
function one(n)
local chosen = 1
for i = 1, n do
if math.random() < 1/i then
chosen = i
end
end
return chosen
end
 
-- 0 filled table for storing results
local results = {}
for i = 1, n do results[i] = 0 end
 
-- run simulation
for i = 1, trials do
local result = one(n)
results[result] = results[result] + 1
end
 
print("Value","Occurrences")
print("-------------------")
for k, v in ipairs(results) do
print(k,v)
end
</lang>
{{Out}}
<pre>
Value Occurrences
-------------------
1 99393
2 100092
3 100412
4 100139
5 99773
6 99802
7 100020
8 99941
9 100063
10 100365
</pre>
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.