Blame view

src/utils/MathUtil.lua 1.46 KB
314bc5df   zhengshouren   提交服务器初始代码
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
  -- 初始化
  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
312b9db5   zhouahaihai   背包
42
43
44
  end
  
  function math.illegalNum(num, min, max)
a6c04593   zhengshouren   非法数字判断加强判断
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  	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 math.abs(max - min) > 1000 then
  		-- 防止出现数值过大的情况,在线上环境出现效率问题
  		return true
  	end
312b9db5   zhouahaihai   背包
61
62
  	for i = min, max do
  		if num == i then
a6c04593   zhengshouren   非法数字判断加强判断
63
  			return false
312b9db5   zhouahaihai   背包
64
65
  		end
  	end
a6c04593   zhengshouren   非法数字判断加强判断
66
  	return true
314bc5df   zhengshouren   提交服务器初始代码
67
  end