Hello, thank you if you are going to read this.
Problem
So I have two tables.
1st is Table A, it has 100 objects.
2nd is Table B, it has 5 objects
So I am trying to pick 5 random objects from table A. Then parent all the objects in Table B to the random 5 objects.
How will I achieve this?
Any help is appreciated!
This?
for Index = 1, 5 do
local RandomA = TableA[math.random(1, #TableA)]
TableB[Index].Parent = RandomA
end
1 Like
Thank you that gave me a basic idea on how I will implement this into my game
local shuffle = function(tbl)
local j
for i = 1, #tbl do
j = math.random(#tbl)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end
--example, randomize song playlist
shuffle(playList)
print(table.unpack(playList))
--example, first 5 numbers of a shuffled sequence
shuffle(sequence)
for i = 1, 5 do
print(i, sequence[i])
end
This is in case you wanted to make sure you did not get the same item multiple times in a row
Other solution without needing to shuffle the table:
local randSelect = function(tbl, count)
local result, lookup = table.create(count), {}
local j
for i = 1, count do
repeat
j = math.random(#tbl)
until not lookup[j]
lookup[j] = i
results[i] = tbl[j]
end
return results
end
print(table.concat(randSelect(sequence, 5), ", "))
5 Likes
thank you so much for your well written answer, this helped me a ton!
Thanks again