-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharandom.lua
More file actions
66 lines (52 loc) · 1.38 KB
/
Copy patharandom.lua
File metadata and controls
66 lines (52 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
local RandomGenerator = {}
RandomGenerator.__index = RandomGenerator
-- LCG (Linear Congruential Generator).
local A = 1664525
local C = 1013904223
local M = 2^32 -- 4294967296
-- внутренний seed по умолчанию
local defaultSeed = os.time()
-- @param seed (optional)
function RandomGenerator.new(seed)
local self = setmetatable({}, RandomGenerator)
if seed then
self.seed = seed % M
else
defaultSeed = (A * defaultSeed + C) % M
self.seed = defaultSeed
end
return self
end
function RandomGenerator:_next()
self.seed = (A * self.seed + C) % M
return self.seed
end
-- @param min
-- @param max
function RandomGenerator:randomInt(min, max)
if min > max then
min, max = max, min
end
local range = max - min + 1
-- масштабирование _next() до нужного диапазона
return min + self:_next() % range
end
-- @param min
-- @param max
function RandomGenerator:randomFloat(min, max)
min = min or 0.0
max = max or 1.0
if min > max then
min, max = max, min
end
local val_0_1 = self:_next() / M
return min + val_0_1 * (max - min)
end
-- @param seed
function RandomGenerator:setSeed(seed)
self.seed = seed % M
end
--- Возвращает текущее значение сида.
function RandomGenerator:getSeed()
return self.seed
end