This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
legomaniack's profile picture

Random Order?

Started by legomaniack, 07 February 2012 - 09:42 PM
legomaniack #1
Posted 07 February 2012 - 10:42 PM
I was wondering, can you have lua print things in a random order, but not repeating?
for exapmle, if i had

aTable = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }

could i print the contents of aTable in a random, non repeating order such as
4
7
6
5
2
3
1
9
10
8

???

please give input.
Casper7526 #2
Posted 07 February 2012 - 11:58 PM
Well… can you store them in a random order? Because if they are stored in sequential order then yes it does make it a bit more difficult to print them in a random order.

I'll write you up a quick function that should randomize a table for ya.


local function randomizetable(tbl)  -- send a table to this function

for x = 1, #tbl + 0 do -- replacing the 0 with another # will jumble the table up more times but isn't really needed
local rnd = math.random(1, #tbl)
table.insert(tbl, #tbl + 1, tbl[rnd])
table.remove(tbl, rnd)
end

return tbl
end


-- example usage
aTable = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
print (textutils.tabulate(aTable))
aTable = randomizetable(aTable)
print (textutils.tabulate(aTable))
legomaniack #3
Posted 08 February 2012 - 11:42 PM
hmm… i got attempt to call nil when i run that…
Never mind, my fault.

if i randomize tbl = {1,2,3}

and its now 312,
would
tbl[1] = 3
?

i got it. ignore this post.