MathUtil.lua
1.47 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
67
68
-- 初始化
function math.randomInit(seed)
seed = seed or skynet.timex()
math.randomseed(tonumber(tostring(seed):reverse():sub(1,6)))
end
-- 随机浮点数
function math.randomFloat(lower, greater)
return math.min(lower, greater) + math.random() * math.abs(greater - lower);
end
function math.randomInt(lower, greater)
return math.random(math.min(lower, greater), math.max(lower, greater))
end
-- 根据权重值从数据集合里面随机出
-- @param dataset 数据集合
-- @param field 权重域
function math.randWeight(dataset, field)
if not dataset then return nil end
field = field or "weight"
-- 计算权值总和
local weightSum = 0
for key, value in pairs(dataset) do
weightSum = weightSum + tonumber(value[field])
end
local randWeight = math.randomFloat(0, weightSum)
for key, value in pairs(dataset) do
if tonumber(value[field]) > 0 then
if randWeight > tonumber(value[field]) then
randWeight = randWeight - tonumber(value[field])
else
return key
end
end
end
return nil
end
function math.illegalNum(num, min, max)
if num == nil then
return true
end
if type(num) ~= "number" then
-- 非数字类型
return true
end
if num ~= num then
-- 非法数字nan
return true
end
if num ~= math.floor(num) then
-- 非整数
return true
end
if num < min or num > max then
return true
end
-- if string.find(tostring(num), '%.') then
-- -- 确保不会出现类似1.0这样的数据
-- return true
-- end
return false
end