One of n lines in a file: Difference between revisions

No edit summary
Line 1,740:
Line 10 : 99600
</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:
<lang powershell>class Holder {
[System.Random]$rng
 
Holder()
{
$this.rng = [System.Random]::new()
}
 
[int] GetOneOfN([int]$Number)
{
$current = 1
for ($i = 2; $i -le $Number; $i++)
{
$limit = 1 / $i
if ($this.rng.NextDouble() -lt $limit)
{
$current = $i
}
}
return $current
}
}
 
$table = [Collections.Generic.Dictionary[int, int]]::new()
$X = [Holder]::new()
 
1..10 | ForEach-Object {
$table.Add($_, 0)
}
for ($i = 0; $i -lt 1e6; $i++)
{
$index = $X.GetOneOfN(10) - 1
$table[$index] += 1
}
[PSCustomObject]$table</lang>
 
=={{header|PureBasic}}==
Anonymous user