Home c# How to generate a random number in the interval without repetitions?

How to generate a random number in the interval without repetitions? [Duplicate]

Author

Date

Category

You need to generate a random number in the range from 1 to 30 inclusive without repetitions. How to do it?


Answer 1, Authority 100%

Basic idea: write unique numbers to the list. We generate a number from 0 to n , where n List length of the number . After generating , delete from the list of the generated number.

Private Static Void Main (String [] Args)
{
  var random = new random ();
  var numbers = enumerable.range (1, 30) .tolist ();
  var numberscopy = new list & lt; int & gt; (numbers);
  for (var i = 0; i & lt; numbers.count; i ++)
  {
    var pickindex = random.next (numberscopy.count);
    VAR RANDNUMBER = NUMBERSCOPY [PICKINDEX];
    Console.Writeline ($ "Generated Value: {RANDNUMBER}");
    numberscopy.removeat (PickIndex);
  }
  Console.ReadLine ();
}

ATTENTION : You can repeat such generation until the numbers are terminated in the list. Next, it will be necessary to re-create a list of numbers.


wrote a class that generates numbers without repetitions until they are running out, after which the second circle generates the same numbers without repetitions, etc.

Public Class Distinctrandom
{
  Private Static Readonly Random _Random = New Random ();
  Private readonly int [] _numbers;
  Private List & lt; int & gt; _notgeneratedNumbers;
  Public Distinctrandom (int [] generateFrom)
  {
    _numbers = generatefrom;
    _notgeneratedNumbers = New List & LT; Int & GT; (GenerateFrom);
  }
  Public int NEXT ()
  {
    if (! _notgeneratedNumbers.any ())
    {
      _notgeneratedNumbers = New List & lt; int & gt; (_ numbers);
    }
    var pickindex = _random.next (_notgeneratednumbers.count);
    var randnumber = _notgeneratedNumbers [PickIndex];
    _notgeneratedNumbers.Removeat (PickIndex);
    RETURN RANDNUMBER;
  }
}

Usage:

Private Static Void Main (String [] Args)
{
  var numbers = enumerable.range (1, 30) .toarray ();
  Var Distinctrandom = New Distinctrandom (Numbers);
  var n = 50;
  For (var i = 0; i & lt; n; i ++)
  {
    var randnumber = distinctrandom.next ();
    Console.Writeline ($ "Generated Number: {RANDNUMBER}");
  }
  Console.ReadLine ();
}

Answer 2, Authority 100%

Fisher-Yetsa Touch

Random Random = New Random ();
int n = 30;
int [] array = enumerable.range (1, n) .toarray ();
for (int i = 0; i & lt; n; n ++)
{
  int j = random.next (n);
  int x = array [i];
  Array [i] = Array [J];
  array [j] = x;
}
Console.WriteLine (String.join (", Array));

output

5 24 16 1 8 17 14 23 12 9 7 21 2 11 4 30 28 10 13 29 3 25 20 6 15 18 22 19 26 27 27

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions