Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating sorted random ints without the sort? O(n)
    primarykey
    data
    text
    <p>Just been looking at a code golf question about <a href="https://stackoverflow.com/questions/350885/create-sort-and-print-a-list-of-100-random-ints-in-the-fewest-chars-of-code">generating a sorted list of 100 random integers</a>. What popped into my head, however, was the idea that you could generate instead a list of positive deltas, and just keep adding them to a running total, thus:</p> <pre><code>deltas: 1 3 2 7 2 ints: 1 4 6 13 15 </code></pre> <p>In fact, you would use floats, then normalise to fit some upper limit, and round, but the effect is the same.</p> <p>Although it wouldn't make for shorter code, it would certainly be faster without the sort step. But the thing I have no real handle on is this: <b>Would the resulting distribution of integers be the same as generating 100 random integers from a uniformly distributed probability density function?</b></p> <p>Edit: A sample script:</p> <pre><code>import random,sys running = 0 max = 1000 deltas = [random.random() for i in range(0,11)] floats = [] for d in deltas: running += d floats.append(running) upper = floats.pop() ints = [int(round(f/upper*max)) for f in floats] print(ints) </code></pre> <p>Whose output (fair dice roll) was:</p> <pre><code>[24, 71, 133, 261, 308, 347, 499, 543, 722, 852] </code></pre> <p><b>UPDATE:</b> <a href="https://stackoverflow.com/questions/1866031/generating-sorted-random-ints-without-the-sort/1866177#1866177">Alok's answer</a> and <a href="https://stackoverflow.com/questions/1866031/generating-sorted-random-ints-without-the-sort/1866055#1866055">Dan Dyer's comment</a> point out that using an <a href="http://en.wikipedia.org/wiki/Exponential_distribution" rel="nofollow noreferrer">exponential distribution</a> for the deltas would give a uniform distribution of integers.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload