Generate random numbers without duplicates

Hi I am trying to generate random numbers from 1 to 9, so that the sequence would be like, 3,5,2,7,8,1,4,6,9 and this will be stored in an array. There should be no same number in two different parts in the array. The math.randomseed function can generate unique numbers but the numbers are decimal points starting with 0. How can I generate integers uniquely?

What you need is a shuffling function. There’s a blog post on it somewhere here. Basically you do something like:

local numbers = {1,2,3,4,5,6,7,8,9} for i = 1, 10 do local random1 = math.random(9) local random2 = math.random(9) numbers[random1], numbers[random2] = numbers[random2], numbers[random1] end

This should switch the place of two items in your table ten times in a row, which should be more than enough to get a random range of unique numbers.

Thank you so much, it works!  :slight_smile:

What you need is a shuffling function. There’s a blog post on it somewhere here. Basically you do something like:

local numbers = {1,2,3,4,5,6,7,8,9} for i = 1, 10 do local random1 = math.random(9) local random2 = math.random(9) numbers[random1], numbers[random2] = numbers[random2], numbers[random1] end

This should switch the place of two items in your table ten times in a row, which should be more than enough to get a random range of unique numbers.

Thank you so much, it works!  :slight_smile: