Array of indefinite length

how to find a random element in a sorted array of unknown length.

+3
source share
2 answers

I suppose you mean how do I find if an element is part of the array?not how do I return a random element from the array?.

Use a binary search and assume that the length is very long (do you have an upper bound for sure?). If the middle element mthat you select at each step is outside the bounds of the array (you need a way to talk about it), then restrict the search to those elements with indices smaller than m.

, , , .

+2

, -, , . , , .

#, int () IEnumerable<int> (items):

Random rnd = new Random();
int cnt = 0;
int selected = 0;
foreach (int item in items) {
  if (rnd.Next(++cnt) == 0) {
    selected = item;
  }
}

0 0, , , 0, . 0 1, 0, . , . , - .

+1

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


All Articles