RosettaCodeData/Task/Modified-random-distribution/Pluto/modified-random-distribution.pluto
2026-04-30 12:34:36 -04:00

32 lines
903 B
Text

require "table2"
local fmt = require "fmt"
local function rng(modifier)
while true do
local r1 = math.random()
local r2 = math.random()
if r2 < modifier(r1) then return r1 end
end
end
local modifier = |x| -> (x < 0.5) ? 2 * (0.5 - x) : 2 * (x - 0.5)
$define N = 100000
$define NUM_BINS = 20
$define HIST_CHAR = "■"
$define HIST_CHAR_SIZE = 125
local bins = table.rep(NUM_BINS, 0)
local bin_size = 1 / NUM_BINS
for i = 1, N do
local rn = rng(modifier)
local bn = rn // bin_size
bins[bn + 1] += 1
end
fmt.print($"Modified random distribution with %,s samples in range [0, 1):\n", N)
print(" Range Number of samples within that range")
for i = 0, NUM_BINS - 1 do
local hist = string.rep(HIST_CHAR, math.round(bins[i + 1] / HIST_CHAR_SIZE))
fmt.print("%4.2f ..< %4.2f %s %,s", bin_size * i, bin_size * (i + 1), hist, bins[i + 1])
end