lua 不调用外部函数自己实现获取随机数

本文介绍了一个基于Lua语言实现的自定义随机数生成器。该生成器使用特定的常数值并模仿了java.util.Random()的行为。文章详细解释了如何通过不同参数调用来生成不同范围内的随机数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

local random = {}

local a = 25214903917   -- These Values for a and c are the actual values found
local c = 11            -- in the implementation of java.util.Random(), see link
local previous = 0

-- 接收一个整数 seed 作为随机序列种子。
function random.randomseed(seed)
    previous = seed
end

local index = 0

-- 1> 无参调用, 产生 (0,1) 之间的浮点随机数
-- 2> 只有参数 n, 产生 1-n 之间的整数
-- 3> 有两个参数 n, m, 产生 n-m 之间的随机整数

function random.random( ... )
    -- 获取随机数
    local r = a * previous + c
    previous = r
    if r < 0 then
        r = -r
    end
    -- 获取参数个数
    local arg = { ... }
    local count = 0  
    for k,v in pairs(arg) do
        count = count + 1
    end
    -- 根据参数个数来确定取值
    if count == 0 then
        r =  r%1000  -- 取0到1000的随机数,可按照自己意愿随意取值
        r =  r * 1.0
        while true do
            r =  r/10
            if r < 1 then
                break
            end
        end
    elseif count == 1 then
        if arg[1] < 1 then
            error "get random number error"
        elseif arg[1] == 1 then
            r = 1
        else
            r = 1 + r%(arg[1]-1)
        end
    elseif count == 2 then
        if arg[2] < arg[1] then
            error "get random number error"
        elseif arg[2] == arg[1] then
            r = arg[1]
        else
            r = arg[1] + r%(arg[2]-arg[1])
        end
    else
        error "get random number error"
    end
    -- print (index,r)
    index = index+1
    return r
end

return random

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值