math.random和shuffle洗牌算法

【math.random】

math.random() --返回一个[0, 1)之间的浮点数
math.random(100) --返回一个[1, 100]间的整数
math.random(1, 100) --返回一个[1, 100]间的整数
math.random(20, 30) --返回一个[20, 30]间的整数

 

【什么时候调用math.randomseed(os.time())?】
不需要每次都调用, 只需要lua虚拟机启动的时候调用一次就可以,频繁调用反而容易得到相同的伪随机序列

math.randomseed(os.time())
math.random() --初始化后需要预调用一次

 

【不过有的时候我们反而需要得到相同的伪随机序列】

# 比如: 战斗回放, 帧同步需要保证所有客户端生成相同的概率这种

# 这个时候我们只要提供相同的seed种子,就能得到相同的伪随机序列

 

【shuffle洗牌算法】

# Fisher–Yates随机置乱算法

function shuffle(arrTb)
    local n = #arrTb
    for i=1,n do
        local r = math.random(n)
        local temp = arrTb[i]
        arrTb[i] = arrTb[r]
        arrTb[r] = temp
    end
end 

 

【参考】

lua math.random() - 吴筱军 - 博客园 (cnblogs.com)

lua 随机数 math.random()和math.randomseed()用法_weixin_30846599的博客-CSDN博客

Lua库函数——math.randomseed()、os.time()的使用_闻人放歌的博客-CSDN博客_math.randomseed

随机洗牌算法_断天涯zzz的博客-CSDN博客

 

posted @ 2022-03-25 21:37  yanghui01  阅读(144)  评论(0编辑  收藏  举报