lua连续随机数

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

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

   写不出就翻译老外的。

有两种方法:

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

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

 

代码如下:

--产生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

性能测试:

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))

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

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

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

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

posted @ 2014-01-21 19:07  半山th  阅读(2058)  评论(0编辑  收藏  举报