[Question]
  [
**Challenge**
*[Sandbox post](https://codegolf.meta.stackexchange.com/a/16598/78039)*
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
* Your program must finish.
* `0` must be the final output, Optionally an empty line instead `0`
  
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~6 5~~ 4 bytes
```
.uOW
```
[Try it here!](https://pyth.herokuapp.com/?code=.uOW&input=9&debug=0)
### 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.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 42 bytes
```
f(_){printf("%d\n",_);(_=rand()%_)&&f(_);}
```
[Try it online!](https://tio.run/##NY7PCsIwDMbvPkWYTFI3Zbta9QmGJz3pmKX7Y0A76TovsmevbdWQhI984ZfIVSelnZOS97FuYDuYmvr1bW9brNj7qUmZFqO4vqgorRjHaqeFqpHFFVss/A6frNuBhyCFXgjdyRTkTWhYOv06l@w9AxfeJB7kEBiGHg0eTkXB2Hfc9hqQdjkHgm0AcUgSYvAF@Pg/dGwGQ6rbwDUerv43CLeo/KECDoXpCf/Gz5lC140ZtYKMzyZr88xl7irLPw "C (gcc) – 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)](https://gcc.gnu.org/), 40 bytes (w/o printing initial value)
```
f(_){printf("%d\n",_=rand()%_);_&&f(_);}
```
[Try it online!](https://tio.run/##NY7PDoIwDMbvPkWjgWyiBq4OfQLiSU9qcNn400SHGdOL4dnnNqBpmy/9ml8rto0QdoVKPD@ygrw3Ertde7Q1KenvrVGZmiwjeVPLTXnQXElCo5KyMo79Bhus24AXR0W84LoRGxAt17B2@nu9098CXHgTWZB9oBh8VeR0KQpKx3HdaSB4yBgg5AHEIEmQwgjwMb9zrnqDqtnDI@of/jMIt/A@oQKOcNMhmY3JGULXlfloBSlbDNZmqcvMVZr9AQ "C (gcc) – 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
```
[Answer]
# [R](https://www.r-project.org/), ~~66 60 56 43~~ 41 bytes
```
function(n)while(print(n))n=sample(n,1)-1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPszwjMydVo6AoM68EyNPMsy1OzC0AiuTpGGrqGv5P0zA0MDDQ/A8A "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
`tYrqt
```
[Try it online!](https://tio.run/##y00syfn/P6Eksqiw5P9/QwMDAA "MATL – 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)
```
[Answer]
# [Pepe](https://github.com/Soaku/Pepe), 25 bytes
Pepe is a programming language made by user [Soaku](https://codegolf.stackexchange.com/users/72792/soaku).
```
REeErEErReEEreeEREEeEEree 
```
[Try it online!](https://soaku.github.io/Pepe/#RE@NI-b*)
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
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
```
{$_,(^*).pick...0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXkcjTktTryAzOVtPT8@g9r81l1qahqGBgaZecWKlQkWFgqHBfwA "Perl 6 – 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.
[Answer]
# [Perl 5](https://www.perl.org/).10.0 `-pl`, 26 bytes
```
say;say while$_=int rand$_
```
[Try it online!](https://tio.run/##K0gtyjH9/784sdIaiBXKMzJzUlXibTPzShSKEvNSVOL//zc14DI0MPiXX1CSmZ9X/F@3IOe/rq@pnqGBngEA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 3 bytes
```
XƬ0
```
This is a monadic link (function) that prints an array and returns **0**.
[Try it online!](https://tio.run/##y0rNyan8/z/i2BqD/4fbHzVus1ZQeLhj@6OGOQrOiTk5CiUZqQo5mXnZCol5KQoFRakFqUA6UaG4IDE5VaEkHyxflFpSWpSnUJaYU5qq9/@/iREA "Jelly – 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.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
ẉ?ℕ₁-₁ṙ↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuTvtHLVMfNTXqAvHDnTMftW34/9/QwOA/AA "Brachylog – 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`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
Δ=L<Ω0M
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3BRbH5tzKw18//83NDAwAAA "05AB1E – 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
```
[Answer]
# 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!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aqtbKXsHKKjbOKtHqvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagpEB138A "J – Try It Online")
[Answer]
# 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>
```
[Answer]
# C, 38 bytes
```
f(k){printf("%d ",k);k?f(rand()%k):0;}
```
[Try it online](https://tio.run/##Dco7CoAwDADQ3VMEQUhEQSd/iAcRh7SlWopVipt49tj18XS9ay0nu4AuPMCVPjhCWSp6nUWGGfi5HKq13YgS0PSJRU/vHdO3mBcG8srT5BeLkYNBKjyNTWqZyNB38gM)
**Ungolfed**
```
void f(int k){
    printf("%d ",k);
    if(k)
        f(rand()%k);
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
W
~O
```
[Try it online!](https://tio.run/##K6gsyfj/P5yrzv//fzMA "Pyth – 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](https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine#comment151542_62764). 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
[Answer]
# [Factor](https://factorcode.org/), 21 bytes
```
[ [ random ] follow ]
```
[Try it online!](https://tio.run/##Nc2xDoIwFEbhnaf43Y2BFY2rYWExToShKa00gXvr7UXD01c0@gDnO95YZcm3a9NeahgRsyZEcaprlEAKMTTwjOQeiyPrEo5F09ZIVozasahKVGWJ07c85w7dv@jheZr4hT7PJuKAHWShBB0d/EJWAxP46WQDYDmGzWb/0fYY3MyUdFsEuv9AcinlNw "Factor – Try It Online")
Basically, collects the values after each iteration (including zeroth iteration) stopping when the value is `f`, where each iteration converts the value `n` to a random integer between `0` and `n-1` inclusive. Calling `random` on zero yields `f`, conveniently terminating the loop.
Interestingly, [the doc page for `follow`](https://docs.factorcode.org/content/word-follow,sequences.html) has an example code that solves almost the same task, but it is actually longer since it tries to exclude zero at the end.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 9 bytes
Anonymous tacit prefix function. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Returns the final value (0) in addition to printing while run.
```
{⌊?⎕←⍵}⍣=
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9XTZA7lAzqPerbWPehfb/k8Dc/ogirqaD603ftQ2EcgLDnIGkiEensH/i1KLS3NKgOrSFEyMuFB4AA "APL (Dyalog Unicode) – 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)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~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.
[Answer]
# 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)
  13:   83 c3 04                add    $0x4,%ebx
  16:   89 d1                   mov    %edx,%ecx
  18:   85 c9                   test   %ecx,%ecx
  1a:   75 ee                   jne    a <start>
  1c:   c3                      ret  
```
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
f=lambda k:print(k)or f(hash('.'*k)%k)
```
Probably not the most cryptographically secure random number generator but to the human eye it looks random enough...
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIduqoCgzr0QjWzO/SCFNIyOxOENDXU9dK1tTNVuT6z9EMk3D3FRT8z8A "Python 3 – Try It Online")
[Answer]
# TI-Basic (TI-84 Plus CE), ~~17~~ 13 bytes
```
While Ans
Disp Ans
int(randAns
End
Ans
```
-4 bytes from [Misha Lavrov](https://codegolf.stackexchange.com/questions/168221/randomizing-until-0/168320#comment406660_168320)
Takes input in `Ans` as `50:prgmNAME`.
TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens). All tokens used here are one byte.
Explanation:
```
While Ans    # 3 bytes, While the number we hold is not zero:
Disp Ans     # 3 bytes,   Display it on its own line
int(randAns  # 4 bytes,   and replace it with a number randomly
                        # chosen from 0 to one less than it (inclusive)
End          # 2 bytes, end While loop
Ans          # 1 byte,  Display (and return) zero
```
---
An 11-byte solution suggested by Misha Lavrov that requires pressing `enter` after each line following the first.
```
Ans
While Ans
Pause int(randAns
End
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ ~~62~~ 60 bytes
```
from random import*
k=input()
while k:print k;k=randrange(k)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocWXbZuYVlJZoaHKVZ2TmpCpkWxUUZeaVKGRbZ9uClAJxeqpGtub//6YA "Python 2 – Try It Online")
---
Saved
* -2 bytes, thanks to Jonathan Allan
[Answer]
# C++ (gcc), 98 bytes
```
#import<cstdio>
#import<cstdlib>
#define d printf("%i ",x 
int p(int x){d);while(x>0)d=rand()%x);}
```
[Try it here!](http://rextester.com/KXTCS31402)
**Usage**
```
int main() {
    p(100);
}
```
This is my first code golf attempt. Any feedback or remarks are welcome.
Edit:
Removed the main function as suggested to make it valid.
[Answer]
# ><>, 92+2 Bytes
```
:nao:0=?;0_1>:{:}(?\\
}(?!\$2*1>x~\$+1$*2/\~00:{{:@}
8+1.\~:{:}\+>$1+f
~~@~~47*0.\(a2*1@@?!.
```
+2B for -v flag
[Try it online!](https://tio.run/##S8sszvj/3yovMd/KwNbe2iDe0M6q2qpWwz4mhgtIKsaoGGkZ2lXUxahoG6poGenH1BkYWFVXWznUclloG@rF1IFUx2jbqRhqp3HV1TnU1ZmYaxnoxWgkAvU5ONgr6v3//1@3TMHQwAAA "><> – 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
```
[Answer]
## 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
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 21 bytes
```
.+
*
L$`.
$.`
+¶<)G?`
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4vLRyVBj0tFL4FL@9A2G013@4T//y0B "Retina – 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.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 7 bytes
```
QWQ=OQQ
```
[Try it online!](https://tio.run/##K6gsyfj/PzA80NY/MPD/fzMA "Pyth – 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 :)
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ 71 bytes
-3 bytes by actually doing what the specs say it should do.
```
import System.Random
f 0=pure[0]
f x=randomRIO(0::Int,x-1)>>=fmap(x:).f
```
[Try it online!](https://tio.run/##HcixCsIwEIDh3ae4sQUN0TE0XZw6FeooDge9aLC5hOSE@PRRuv3f/8Lypm1rzYcUs8DtW4SCWpDXGA4OtE2fTHf9@He1ed/LNHfamInlWE/nfhytC5i6anrlWkDPYCFlzwJ2GMCBgky47niSXCMLsZR20T8 "Haskell – Try It Online")
[Answer]
# 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:
[![enter image description here](https://i.stack.imgur.com/TfJk4.png)](https://i.stack.imgur.com/TfJk4.png)
[Answer]
# Powershell, ~~36~~ 32 bytes
-4 bytes thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)
```
filter f{$_;if($_){Random $_|f}}
```
Testscript:
```
filter f{$_;if($_){Random $_|f}}
100 |f
```
Output:
```
100
61
20
8
6
3
0
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 35 bytes
```
for($a="$args";$a;$a=Random $a){$a}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl0VZJJbEovVjJWiURiGyDEvNS8nMVVBI1q1USa////29oYAAA "PowerShell – 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).
]