TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: How many times will this loop run on average?

1 点作者 aalhour超过 1 年前
A friend of mine shared the following code snippet with me and asked me to guess how many times the loop will run on average:<p><pre><code> for(int i = 0; i &lt; Random(1, 100); i++); </code></pre> I tried to guess the answer analytically and gussed ~50 but the empirical test was surprising to me. Can someone explain why the average is around 12?<p>Runnable code: https:&#x2F;&#x2F;replit.com&#x2F;@aalhour&#x2F;RandomLoop#main.py<p>EDIT: Formatting.

4 条评论

Someone超过 1 年前
In C (and your Python conversion), the <i>i &lt; Random(1, 100)</i> part is evaluated each time through the loop, not once at start of the loop to determine the limit.<p>So, it’s 1% that the loop ends at <i>i = 1</i>, if it takes that hurdle 2% that it ends at <i>i = 2</i>, if it takes that hurdle 3% that it ends at <i>i = 3</i>, etc.<p>The calculation is easier if you phrase that this way:<p>It’s 99% that the loop continues at <i>i = 1</i>, if it takes that hurdle 98% of the rest that it continues at <i>i = 2</i>, if it takes that hurdle 97% that it continues at <i>i = 3</i>, etc.<p>So, the probability to make it past <i>i = n</i> is<p><pre><code> 0,99 × 0,98 × 0,97 × … × (1 - n&#x2F;100) </code></pre> Note that this isn’t necessarily the case in all languages. Pascal, for example, has a real <i>for</i> loop where the limit is evaluated once and the index variable cannot be changed inside the loop, so that the compiler can determine the number of iterations before starting the first iteration.
评论 #38827438 未加载
hardlianotion超过 1 年前
Expected index given by<p>E [X] = \sum_{i \in [2,100)} p(X &lt; i)\prod_{j &lt; i}p (X \ge j)i.<p>Edit: Sorry rest of reply was wrong. Had to account for not hitting until i^th loop.
评论 #38827333 未加载
orbz超过 1 年前
You’re calculating a random number every time the loop runs. If you want an average of 50 you should call random outside the loop and save the value to be compared each time.
评论 #38827340 未加载
haltist超过 1 年前
The only random variable in that code is &quot;Random(1, 100)&quot; and its expected value is 50.