# Randomizing until 0

Challenge

Sandbox post

Given a positive integer (K) Output a uniformly-random integer (Y) between [0, K).

If Y > 0 Assume K = Y and repeat the process until Y = 0.

Rules

• Input must be printed at first
• Output format as you wish
• 0 must be the final output, Optionally an empty line instead 0
• If the submission is a function, may it return 0 in addition to printing it? – Adám Jul 9 '18 at 12:55
• @Adám yes, you can return in addition – Luis felipe De jesus Munoz Jul 9 '18 at 12:59
• Do I need to seed my RNG? – SIGSTACKFAULT Jul 9 '18 at 16:16
• May we print without delimiters? – Titus Jul 30 '18 at 15:44
• I got curious. It's quite easy to prove that the average number of steps this program takes before it terminates is H(K-1) + 1 where H(K) is the K'th harmonic number. For n=1000, that's 8.484 steps on average. – J.Doe Sep 21 '18 at 14:02

# Pyth, 6 5 4 bytes

.uOW


Try it here!

### How it works

.uOW    Full program. Takes an integer from  STDIN and outputs a list to STDOUT.
.u      Cumulative fixed-point. Apply the given function with a given initial value,
which is implicitly assigned to the input, until a result that has occurred
before is found. Returns the list of intermediate results.
W    Conditional application. If the argument (the current value) is truthy, then
apply the function below, otherwise leave it unchanged.
O     Random integer in the range [0, N).
IOW: at each iteration of .u, assign a variable N to the current value, starting
with the input. If N is not 0, then choose a random integer in [0, N), else
return N unchanged. Whenever we encounter a 0, the next iteration must also
result in a 0, and therefore the loop stops there.

• I saw a way to do this in Pyth but I am a beginner. Respect. Language of the month in August maybe? – ElPedro Jul 9 '18 at 22:17

# C (gcc), 42 bytes

f(_){printf("%d\n",_);(_=rand()%_)&&f(_);}


Try it online!

Uses short-circuited logical and.

f(_){                 // f(int _) {
printf("%d\n",_); // print argument and a newline
(_=rand()%_)      // set _ to rand()%_
&&f(_);}          // short-circuit AND to recursively call f if _ not zero


## C (gcc), 40 bytes (w/o printing initial value)

f(_){printf("%d\n",_=rand()%_);_&&f(_);}


Try it online!

Uses short-circuited logical and.

f(_){              // f(int _) {
printf("%d\n", // print an integer and a newline
_=             // The integer is _ which we set to...
rand()%_);     // a random value modulo the input _
_&&f(_);}      // short-circuit AND to recursively call f if _ not zero

• rand()%_ is not uniform – njzk2 Jul 9 '18 at 17:01
• I'm fully aware that rand() is almost always biased (due to truncation), but the standard doesn't guarantee it (RAND_MAX could in theory be a multiple of all our numbers, just by luck :P though usually it's ~65k). In practice for the ranges we're dealing with it will appear sufficiently random to not stand out against similar submissions in this challenge. – LambdaBeta Jul 10 '18 at 2:47
• that's from the challenge "Output a uniformly-random integer", so, strictly speaking, this is not valid – njzk2 Jul 10 '18 at 2:53
• Strictly speaking all languages here use prng's. None of them will give a true uniform random number (which would require a perfect source of entropy). While many are more uniform than this, that isn't noticeable in log(k) iterations. – LambdaBeta Jul 10 '18 at 11:37
• @GeorgeV.Williams why not? – Ruslan Jul 12 '18 at 9:49

# R, 66 60 56 43 41 bytes

function(n)while(print(n))n=sample(n,1)-1


Try it online!

• I don't think you need >0 and cat(n,"") (empty string) will also work. – Giuseppe Jul 9 '18 at 12:56
• But I think print is more efficient here, as it returns its argument: 56 bytes – Giuseppe Jul 9 '18 at 13:26
• Also 56 bytes: k=scan();while(x<-sample(1:k-1,1))k=c(x,k);cat(rev(k),0) – JAD Jul 9 '18 at 14:04
• I forgot to remove the curly brackets, so you can save 2 more bytes ;) Try it online! – digEmAll Jul 9 '18 at 18:07
• 39 bytes: n=scan();while(print(n))n=sample(n,1)-1 – djhurio Jul 10 '18 at 13:45

# MATL, 6 bytes

tYrqt


Try it online!

### Explanation

        % Do...while
t      %   Duplicate. Takes input (implicit) the first time
Yr     %   Uniform random integer from 1 to n, included
q      %   Subtract 1
t      %   Duplicate. This will be used as loop condition
% End (implicit). Proceeds with next iteration if non-zero
% Display stack (implicit)


