简体   繁体   中英

Unique random numbers in listbox

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,

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.

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));

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);

    } 
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())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM