-2

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.

  • 1
    Search for "shuffle". – Floris Dec 11 '13 at 19:26
  • Why do you say that, that the lottery does not have the same numbers. Do you mean not the same number in a set of numbers? – Hogan Dec 11 '13 at 19:26
  • possible duplicate of [how do i seed a random class to avoid getting duplicate random values](http://stackoverflow.com/questions/1785744/how-do-i-seed-a-random-class-to-avoid-getting-duplicate-random-values) – John Dec 11 '13 at 19:27
  • @Hogan Surely you know how lotteries work. Combination of `k` number out of `n` without replacement. – millimoose Dec 11 '13 at 19:27
  • @Hogan When you have a lottery you're selecting, say, 5 numbers between 1 and 100, but those 5 numbers should be unique. The lottery is never 1,1,1,1,1. – Servy Dec 11 '13 at 19:27
  • Yes guys, I answered that question, I'm still not sure it was what was being asked, but I answered what the question seemed to be asking. – Hogan Dec 11 '13 at 19:28
  • possible duplicate of [Select a random N elements from List in C#](http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp) – Alexei Levenkov Dec 11 '13 at 20:06

3 Answers3

1

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.

Hogan
  • 69,564
  • 10
  • 76
  • 117
0

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();
Oleh Nechytailo
  • 2,155
  • 17
  • 26
0

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

Andrew Paes
  • 1,940
  • 1
  • 15
  • 20