Amortized Analysis What would be the amortized analysis of the following algorithm: ``` function listRandomUnique(count, range) { var list = []; while (list.length < count) { var x = Math.floor(Math.random()*range); if (list.indexOf(x) === -1) { list.push(x); } } return list; } ```
@e.mccormick What makes it an interesting question is that we have a random variable.
Technically speaking, it could never halt. That is the worst case scenario, but realistically it should eventually halt.
We can say \(n\) is the range, and \(k\) is the count. The point here is to get \(k\) integers between \(0\) and \(n\).
At the start, your probability of having to call `Math.random()` again is \(0/n\). But the next time it would be \(1/n\).
When you're trying to get the \(k\)th random integer, you'd have \((k-1)/n\) probability of having to go again.
This is almost more of a probability question than a computer science one.
The worst case scenario or never halting is sort of a useless analysis. I guess the average case scenario is more helpful.
If we say \(r\) is the number of times that `Math.random()` is called, we'd be looking for the expected value of \(r\) in terms of \(n,k\).
Start with \(i=0\), we call it once. \(1\). When \(i=1\) we call it once. \(1\). Then we have \(1/n\) probability we need to call it again. It's a geometric distribution.
\[ E[r]=\sum_{i=0}^{k-1}\frac{n}{n-i} \]
This line is confusing me, does it create a random double between 0 and x? ``` var x = Math.floor(Math.random(x)); ```
And how is the parameter range used in the function?
Haven't seen an argument passed into the Math class's random method before. Just what the no-arg method call results in. I wonder what happens.
ah gotcha.
Join our real-time social learning platform and learn together with your friends!