0

How can I generate random numbers with no repeat in C#. I have one array and I want to fill every room with random numbers from 0 to 9. Each room shoud have diffrent numbers. I use this:

for (int i = 0; i < 20; i++)
{
    Random rnd = new Random();
    int temp = 0;
    temp = rnd.Next(0, 9);
    page[i] = temp;
}

But I get same number in evey room's of array.

2
  • 1
    "I just want to know how i can generate random numbers with no repeat in c#?" - This is not possible. A random number is suppose to repeat otherwise its not actually a random number generator but a unique value generator which is trival to code. Your code is also flawed because you will always have the same seed value. May 21, 2012 at 16:45
  • You talk about rooms but have a page array!? Do you mean every entry in array page shall be unique? Do I understand you right that you want 20 digits in page, all being distinct? Jan 14, 2016 at 17:07

7 Answers 7

5

With such a small list of numbers to choose from you can simply generate a list that contains all of them and then shuffle them.

4

Your problem is that you are creating the Random object in every loop. The Random object must be created only once. Try this instead:

Random rnd = new Random(); // <-- This line goes out of the loop        
for (int i = 0; i < 20; i++) {
    int temp = 0;
    temp = rnd.Next(0, 9);
    page[i] = temp;
}
0

This will create a unique range of 1 to rangeEx inclusive. The next two lines create a random number Generator and orders the IEnumerable range with a randome number. this is then called with ToArray and returned!

   private int[] RandomNumber(int rangeEx)
    {
        var orderedList = Enumerable.Range(1, range);
        var rng = new Random();
        return orderedList.OrderBy(c => rng.Next()).ToArray();
    }
-1
        ArrayList page=new ArrayList();
        int random_index;            
        random rnd = new Random();

        for (int i = 0; i < 20; i++)
        {
            do                            
            {
                random_index = rnd.Next(10);
                if (!(page.Contains(random_index)))
                                break;
            } while (page.Contains(random_index));
            page.Add(random_index);
        }
1
  • Can you explain your answer a bit more?
    – Benvorth
    Nov 23, 2014 at 19:35
-1
    public Form1()
    {
        InitializeComponent();
    }
    int A, B;
    string Output;
    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            while (A == B)
            {
                Random r = new Random();
                A = r.Next(1, 6);
            }
            Output = Output + A;
            B = A;
        }
        textBox1.Text = Output;
    }

Output: 24354132435213245415 (not repeating)

-1
using System;

using System.Collections.Generic;

using System.Linq;


namespace nonRepeatableRndm
{

    class Program
    {
        //variable with the Values
        List<string> RandomVal = new List<string>();
        //variable to compare the randomly genarated Values
        List<string> CompaerbyString = new List<string>();
        //Variable that gets Value from  the list Values
        string DisplayVal;
        //instantiates the Random Class
        Random r;
        //this Method gives Value to the list and initializes th the Random Class
        void setVal()
        {
            //Adding to the list
            RandomVal.Add("A");
            RandomVal.Add("b");
            RandomVal.Add("c");
            RandomVal.Add("d");
            RandomVal.Add("e");
            RandomVal.Add("f");
            RandomVal.Add("g");
            RandomVal.Add("h");
            RandomVal.Add("i");
            RandomVal.Add("j");
            RandomVal.Add("k");
            RandomVal.Add("l");
            RandomVal.Add("m");
            RandomVal.Add("n");
            RandomVal.Add("o");
            RandomVal.Add("p");
            RandomVal.Add("q");
            RandomVal.Add("r");
            RandomVal.Add("s");
            RandomVal.Add("t");
            RandomVal.Add("u");
            RandomVal.Add("v");
            RandomVal.Add("w");
            RandomVal.Add("x");
            RandomVal.Add("y");
            RandomVal.Add("z");

            //Instantiating the Random Method
            r = new Random();
        }
        //This method Gives Out the Random Values
        public void DisplayRand()
        {

           //Setting Random Index 
           int getIndex =  r.Next(0, RandomVal.Count - 1);
            //Now we are trying to pass a random value to the String 
            DisplayVal = RandomVal.ElementAt<string>(getIndex);
            //we are testing to see if String in Display is contained in the List that will used Compare
            if (!CompaerbyString.Contains(DisplayVal))
                Console.WriteLine(DisplayVal.ToUpper());
            else
            {
                try
                {
                    this.DisplayRand();
                }
                catch(Exception e)
                {
                    Console.WriteLine("You have Reached the End of the list...");
                    Environment.Exit(0);
                }
            }
            //Adding Corrent DisplayVal's Value to the List for Comparison
            CompaerbyString.Add(DisplayVal);
        }
        //This is Simple method that Calls the Display
        void Call()
        {
            //This For loop is to Ensure we have no Stack Overflow
            for ( int i = 0; i < RandomVal.Count-1;i++)
            {
                this.DisplayRand();

            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Random Values With Out Repeatating Any Value");
            //Simple Instantiation
            Program dis = new Program();
            //Simple Call
            dis.setVal();
            //Simple Call
            dis.Call() ;
            Console.ReadLine();   
        }
    }
}

This is the output

0
-2

100 % right

   public int[] UniqeRandomArray(int size , int Min , int Max ) {

        int [] UniqueArray = new int[size];
        Random rnd = new Random();
        int Random;

        for (int i = 0 ; i < size ; i++) {

            Random = rnd.Next(Min, Max);

            for (int j = i; j >= 0 ; j--) {

                if (UniqueArray[j] == Random)
                { Random = rnd.Next(Min, Max); j = i; }

            }

            UniqueArray[i] = Random;

        }

        return UniqueArray;

    }

// Notice to be unique [Max - Min > size] NOT equal

1
  • Also this is not at all efficient for large array instead you may create a sorted array and use one shuffling techniques to create the randomness
    – Anoush
    Dec 1, 2013 at 8:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.