Aaron L. W- Gabriel
Aaron L. W- Gabriel

Reputation: 107

How to generate unique random integers that do not duplicate

I have created a short program that creates 3 random integers between 1-9 and stores them in an array, however, I would not like any of them to repeat, that is, I would like each to be unique. Is there an easier way to generate 3 unique integers other than having to iterate through the array and comparing each integer to each other? That just seems so tedious if I were to increase my array to beyond 3 integers. This is my code to generate 3 random numbers. I saw other code in Java, but I thought maybe C# has a easier and more efficient way to do it.

var number = new Numbers[3];
Random r = new Random();
for ( int i = 0; i < number.Length; i++)
{
     number[i] = new Numbers(r.Next(1,9));
}
Console.WriteLine("The Three Random Numbers Are:");
foreach(Numbers num in number)
{
    Console.WriteLine("{0}", num.Number);
}

Upvotes: 0

Views: 260

Answers (3)

kkyr
kkyr

Reputation: 3845

I would do something like this:

var range = Enumerable.Range(1, 8);

var rnd = new Random();
var listInts = range.OrderBy(i => rnd.Next()).Take(3).ToList();

Upvotes: 1

Elshan
Elshan

Reputation: 7693

using System;
using System.Collections.Generic;

public class Test
{
    static Random random = new Random();

    public static List<int> GenerateRandom(int count)
    {
        // generate count random values.
        HashSet<int> candidates = new HashSet<int>();
        // top will overflow to Int32.MinValue at the end of the loop
        for (Int32 top = Int32.MaxValue - count + 1; top > 0; top++)
        {
            // May strike a duplicate.
            if (!candidates.Add(random.Next(top))) {
                candidates.Add(top);
            }
        }

        // load them in to a list.
        List<int> result = new List<int>();
        result.AddRange(candidates);

        // shuffle the results:
        int i = result.Count;  
        while (i > 1)
        {  
            i--;  
            int k = random.Next(i + 1);  
            int value = result[k];  
            result[k] = result[i];  
            result[i] = value;  
        }  
        return result;
    }
    public static void Main()
    {
        List<int> vals = GenerateRandom(10);
        Console.WriteLine("Result: " + vals.Count);
        vals.ForEach(Console.WriteLine);
    }
}

Grate explanation and answers from here

Source http://ideone.com/Zjpzdh

Upvotes: 0

ecth
ecth

Reputation: 1245

You could make an array or a list of the numbers that might be generated, e.g. 0, 1, 2, 3. Then you generate a number from 0 to this list's length, e.g. 2 and pick list[2] so for the next time you only have 0, 1, 3 in your list. It takes longer to generate it, especially for long lists but it doesn't repeat numbers.

Upvotes: 0

Related Questions