How to Generate random numbers without the same number

253 Views Asked by At

Can you please give me the answer how can i generate numbers without the same numbers ? Because i am creating a lottery program, and i want my program having no same numbers because the lottery is not having an output that has the same numbers.

3

There are 3 best solutions below

0
On

I believe what you want to do is use the Set specialized collection. Pick a random item left in the Set and then remove it from the set. Pick another.

0
On

Be careful with multithreading and random initialization.

static Random r = new Random();
static IEnumerable<int> Randoms(int max)
{
    while(true)
        yield return r.Next(max);
}

Usage:

var items = Randoms(50).Distinct().Take(10).ToArray();
0
On

You now you need to put it in a recursive method, but here is a simple way.

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        List<int> numbers = new List<int>();
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);
        numbers.Add(4);
        numbers.Add(5);
        numbers.Add(6);
        numbers.Add(7);

        Random rand = new Random();

        var numbersSfle = numbers.OrderBy(item => rand.Next()).ToList();
        Console.Write(numbersSfle[0].ToString());
        numbers.RemoveAt(0);


        numbersSfle = numbers.OrderBy(item => rand.Next()).ToList();
        Console.Write(numbersSfle[0].ToString());
        numbers.RemoveAt(0);
    }
}

The fiddle:

http://ideone.com/p39Lhg