首页 > 其他 > 详细

lua连续随机数

时间:2014-01-21 21:34:33      阅读:485      评论:0      收藏:0      [点我收藏+]

号外:惭愧,工作后几乎没有写博客了,其实是有时间的(每周单休),只是厌烦对着屏幕了,还有懒。

   现在老板换人了,时间会多点,估计正常就每周双休了,决定还是每周写两篇(不一定是love2d),

   写不出就翻译老外的。

有两种方法:

1、把生成的数放到一个表里面,每次随机时判断这个表里是否有,若有再随机一次

2、先生成一个连续的数字表t,每次随机一个数n,把t[n]保存,并移除t[n]

 

代码如下:

bubuko.com,布布扣
--产生1~~m,若有n的则m~~n的数字表
function table.fillNum(m,n)
    local j,k
    if n then
       j=m
       k=n
    else
        j=1
        k=m
    end

    local t={}
    for i=j,k do
        table.insert(t,i)
    end
    return t

end


--产生不相同的从m到n,一共cnt个随机数表
function math.randomx( m,n,cnt ) --方法1
    if cnt>n-m+1 then
        return {}
    end
    local t = {}
    local tmp = {}
    math.randomseed(os.time())
    while cnt>0 do
        local x =math.random(m,n)
        if not tmp[x] then
            t[#t+1]=x
            tmp[x]=1
            cnt=cnt-1
        end
    end
    return t
end
--同上
function math.randomEx(m,n,cnt) --方法2
    if cnt>n-m+1 then
        return {}
    end
    local x=0
    local t={}
    local tmp=table.fillNum(m,n)
    math.randomseed(os.time())
    while  cnt>0 do
       x=math.random(1,n-m+1) 
       table.insert(t,tmp[x])
       table.remove(tmp,x)
       cnt=cnt-1
       m=m+1
      
    end
    return t
end


t=math.randomx(11, 25, 6)
for i=1,6 do
  print(t[i])
end
print("...........")
t=math.randomEx(11, 25, 6)
for i=1,6 do
  print(t[i])
end
bubuko.com,布布扣

性能测试:

bubuko.com,布布扣
t1=os.clock()
for i=1,10000 do
  math.randomEx(11,15,5)
end
t2=os.clock()
for i=1,10000 do
  math.randomx(11,15,5)
end
t3=os.clock()
print((t3-t2)-(t2-t1))
bubuko.com,布布扣

两种方法差别不是很大,而且当在10000后再加2个0时,就需要很长时间了,或者挂掉。

如果需要在相隔较短的时间内生成相差较大的随机数可以把math.randomseed(os.time())

替换为math.randomseed(tostring(os.time()):reverse():sub(1, 6))。

因为在相隔较短时间时os.time()相差不大,reverse可以把字符串倒转,这样就相差大了,详见此文

lua连续随机数

原文:http://www.cnblogs.com/xdao/p/lua_random.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!