随机迭代填充Lua中的表 [英] Random iteration to fill a table in Lua

查看:142
本文介绍了随机迭代填充Lua中的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图随机填写一个包含26个值的表格。也就是说,我有一个名为 rndmalpha 的表,我想在整个表中随机插入值。这是我的代码:

I'm attempting to fill a table of 26 values randomly. That is, I have a table called rndmalpha, and I want to randomly insert the values throughout the table. This is the code I have:

rndmalpha = {}
for i= 1, 26 do
  rndmalpha[i] = 0
end

valueadded = 0

while valueadded = 0 do
  a = math.random(1,26)
  if rndmalpha[a] == 0 then
    rndmalpha[a] = "a"
    valueadded = 1
  end
end

while valueadded = 0 do
  a = math.random(1,26)
  if rndmalpha[a] == 0 then
    rndmalpha[a] = "b"
    valueadded = 1
  end
end

...

代码重复直到z,所以这只是一个大概。然而,我遇到的问题是随着表格的填充,随机点击次数减少。这有可能冻结程序,特别是在最后的字母中,因为只有2-3个数字 0 作为值。那么,如果循环在最终达到最后一个数字之前经过一百万次调用会发生什么?有没有一种有效的方式来说,嘿,无视位置6,13,17,24和25,并专注于填补其他人。?就此而言,是否有更有效的方法来做我正在做的事情?

The code repeats itself until "z", so this is just a general idea. The problem I'm running into, however, is as the table gets filled, the random hits less. This has potential to freeze up the program, especially in the final letters because there are only 2-3 numbers that have 0 as a value. So, what happens if the while loop goes through a million calls before it finally hits that last number? Is there an efficient way to say, "Hey, disregard positions 6, 13, 17, 24, and 25, and focus on filling the others."? For that matter, is there a much more efficient way to do what I'm doing overall?

推荐答案

您正在使用的算法看起来非常不高效,在我看来,你需要的是用所有字母表初始化一个表:

The algorithm you are using seems pretty non-efficient, it seems to me that all you need is to initialize a table with all alphabet:

math.randomseed(os.time())
local t = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}    

然后洗牌元素:

for i = 1, #t*2 do
    local a = math.random(#t)
    local b = math.random(#t)
    t[a],t[b] = t[b],t[a]
end  

交换的元素#t * 2 次数给出了随机性。如果您需要更多随机性,请增加改组次数,并使用更好的随机数生成器。 C库提供的 random()函数通常不太好。

Swapping the elements for #t*2 times gives randomness pretty well. If you need more randomness, increase the number of shuffling, and use a better random number generator. The random() function provided by the C library is usually not that good.

这篇关于随机迭代填充Lua中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