Create a random number

Is it possible to create a random number from a set of numbers in C #.

For example, I have an array of numbers from 1-90 and after the number has been called the property of this number. Therefore, I want to generate numbers in which this property has not changed. Therefore, it will randomly call numbers from 1 to 90 units.

I did this using a loop, but if possible, I just wanted to use the Quiker and Cleaner method.

My current code is:

    public object GenerateNumber()
    {
        bool alreadyCalled = false;
        while (!alreadyCalled)
        {
           Random randomNumber = new Random(System.DateTime.Now.Millisecond);
            int RandomNumberCalled = randomNumber.Next(1, 91);             


            if (Numbers.ToList().Find(x => x.Number == RandomNumberCalled).IsCalled != null)
            {    

             // change number to is called and do other things. 

            }
        }
        return false;
    }
+3
source share
4 answers
list<int> myNumbers=GetNumbers();
Random r=new Random();
while (myNumbers.Count()>0)
{
  int index=r.Next(myNumbers.Count());
  ReportSelectedNumber(myNumbers[index]);
  myNumbers.RemoveAt(index);
}

Make sure you have GetNumbers()one that will return to you the list from which you want to select your numbers, and ReportSelectedNumber()to do something with the newly selected number.

0
source

List , . shuffle, . Knuth shuffling ( ).

+10

, , 100%. . , - , .

+6

  • Using Random(...)in a loop will cause repetitions when the seed is the same. In your example, the same millisecond will often be deleted.

  • Random numbers are repeated. With a large number of iterations, you expect that the distribution will be fairly even for each number in the range, but for any given randomly generated number, it will not be able to know the previously generated numbers.

To answer your question where you really need a shuffled list of numbers, you should be able to adapt it in your code:

var randomOrderInts = Enumerable.Range(1, 91).OrderBy(x => Guid.NewGuid());
0
source

Source: https://habr.com/ru/post/1769141/


All Articles