Designing an arbitrary random class

I know that C # has a Random class and possibly several classes in LINQ, but if I were to write my own code to randomly select an item from a collection without using any built-in .NET objects, how can I do this?

I can’t cover up the logic required for this - how would I tell the system when to stop the iteration and select the current value - at random?

EDIT: This is a hypothetical question. This is not related to production coding. I'm just curious.

thanks

+3
source share
7 answers

, - -, . , . , - 00 99, .

0

.

Random r = new Random();
int randomIndex = r.Next(0, myCollection.Size -1);
var randomCollectionItem = myCollection[randomIndex];

, .

+4

. , , , , - . .

, , .

+3

. , , .

, . " ", :

rnd = seed; // some starting value 
rnd = (a * rnd + b)  % c;  // next value
...

a, b cthese . .


- "" - , , .. - , . , (IIRC , , , ).


- - - .

+2

, , , . , - , , , .

int index = customRandomGenerator.Next();
var selection = items[index];

, ( ), :

int index = customRandomGenerator.Next();
Item selection = null;
for (int i = 0; i < items.Length; i++) 
{
  if (i == index)
  {
    selection = items[i];
    break;
  }
}
0

" " .NET Framework System.Cryptography.RandomNumberGenerator - Reflector, , ? , , - - Random - Reflector.

0

, , , , , , , , , .

0

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


All Articles