# Pepe, 25 bytes

Pepe is a programming language made by user Soaku.

REeErEErReEEreeEREEeEEree


Try it online!

Explanation:

REeErEErReEEreeEREEeEEree # full program

REeE                      # input as num, in stack 1
rEE                   # create loop in stack 2 with name 0
rReEE              # - output and preserve the number in stack 1
reeE          # - output a newline "\n"
REEeEE    # - random number by 0 to input
ree # goto loop with name 0 if stack 1 is not equal
to stack 2


# Perl 6, 18 bytes

{$_,(^*).pick...0}  Try it online! Anonymous code block that returns a list of values. If you don't mind the numbers being ranges, you can do: {^$_,^*.pick...0}


for 17 bytes. Funnily enough, another builtin random function, roll, has the same behaviour in this instance for the same amount of bytes.

# Perl 5.10.0 -pl, 26 bytes

say;say while$_=int rand$_


Try it online!

# Jelly,  4  3 bytes

XƬ0


This is a monadic link (function) that prints an array and returns 0.

Try it online!

### How it works

XƬ0  Monadic link. Argument: n

XƬ   Pseudo-randomly pick (X) an integer k in [1, ..., n], set n = k, and repeat.
Do this 'til (Ƭ) the results are no longer unique and return the array of
unique results, including the initial value of n.
This stops once X returns k with argument k. The second k will be omitted
from the return value.
0  Print the resulting array and set the return value to 0.

• Very nice strikethrough of the 4! – ngm Jul 9 '18 at 14:50
• We wouldn't like crossed out 4 to look like regular 4, would we? – Dennis Jul 9 '18 at 14:54

# Brachylog, 8 bytes

ẉ?ℕ₁-₁ṙ↰


Try it online!

### Explanation

ẉ          Write the input followed by a linebreak
?ℕ₁       The input must be in [1, …, +∞)
-₁ṙ    Generate an integer in [0, …, input - 1] uniformly at random
↰   Recursive call with that random integer as the new input


The recursion will stop once ?ℕ₁ fails, that is, when the input is 0.

# 05AB1E, 8 7 bytes

Δ=L<Ω0M


Try it online!

Explanation

Δ         # loop until value doesn't change
=        # print current value
L<Ω     # push a random number in ([1 ... X] - 1)
# will return -1 when X=0
0M   # push max of that and 0

• Δ=Ý¨Ω0M is equivalent. – Magic Octopus Urn Jul 9 '18 at 18:01

# J, 13 bytes

[:}:? ::]^:a:


On the subway, so apologies for lack of TIO (hopefully there isn’t a lack of correctness).

Outputs a list of values.

Presumably the APL approach will be shorter, but this is what I thought of.

# How it works

^:a: apply repeatedly until convergence, storing intermediate results in an array.

? random integer in range [0, K) for K greater than 0. For 0, it gives a random integer in range (0,1). For a floating point number, it errors.

::] catch an error for an input to ? and instead of erroring, output the input that caused the error.

}: get rid of the last value in the array (this is so that a floating point number isn’t output).

Try it online!

• It is just me or the code returns the same output? – Luis felipe De jesus Munoz Jul 9 '18 at 14:10
• @LuisfelipeDejesusMunoz someone who knows J better than I might be able to explain but I think that RNG always starts with the same seed. There is also the fixed seed ?., but I don’t think I’m using that. – cole Jul 9 '18 at 14:22
• @cole you are correct. – Jonah Jul 9 '18 at 14:46

# JavaScript (ES6), 38 37 bytes

-1 byte thanks to @Arnauld

f=n=>[n,...n?f(Math.random()*n|0):[]]


f=n=>[n,...n?f(Math.random()*n|0):[]]
<input type=number id=a><button onclick="console.log(f(+a.value))">Test</button>

• Can you reduce the math.random at all? e.g. with codegolf.stackexchange.com/a/35648/67066 – Marie Jul 9 '18 at 18:56
• @Marie using new Date%n doesn't really work here, since it doesn't change fast enough to be useful for generating multiple random numbers – Herman L Jul 9 '18 at 19:10

# C, 38 bytes

f(k){printf("%d ",k);k?f(rand()%k):0;}


Try it online

Ungolfed

void f(int k){
printf("%d ",k);
if(k)
f(rand()%k);
}

• You can save a byte by replacing the ternary operator with a &&; also, you may want to consider seeding the RNG in your main function: Try it online! – ErikF Jul 9 '18 at 18:56
• You can also get rid of the ternary altogether and terminate in an error. 34 bytes – Jo King Jul 10 '18 at 6:43

# Pyth, 4 bytes

W
~O


Try it online!

This basically implements the algorithm:

