<p>Say I have a linked list of numbers of length <code>N</code>. <code>N</code> is very large and I don’t know in advance the exact value of <code>N</code>. </p>

<p>How can I most efficiently write a function that will return <code>k</code> completely <em>random numbers</em> from the list?</p>

[{'answer_id': 54070, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 2, 'selected': False, 'text': '<p>I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.</p>\n\n<p>If you somehow don\'t know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn\'t bias...)</p>\n\n<p>Other than that: "If I were you, I wouldn\'t be starting from here." Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.</p>\n'}, {'answer_id': 54072, 'author': 'Christian Oudard', 'author_id': 3757, 'author_profile': 'https://Stackoverflow.com/users/3757', 'pm_score': -1, 'selected': False, 'text': "<p>Well, you do need to know what N is at runtime at least, even if this involves doing an extra pass over the list to count them. The simplest algorithm to do this is to just pick a random number in N and remove that item, repeated k times. Or, if it is permissible to return repeat numbers, don't remove the item.</p>\n\n<p>Unless you have a VERY large N, and very stringent performance requirements, this algorithm runs with <code>O(N*k)</code> complexity, which should be acceptable.</p>\n\n<p>Edit: Nevermind, Tom Hawtin's method is way better. Select the random numbers first, then traverse the list once. Same theoretical complexity, I think, but much better expected runtime.</p>\n"}, {'answer_id': 54083, 'author': 'George Mauer', 'author_id': 5056, 'author_profile': 'https://Stackoverflow.com/users/5056', 'pm_score': -1, 'selected': False, 'text': "<p>Why can't you just do something like</p>\n\n<pre><code>List GetKRandomFromList(List input, int k)\n  List ret = new List();\n  for(i=0;i&lt;k;i++)\n    ret.Add(input[Math.Rand(0,input.Length)]);\n  return ret;\n</code></pre>\n\n<p>I'm sure that you don't mean something that simple so can you specify further?</p>\n"}, {'answer_id': 54101, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 5, 'selected': False, 'text': '<p>This is called a <a href="http://gregable.com/2007/10/reservoir-sampling.html" rel="noreferrer">Reservoir Sampling</a> problem.  The simple solution is to assign a random number to each element of the list as you see it, then keep the top (or bottom) k elements as ordered by the random number.</p>\n'}, {'answer_id': 54174, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 1, 'selected': False, 'text': '<p>If you don\'t know the length of the list, then you will have to traverse it complete to ensure random picks. The method I\'ve used in this case is the one described by Tom Hawtin (<a href="https://stackoverflow.com/questions/54059/efficiently-selecting-a-set-of-random-elements-from-a-linked-list#54070">54070</a>). While traversing the list you keep <code>k</code> elements that form your random selection to that point. (Initially you just add the first <code>k</code> elements you encounter.) Then, with probability <code>k/i</code>, you replace a random element from your selection with the <code>i</code>th element of the list (i.e. the element you are at, at that moment).</p>\n\n<p>It\'s easy to show that this gives a random selection. After seeing <code>m</code> elements (<code>m &gt; k</code>), we have that each of the first <code>m</code> elements of the list are part of you random selection with a probability <code>k/m</code>. That this initially holds is trivial. Then for each element <code>m+1</code>, you put it in your selection (replacing a random element) with probability <code>k/(m+1)</code>. You now need to show that all other elements also have probability <code>k/(m+1)</code> of being selected. We have that the probability is <code>k/m * (k/(m+1)*(1-1/k) + (1-k/(m+1)))</code> (i.e. probability that element was in the list times the probability that it is still there). With calculus you can straightforwardly show that this is equal to <code>k/(m+1)</code>.</p>\n'}, {'answer_id': 21201378, 'author': 'Richard', 'author_id': 752843, 'author_profile': 'https://Stackoverflow.com/users/752843', 'pm_score': 6, 'selected': True, 'text': '<p>There\'s a very nice and efficient algorithm for this using a method called <strong>reservoir sampling</strong>.</p>\n\n<p>Let me start by giving you its <strong>history</strong>:</p>\n\n<p><strong>Knuth</strong> calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven\'t been able to find Waterman\'s original document, if it exists, which may be why you\'ll most often see Knuth quoted as the source of this algorithm.</p>\n\n<p><strong>McLeod and Bellhouse, 1983</strong> (1) provide a more thorough discussion than Knuth as well as the first published proof (that I\'m aware of) that the algorithm works.</p>\n\n<p><strong>Vitter 1985</strong> (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.</p>\n\n<p>In <strong>pseudocode</strong> the algorithm is:</p>\n\n<pre><code>Let R be the result array of size s\nLet I be an input queue\n\n&gt; Fill the reservoir array\nfor j in the range [1,s]:\n  R[j]=I.pop()\n\nelements_seen=s\nwhile I is not empty:\n  elements_seen+=1\n  j=random(1,elements_seen)       &gt; This is inclusive\n  if j&lt;=s:\n    R[j]=I.pop()\n  else:\n    I.pop()\n</code></pre>\n\n<p>Note that I\'ve specifically written the code to avoid specifying the size of the input. That\'s one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it <em>still</em> assures you that each element you encounter has an equal probability of ending up in <code>R</code> (that is, there is no bias). Furthermore, <code>R</code> contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an <a href="https://en.wikipedia.org/wiki/Online_algorithm" rel="noreferrer">online algorithm</a>.</p>\n\n<p><strong>Why does this work?</strong></p>\n\n<p>McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It\'s pretty, but it would be a bit difficult to reconstruct it here. Therefore, I\'ve generated an alternative proof which is easier to explain.</p>\n\n<p>We proceed via proof by induction.</p>\n\n<p>Say we want to generate a set of <code>s</code> elements and that we have already seen <code>n&gt;s</code> elements.</p>\n\n<p>Let\'s assume that our current <code>s</code> elements have already each been chosen with probability <code>s/n</code>.</p>\n\n<p>By the definition of the algorithm, we choose element <code>n+1</code> with probability <code>s/(n+1)</code>.</p>\n\n<p>Each element already part of our result set has a probability <code>1/s</code> of being replaced.</p>\n\n<p>The probability that an element from the <code>n</code>-seen result set is replaced in the <code>n+1</code>-seen result set is therefore <code>(1/s)*s/(n+1)=1/(n+1)</code>. Conversely, the probability that an element is not replaced is <code>1-1/(n+1)=n/(n+1)</code>.</p>\n\n<p>Thus, the <code>n+1</code>-seen result set contains an element either if it was part of the <code>n</code>-seen result set and was not replaced---this probability is <code>(s/n)*n/(n+1)=s/(n+1)</code>---or if the element was chosen---with probability <code>s/(n+1)</code>.</p>\n\n<p>The definition of the algorithm tells us that the first <code>s</code> elements are automatically included as the first <code>n=s</code> members of the result set. Therefore, the <code>n-seen</code> result set includes each element with <code>s/n</code> (=1) probability giving us the necessary base case for the induction.</p>\n\n<p><strong>References</strong></p>\n\n<ol>\n<li><p>McLeod, A. Ian, and David R. Bellhouse. "A convenient algorithm for drawing a simple random sample." Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. (<a href="http://www.jstor.org/stable/10.2307/2347297" rel="noreferrer">Link</a>)</p></li>\n<li><p>Vitter, Jeffrey S. "Random sampling with a reservoir." ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. (<a href="http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf" rel="noreferrer">Link</a>)</p></li>\n</ol>\n'}]
['https://Stackoverflow.com/questions/54059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']