Question

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

...

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?

Was it helpful?

Solution

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"}    

and Then shuffle the elements:

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  

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.

OTHER TIPS

Instead of randoming for each letter, go through the table once and get something random per position. The method you're using could take forever because you might never hit it.

Never repeat yourself. Never repeat yourself! If you're copy and pasting too often, it's a sure sign something has gone wrong. Use a second table to contain all the possible letters you can choose, and then randomly pick from that.

letters = {"a","b","c","d","e"}
numberOfLetters = 5

rndmalpha = {}

for i in 1,26 do
    rndmalpha[i] = letters[math.random(1,numberOfLetters)]
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top