\begin{align} % Unknown environment algorithm :( &Q \gets \text{input} \\ &\mathbf{Repeat} \\ &\begin{array}{cl} 1. & temp \gets Q \\ 2. & Q \gets \text{unif}\{ 0, Q - 1 \} \\ 3. & \mathtt{Print}(temp) \end{array} \\ &\mathbf{Until} \quad temp = 0 \end{align}

To translate the Pyth into the algorithm, we can mostly just examine what each character means. Since Pyth is written in prefix notation (i.e. * + 1 2 3 is (1 + 2) * 3) we can start from the left and fill in the arguments as we go.

W begins a traditional while loop. The first statement after it is the loop condition and the second statement after it is the loop body. If the second statement is empty it becomes a no-op. This while works exactly like the Python while, so it will evaluate non-zero integers as True and zero as false.

The first statement after the while begins with the newline character. This corresponds to Pyth's "print and return with a newline" function. This takes one argument, which is then printed and also returned unmodified. This allows us to print the intermediate steps while also performing the needed operations.

The argument passed to this print function begins with ~ which is a bit special. If the character immediately after ~ is a variable it takes two arguments, otherwise it takes one. Since O is not a variable ~ will consume only one argument. ~ functions a bit like += does in many conventional languages, though the closest operator would be the post-increment operator ++ from C. You may know that x++ will be like using x as the current value, but thereafter x will be x+1. ~ is the same idea, but generalised to whatever the result of the first argument is. How it picks what variable to assign to will be addressed later.

The argument of ~ is O which is very simple. When its one argument is an integer O returns a value from 0 to one less than that integer uniformly at random.

Now you may have noticed O does not have an argument. Here the Pyth interpreter kindly fills in a guess, which here is the variable Q. Q has a special meaning in Pyth: whenever it is present in a program the Pyth program begins with assigning Q to the input of the program. Since this is the first variable occurring in ~'s argument Q is also now the variable that ~ will assign a value to.

Summed up our "readable" program might look like:

while print_and_return( assign_variable( Q, unif(0, Q-1) ) ):
pass


And one sample "run-through" might look like:

1. Q = 5
2. O returns 3, ~ returns 5, \n returns and prints 5 which is true
3. Q = 3
4. O returns 0, ~ returns 3, \n returns and prints 3 which is true
5. Q=0
6. O returns something irrelevant, ~ returns 0, \n returns and prints 0 which is false
7. Q = something irrelevant
8. Terminate

# APL (Dyalog Unicode), 12 9 bytes

Anonymous tacit prefix function. Assumes ⎕IO (Index Origin) to be 0, which is default on many systems. Returns the final value (0) in addition to printing while run.

{⌊?⎕←⍵}⍣=


Try it online!

{}⍣= apply the following function until stable:

⎕←⍵ output the argument

? return a uniformly distributed random number in the range 0 through that–1

⌊ round down (because ?0 gives a (0,1) float)

# C (gcc), 40 42 bytes

Some idiot™ forgot to print the initial value first.

f(K){while(K)printf("%d\n",K,K=rand()%K);}


Don't panic.

• You tied me, the question also requires that you print the initial K. Without it I also got 40. You can also get the 42 fully compliant version in a similar way: f(K){while(K)printf("%d\n",K),K=rand()%K;}. Still you got my +1 for an equal solution! – LambdaBeta Jul 9 '18 at 17:26
• Even better: f(K){while(K)printf("%d\n",K,K=rand()%K);} – SIGSTACKFAULT Jul 9 '18 at 17:47

# x86 + rdrand, 19 bytes

Straightforward implementation. Takes input K in ecx and outputs to a buffer in ebx.

0000000a <start>:
a:   0f c7 f0                rdrand %eax
d:   31 d2                   xor    %edx,%edx
f:   f7 f1                   div    %ecx
11:   89 13                   mov    %edx,(%ebx)
8+1.\~:{:}\+>$1+f ~~@~~47*0.\(a2*1@@?!.  +2B for -v flag Try it online! ><>'s only source of randomness comes from the 'x' instruction, which sets the instruction pointer's direction to a random value. As such, generating a random number from 0 to n isn't trivial. I first calculate how many bits are required to represent a number in the range [0,n), then generate random bits to generate a random number. This leaves the possibility that it'll generate a number slightly larger than n, in which case we just discard it and try again. # Explanation: :nao Print the current number followed by a newline :0=?; If the current n is 0, terminate Calculate how many random bits we need to be generating: 0 1 Initialise the variables for this loop: numberOfBits = 0, maxValue = 1 :{:}(?\ If maxValue >= n, break out of the loop *2 maxValue *= 2$+1$numberOfBits += 1 Generate the random number: ~ Delete maxValue 00 Initialise randomNumber = 0, i = 0 }(?!\ :{{:@} If i >= numberOfBits, break out of the (inner) loop$2*                          randomNumber *= 2
_
1>x~\                     The random bit: If the IP goes up or
\+>                     left, it'll be redirected back onto the 'x',
if it goes down, it adds one to randomNumber
If it goes right, it does nothing to randomNumber

$1+ increment i 8+1. f Jump back to the start of the inner loop After we've generated our number, check that it's actually below n ~ Delete i :{:} ( ? Test that the number is less than n a2*1 . If it's not, jump back to the start of the number generation section @~~ Otherwise delete the old value of n, and numberOfBits 47*0. Then jump back to the start of the program  • Very nice! I came up with the same idea independently; without whitespace, my solution uses several characters fewer than yours, but you've managed to make a much more compact block of code. – Théophile Jul 17 '18 at 1:05 • The current meta consensus is that you don't have to count the bytes used on flags – Jo King Jul 17 '18 at 6:19 ## MATLAB (49 46 bytes) @(k)eval('while k;disp(k);k=randi(k)-1;end;0')  Sample output: >> @(k)eval('while k;disp(k);k=randi(k)-1;end;0') ans(5) ans = @(k)eval('while k;disp(k);k=randi(k)-1;end;0') 5 3 2 1 ans = 0  • I suppose you can do k=randi(k)-1 for a few bytes less. – Sanchises Jul 11 '18 at 13:16 # Retina, 21 bytes .+ * L$.
$. +¶<)G?  Try it online! Explanation: +  Repeat until the value stops changing (i.e. 0). ¶<)  Print the value before each pass through the loop. .+ *  Convert to unary. L$.
$.  Create the range and convert to decimal. G?  Pick a random element. # Pyth, 6 7 bytes QWQ=OQQ  Try it online! +1 to print the initial input value. While Q is truthy, set Q to be a random integer between 0 and Q and print Q. Not the shortest Pyth answer but I'm just learning and only posting because of the recent discussion about no-one using Pyth any more :) • I managed to tie using cumulative reduce but keeping it as a procedural program. Thanks for the motivation to work on a golf :) – FryAmTheEggman Jul 9 '18 at 15:16 • That's cool. Still trying to work out how (why) it works. – ElPedro Jul 9 '18 at 16:07 • By default, both = and ~ use the first variable of an expression as the variable that will be assigned if one isn't specified. For example ~hT will set T to 11 while returning 10. The only other fancy trick is that the newline character prints its input and then returns that value unmodified, so we can have an empty loop body. Let me know if something else is confusing :) – FryAmTheEggman Jul 9 '18 at 21:54 • @FryAmTheEggman That's beautiful. – isaacg Jul 11 '18 at 5:31 • @isaacg Thanks! I originally meant for it to just be edited in here, but I decided to write something up since I wanted to try MathJax. These kinds of Pyth answers were always my favourite since they feel both intentional but also abusive :) – FryAmTheEggman Jul 11 '18 at 20:26 # Haskell, 74 71 bytes -3 bytes by actually doing what the specs say it should do. import System.Random f 0=pure f x=randomRIO(0::Int,x-1)>>=fmap(x:).f  Try it online! # IBM/Lotus Notes Formula, 48 bytes o:=i;@While(i>0;i:=@Integer(i*@Random);o:=o:i);o  Field formula that takes input from another field i. There's no TIO for formula so here's a screenshot of a sample output: # Powershell, 36 32 bytes -4 bytes thanks AdmBorkBork filter f{$_;if($_){Random$_|f}}


Testscript:

filter f{$_;if($_){Random $_|f}} 100 |f  Output: 100 61 20 8 6 3 0  # PowerShell, 35 bytes for($a="$args";$a;$a=Random$a){$a}  Try it online! Full program. Takes input $args, stores it into $a, and enters a for loop. Each iteration we're checking whether $a is still positive (as 0 is falsey in PowerShell). Then we leave $a on the pipeline and move to the next iteration, where we set $a to be the result of Get-Random $a, which returns an integer in the range 0..($a-1).

(Ab)uses the fact that PowerShell outputs an additional trailing newline in lieu of outputting the final zero (allowed by the rules as currently written).

• "$args" - nice. I was stuck on $args in this case – mazzy Jul 9 '18 at 20:29

# Lua, 58 bytes

p,r=print,...+0 p(r)while r>0 do r=math.random(0,r)p(r)end


Try it online!

For some more Lua love here :)

• Hey, you can remove the +0 on the r declaration and move it to the r on the while statement, by doing so you'll use 1 less byte for the space (p,r=print,...p(r)while). – Visckmart Jul 29 '18 at 4:14