I want to generate a random number in Befunge, from 0 to n, where n is an arbitrary number. How would I go about doing this?
I thought of trying this (this example has 2 chained chunks of code to show how it works):
v v
?#>?#>
1 1
+ +
> ^> ^
and repeating as needed, but I would need n copies of that chunk of code.
Is there a better way I can generate a random number like rand(0, 10) in other languages?
Nerdsniped!
Here's my solution:
Enter on the left, with
non the stack. Each|marks a new phase of the algorithm.n n 0 0 nand transform thatninto2 2 ... 2 2.n n 0 0 2^kfork >= lg n.2^kintom=2^k + 2^{k-1} + 2^{k-2} + ... + 4 + 2 + 1, except that we use?to skip each term with 50% probability.n n minto (ifn > m)m, and print it; or (ifn <= m)n, and return to the beginning of the entire algorithm.This generates an unbiased uniform distribution in the half-open range
[0..n), for anynsupplied by the caller.Here's a test harness that generates and prints
52*:*= 100 unbiased integers from the half-open range[0, 10'000). Run it on tio.run.