Reputation: 53
I was wondering how can I get 8 unique random numbers in my listbox, code so far:
lbLeft.Items.Clear();
Random rnd = new Random();
int n = rnd.Next();
int x = 8;
do
{
lbL.Items.Add(rnd.Next(0, 20));
} while ((lbLeft.Items.Count != x));
It is filling the listbox with 8 random numbers, but I need them unique.
Any help would be greatly appreciated,
Upvotes: 0
Views: 3031
Reputation: 1581
You can create a list from 0 to n, choose a random from that list, remove it and decrement your max value by one. This way you know that you will only go through the for look x times.
lbLeft.Items.Clear();
Random rnd = new Random();
int x = 8;
int upperBound = 20;
List<int> uniqueInts = new List<int>(upperBound);
for (int i = 0; i < upperBound; i++)
uniqueInts.Add(i);
for (int i = 0; i < x; i++ )
{
int index = rnd.Next(0, uniqueInts.Count);
lbLeft.Items.Add(uniqueInts[index]);
uniqueInts.RemoveAt(index);
}
Upvotes: 1
Reputation: 1327
lbLeft.Items.Clear();
Random rnd = new Random();
for (int i = 0; i < 8; i++)
{
n = rnd.Next(0, 20);
while(lbLeft.Contains(n.ToString())
{
n = rnd.Next(0, 20);
}
al.Add(n);
lbL.Items.Add(n.ToString())
}
Upvotes: 0
Reputation: 12439
Add this check in your code: if(!lbl.Items.Contains(n))
lbLeft.Items.Clear();
Random rnd = new Random();
int n = rnd.Next();
int x = 8;
do
{
n = rnd.Next(0, 20);
if(!lbl.Items.Contains(n))
lbL.Items.Add(n);
} while ((lbLeft.Items.Count != x));
Upvotes: 4
Reputation: 24316
HashSet<int> uniques = new HashSet<int>();
Random random = new Random();
while(uniques.Count!= 8)
{
uniques.Add(random.Next(0,20)); //terrible upper bound
}
The Set
will guarantee that duplicates cannot be contained within it.
Upvotes: 6