Lua中随机数重复的问题

我是 Lua 的新手,计划开发 Bingo 游戏。 我已经创建了 25 个网格,并随机生成了数字。 但是网格中的数字重复了。 我尝试了搜索但未能找到解决方法,请朋友们帮帮我。

--输入代码
local widget = require "widget"
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local xaxis = {40,80,120,160,200,40,80,120,160,200,40,80,120,160,200,40,80,120,160,200,40,80,120,160,200}
local yaxis = {40,40,40,40,40,80,80,80,80,80,120,120,120,120,120,160,160,160,160,160,200,200,200,200,200}
local img = {}
local i
local k
local u={}
    for i = 1, 25 do
        img[i] = display.newImageRect( "t.png", 39, 39 )
        img[i].x=xaxis[i]
        img[i].y=yaxis[i]
        math.randomseed( os.time() )
        j = math.random(1,75)
        u[i], u[j] = u[j], u[i]
        img[i] = display.newText(j,0,0,native.systemFont,20)
        img[i].x=xaxis[i]
        img[i].y=yaxis[i]
    end

这些数字是随机生成的,但是数字重复了。

点赞
用户1283847
用户1283847

这是几乎每种编程语言中常见的错误。当您在循环中使用随机数时,应该始终在循环外分配时间种子。因为迭代非常快,每次都会重新分配当前时间,导致生成相同的随机数。

所以你只需要将 math.randomseed(os.time()) 移出循环:

math.randomseed(os.time())

for i = 1, 25 do
    img[i] = display.newImageRect("t.png", 39, 39)
    img[i].x = xaxis[i]
    img[i].y = yaxis[i]
    j = math.random(1, 75)
    u[i], u[j] = u[j], u[i]
    img[i] = display.newText(j, 0, 0, native.systemFont, 20)
    img[i].x = xaxis[i]
    img[i].y = yaxis[i]
end

证明

2013-08-05 06:56:54