0

I need to print numbers from 1 to 50 in random order without repeating it .

static void Main(string[] args)
{
     ArrayList r = new ArrayList();

     Random ran = new Random();      
     for (int i = 0; i < 50; i++)
     {
        r.Add(ran.Next(1,51));

     }

     for (int i = 0; i < 50; i++)
        Console.WriteLine(r[i]);
     Console.ReadKey();
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Take a look at this: http://stackoverflow.com/questions/12294128/generating-random-numbers-and-inserting-into-array-without-repeats – Matheno Oct 04 '13 at 10:13
  • Don't use `ArrayList` anymore. It belongs old days when C# doesn't have _generics_. Use `List` instead. – Soner Gönül Oct 04 '13 at 10:13

3 Answers3

2

What you want here is the Fisher Yates Shuffle

Here is the algorithm as implemented by Jeff Atwood

cards = Enumerable.Range(1, 50).ToList();
for (int i = cards.Count - 1; i > 0; i--)
{
  int n = ran.Next(i + 1);
  int temp = cards[i];
  cards[i] = cards[n];
  cards[n] = temp;
}
Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
1

If you don't want to repeat the numbers between 1 and 50, your best bet is to populate a list with the numbers 1 to 50 and then shuffle the contents. There's a good post on shuffling here: Randomize a List<T>

Community
  • 1
  • 1
Steve
  • 7,171
  • 2
  • 30
  • 52
0

All you need to do is this check if the number already exists in the list and if so get another one:

static void Main(string[] args)
{
    ArrayList r = new ArrayList();

    Random ran = new Random();      
    int num = 0;

    for (int i = 0; i < 50; i++)
    {
        do { num = ran.Next(1, 51); } while (r.Contains(num));
        r.Add(num);
    }

    for (int i = 0; i < 50; i++)
       Console.WriteLine(r[i]);

    Console.ReadKey();
}

Edit: This will greatly increase the effeciency, preventing long pauses waiting for a non-collision number:

    static void Main(string[] args)
    {
        List<int> numbers = new List<int>();

        Random ran = new Random();
        int number = 0;
        int min = 1;
        int max = 51;

        for (int i = 0; i < 50; i++)
        {
            do
            {
                number = ran.Next(min, max);
            }
            while (numbers.Contains(number));

            numbers.Add(number);

            if (number == min) min++;
            if (number == max - 1) max--;
        }

        for (int i = 0; i < 50; i++)
            Console.WriteLine(numbers[i]);

        Console.ReadKey();
    }
Ashigore
  • 4,618
  • 1
  • 19
  • 39