how to find a random element in a sorted array of unknown length.
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?.
how do I find if an element is part of the array?
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.
m
, , , .
, -, , . , , .
#, int () IEnumerable<int> (items):
int
IEnumerable<int>
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, . , . , - .
Source: https://habr.com/ru/post/1755110/More articles:tkinter: ΠΏΠ΅ΡΠ΅ΡΠ°ΡΠΊΠΈΠ²Π°Π½ΠΈΠ΅ Π²ΠΈΠ΄ΠΆΠ΅ΡΠΎΠ² - python-3.xHow to serve multiple domains with a single ASP.NET MVC application? - asp.net-mvcunit testing - to cover test code for java - javaΠ Π°Π·Π»ΠΈΡΠΈΡ Tomcat ΠΈ Jetty ΠΏΡΠΈ ΡΠ°Π±ΠΎΡΠ΅ ΠΏΡΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠΉ Grails - tomcathttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1755109/an-error-occurred-loading-a-configuration-file-failed-to-start-monitoring-changes-to-share&usg=ALkJrhgLASyMfzcFsHfP2M10XFS-ShJm1ADuplicate / import Xcode projects from one Mac to another - xcodeΠΠΈΠ½Π°ΠΌΠΈΡΠ΅ΡΠΊΠΈΠ΅ Π±ΠΈΠ±Π»ΠΈΠΎΡΠ΅ΠΊΠΈ Sandboxing Π‘++ - c++How to change an Xcode 4 project as machine independent, such as Visual Studio or Eclipse - ioshttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1755114/getting-a-visitors-facebook-info-without-app-permission-how-does-yelp-do-it&usg=ALkJrhj_tp9NpxsBQWwR5gyu6r0kL57o4wHow to configure PHP to display detailed errors instead of a 500 error page? - phpAll Articles