title: Helloellolloloo Worldorldrldldd

text:
# Question
Title: Helloellolloloo Worldorldrldldd
Make a program that takes the word you input, and adds that word to the back of itself minus its first letter, then repeats until all letters are gone. For example, `cat` would become `catatt`, and `hello` would become `helloellolloloo`.

**Input**
Any of the 26 letters of the English alphabet. There may be multiple words separated by spaces, and the change should be applied to every word.

**Output**
The word(s) inputted, with each word put after itself with its first letter missing, and then with its second letter missing, and so on until there are no more letters to add.

**More examples:**

`ill eel` outputs `illlll eelell`

`laser bat` outputs `laserasersererr batatt`

`darth vader` outputs `dartharthrththh vaderaderdererr`

This is code golf, so the shortest code wins.

Clarification:
You can treat the input or output as a list. You can separate words using newline instead of space. You can add a trailing space to the input.

# Answer
> 32 votes
# Japt `-m`, ~~6~~ 3 bytes

Input and output are arrays of words.

```
£sY

```

Try it

---

## Explanation

```
        :For each word in the input array
£       :Map each letter at index Y
 sY     :  Slice the current word from index Y

```

# Answer
> 38 votes
# brainfuck, ~~60~~ 56 bytes

```
,[>++++++++[-<----<++++>>]<[>>]<[[<]>.[[-]>[.>]<[<]>]],]

```

Try it online!

Requires a trailing space and prints a leading space. Both of these could be circumvented, but that ends up at 112 bytes.

### Explanation

```
,[  Loop over each byte of input
  Tape: 32 w o r-32 d'
  >++++++++[-<----<++++>>]   Subtract 32 from the character and add 32 to the previous char
  Tape: 32 w o r d-32 0'
  <[>>]<   If the last character was a space
  Tape: 32 w o r d-32 0'
  or
  Tape: 32 w o r d' space-32
  [
    [<]>.   Move to the end of the word and print out the space
    [   Loop over each letter
      [-]    Remove the first letter (initially space)
      >[.>]  Print the rest of the word
      <[<]>  Move back to the first letter
    ]
    Tape: clear
  ]
,]  Get the next byte of input

```

# Answer
> 20 votes
## Haskell, ~~36~~ 21 bytes

```
map$concat.scanr(:)""

```

Try it online!

Edit: -15 bytes, because of new IO format (list of words instead of space separated words)

# Answer
> 19 votes
## Perl `-p`, ~~36~~ ~~25~~ 23 bytes

```
s!\b|\S!$'=~s/ .*//r!eg

```

Try it online!

This is a single regsub. First, it matches all word boundaries or non-space characters:

```
[][H][e][l][l][o] [][W][o][r][l][d]

```

Note that each of these matches should be replaced with the rest of the word:

```
[→Hello][H→ello][e→llo][l→lo][l→o][o→] (...)

```

We can accomplish this with the special variable `$'`, which stores the part of the string after the match. However, we need to apply the nested regsub `s/ .*//` to it, which removes everything past the first space in `$'`, in order to get rid of the remaining words in the input.

Thanks to @nwellnhof for 2 bytes.

# Answer
> 19 votes
# Python 3, 49 bytes

```
d=lambda s:' '.join(n+d(n[1:])for n in s.split())

```

Try It Online!

This takes advantage of the fact that `"".split()` returns an empty array so that acts as the check for the base case in the recursion.

# Answer
> 17 votes
# Jelly, 3 bytes

```
ḊƬ€

```

Try it online!

Don’t need the `K`s anymore since array input/output is now allowed.

```
ḊƬ€
  €   For each word:
Ḋ       Remove the first letter
 Ƭ      until there are none left.

```

# Answer
> 14 votes
# JavaScript (ES6), 33 bytes

*Saved 1 byte thanks to @ShieruAsakoto*

I/O format: array of words.

```
a=>a.map(g=w=>w&&w+g(w.slice(1)))

```

Try it online!

---

# JavaScript (ES6), 35 bytes

I/O format: array of words.

```
a=>a.map(w=>w.replace(/./g,"$&$'"))

```

Try it online!

# Answer
> 14 votes
# APL(Dyalog), ~~19~~ 9 bytes

`{⌽∊,\⌽⍵}¨`

*thanks to @H.PWiz for jogging my brain*

This works because all strings in APL are character arrays.

```
{⌽∊,\⌽⍵}¨
        ¨ - for each string
      ⍵} - string argument - ex. "hello"
     ⌽ - reverse - "olleh"
   ,\ - scan magic - "o" "ol" "oll" "olle" "olleh"
  ∊ - enlist(join together) "oolollolleolleh"
{⌽ - reverse - "helloellolloloo"

```

TIO

# Answer
> 13 votes
# , ~~82~~ ~~75~~ 67 bytes

```
write(sapply(x<-scan(,""),substring,1:(y=max(nchar(x))),y),1,y,,"")

```

Try it online!

*Several bytes saved thanks to JayCe*

Separates output with newlines.

The `sapply(...)` expression generates a matrix/column vector of the appropriate substrings, padding with `""` as needed. `write` then prints the elements of the matrix, `y` per line, separating them with `""`.

# Answer
> 8 votes
# brainfuck, ~~94~~ 93 bytes

```
-[-[-<]>>+<]>-<<+[[[-]<,[->+>+<<]>[-<+>]>>[-<->>+<]<]<<[>>+<<[-]]<[<]>[[.>]<[<]>[-]>]>>>>.<<]

```

Try it online!

* Saved one byte thanks to Nitrodon -- golfing `.[-]>[.>]<[<]>` to `[.>]<[<]>[-]>`.

# Explanation

```
[[[ (dynamic) tape layout: ... NUL STR ... STR CHR FLG BUF SPC NUL ... ]]]

load a 32 into SPC
-[-[-<]>>+<]>-

while FLG
<<+[

 read a word
 [
  clear FLG; read CHR
  [-]<,
  copy CHR to BUF (using FLG as a temporary)
  [->+>+<<]>[-<+>]
  subtract SPC from BUF and save SPC
  >>[-<->>+<]
  move tape layout one to the right
  <
 ]

 strip trailing space; set FLG to true
 << [>>+<<[-]]
 to STR's first character
 <[<]>
 print word in all reduced forms
 [
  [.>]<[<]>[-]>
 ]

 print SPC; move to FLG
 >>>>.<<
]

```

Try it online!

# Attribution

Esolang's brainfuck constant collection was used for the initial space load.

# Answer
> 6 votes
# Husk, ~~6~~ 4 bytes

-2 bytes thanks to Jonathan Allan (taking input as a list)!

```
moΣṫ

```

Try it online!

### Explanation

Takes input as a list of strings and maps the following function:

```
Σṫ  -- example argument: "abc"
 ṫ  -- tails: ["abc","bc","c"]
Σ   -- concat: "abcbcc"

```

# Answer
> 6 votes
# 05AB1E, 5 bytes

```
€.síJ

```

Try it online!

**Explanation**

```
€.s        # push suffixes of each
   í       # reverse each
    J      # join suffixes

```

# Answer
> 5 votes
# Retina 0.8.2, 15 bytes

```

¶
.
$&$%'
¶

```

Try it online! Note: trailing spaces. Explanation:

Split on spaces.

```
.
$&$%'

```

Append its suffix to each letter. The `%` means that we only get the word's suffix.

Join with spaces.

# Answer
> 5 votes
# Vim, 47 bytes (38 key strokes)

Start with your input as the sole line in a Vim buffer.

```
:s/<Space>/\r/g<CR>ggqaywPlxqqb99@aj0q99@bgg99J

```

## Explanation

This puts each word on its own line, iterates over each line, then rejoins them all. Breaks if words are longer than 99 characters or if your input has more than 99 words.

1. `:s/<Space>/\r/g<CR>` replaces spaces with new lines (`\r`)
2. `gg` positions the cursor at the beginning of the first line
3. `qa` begins recording macro *a*:
    * `yw` yanks the rest of the word
    * `P` puts it behind the cursor
    * `lx` removes the first letter of the latter word
    * `q` stops recording macro *a*
4. `qb` begins recording macro *b*:
    * `99@a` executes macro *a* ninety-nine times (introduces the character limit)
    * `j0` positions the cursor at the start of the next line
    * `q` stops recording macro *b*
5. `99@b` executes macro *b* ninety-nine times (introduces the word limit)
6. `gg` positions the cursor at the first line
7. `99J` joins the following ninety-nine lines with spaces (word limit again)

For another 2 bytes (2 key strokes) you could extend the word limit to 999. Another 4 bytes, 9999, etc.

# Answer
> 5 votes
# Pepe, ~~167~~ 153 bytes

```
REEerEeeEeeeeeRrEEEEerEEEEEeerEErEEeerreErEEeErreEREEEEEEEreereErEerEEEErEEeerrEEreRRErEEEEreREEreeereReeRerEEEEEErEEEeerreEerEEeerEEEEerEEeEreereErEeree

```

Try it online!

# Answer
> 5 votes
# 16-bit x86 assembly code, 24 bytes

```
     47             inc    di
     B020           mov    al,20h
l1:  3806           cmp    [si],al
     7212           jb     l5 ;less means end of string
     7401           je     l2  ;equal means space was seen
     4F             dec    di ;overwrite extra space
l2:  E80300         call   l3
     46             inc    si ;move to next character in word
     75F1           jne    l1
l3:  56             push   si
l4:  3806           cmp    [si],al
     A4             movsb      ;copy character
     77FB           ja     l4  ;until either zero or space is seen
     5E             pop    si
l5:  C3             ret
```

Call with si = pointer to source string, di = pointer to output buffer.
The source string requires a zero byte to end it.
The code is the same in 16- or 32- or 64-bit (si/di become either esi/edi or rsi/rdi).
32-bit code is two bytes larger because of the expanded call.
64-bit code is three bytes larger still because the inc/dec of rsi/rdi attracts a prefix (but if it is known that they are within 32-bit memory space, then they can be esi/edi again to avoid that penalty).

# Answer
> 4 votes
# MATL, ~~18~~ 16 bytes

```
"@gXH"HX@Jh)]0&h

```

Input is a cell array of words. Try it online!

### Explanation

```
"         % Implicit input: cell array of strings. For each cell
  @g      %   Push content of current cell, that is, a word
  XH      %   Copy into clipboard H
  "       %   For each letter
    H     %     Push word
    X@    %     Push iteration index
    Jh)   %     Index from that until the end into current word
  ]       %   End
  0       %   Push 0. Will be cast to char. Char(0) is displayed as space
  &h      %   Concatenate horizontally all elements so far. Implicit display

```

# Answer
> 4 votes
# K4 / K (oK), 9 bytes

**Solution:**

```
,/'(1_)\'

```

Try it online!

**Explanation:**

```
,/'(1_)\' / the solution
        ' / apply to each
       \  / scan
   (  )   / do this together
    1_    / drop first
,/'       / flatten (,/) each (')

```

# Answer
> 4 votes
# C++ (clang), 174 bytes

```
#include<map>
#include<string.h>
std::string r(std::string w){while(auto x=strchr(w.c_str(),32))return r(w.substr(0,x-w.c_str()))+" "+r(x+1);return w!=""?w+r(w.substr(1)):w;}

```

Try it online!

It's my first submission, and i didn't know if returning string instead of printing it is okay :)

# Answer
> 4 votes
# Stax, 3 bytes

```
m|]

```

Run and debug it

Explanation:

```
m   Map over the lines
 |] Get all suffixes (suffices?)
    Implicit flatten and output

```

# Answer
> 4 votes
# Vyxal, 5 bytes

```
ƛ[Ḣx+

```

Try it Online!

(IMO) this is a really neat recursive solution. Port of my JS answer that came out really nicely.

```
ƛ     # Foreach value as n
 [    # If truthy (Not empty string)
   x  # Call this function (The function we're mapping with)
  Ḣ   # With n[1:] - remove first character
    + # Appended to the result

```

The "concatenation of suffixes" approach doesn't do any better:

# Vyxal, 5 bytes

```
ƛṘ¦∑Ṙ

```

Try it Online!

```
ƛ     # Map...
 Ṙ    # Reverse
  ¦   # Cumulative sums (prefixes)
   ∑  # Concatenated
    Ṙ # Reversed

```

# Answer
> 3 votes
# Charcoal, 14 bytes

```
⪫Ｅ⪪Ｓ ⭆ι✂ιμＬι¹

```

Try it online! Note: Trailing space. Link is to verbose version of code. Explanation:

```
   Ｓ            Input string
  ⪪             Split on spaces
 Ｅ              Map over each word
      ι         Current word
     ⭆          Map over each character and join
        ι       Current word
         μ      Current index
           ι    Current word
          Ｌ     Length
            ¹   Literal 1
       ✂        Slice
⪫               Join with spaces
                Implicitly print

```

# Answer
> 3 votes
# Pip `-s`, 11 bytes

```
J_@>,#_Mq^s

```

Takes the space-separated list of words from stdin. Try it online!

### Explanation

```
             s is space (implicit)
        q    Read a line of stdin
         ^s  Split it on spaces
       M     Map this lambda function to each word:
 _            The word...
  @>          sliced starting at index...
    ,#_       range(len(word))
              This creates len(word) slices ["word" "ord" "rd" "d"]
J             Join those into a single string
             The resulting list of modified words is printed; the -s flag uses space
             as the separator

```

# Answer
> 3 votes
# Python 2, 63 bytes

```
lambda s:' '.join(map(g,s.split()))
g=lambda s:s and s+g(s[1:])

```

Try it online!

# Answer
> 3 votes
# Canvas, 6 bytes

```
±［±］⇵］

```

Try it here!

5 bytes with a crazy output format

# Answer
> 3 votes
# C#, 111 90 bytes

```
b=>string.Join(" ",(b.Split(' ').Select(x=>string.Concat(x.Select((y, i)=>x.Substring(i))))))

```

Try it Online!

By Changing input and output to arrays, I saved a few bytes:

```
b=>b.Select(x=>string.Concat(x.Select((y,i)=>x.Substring(i)))).ToArray()

```

Try it Online!

# Answer
> 3 votes
# K (oK), ~~17~~ 13 bytes

```
{,/|:'|,\|x}'

```

Try it online!

Prefix anonymous function; Input is taken as a list of strings, which in turn are lists of characters.

Thanks @streetster for 4 bytes.

### How:

```
{,/|:'|,\|x}' //Main function, argument x → ("ill";"eel")
            ' // For each element of the argument
         |x}  // Flip it. x → ("lli";"lee")
       ,\     // Concatenate each element, keeping intermediates. x → (("l";"ll";"lli");("l";"le";"lee")
      |       // Flip it again. x → (("lli";"ll";"l");("lee";"le";"l"))
   |:'        // Now flip each element. x → (("ill";"ll";"l");("eel";"el";"l"))
{,/           // Concatenation scan. x → ("illlll";"eelell")

```

# Answer
> 3 votes
# Common Lisp, 179 bytes

```
(defun r(s)(cond((endp s)nil)((eql(first s)#\Space)(princ " ")(r(rest s)))(t(q s)(r(rest s)))))(defun q (l)(cond((eql(first l)#\Space)t)((endp l)t)(t(princ(first l))(q(rest l)))))

```

Try it online!

This is my first try at golfing any edits are welcome

# Answer
> 3 votes
# Lua, 70 bytes

```
for i=1,#arg do x=arg[i]for i=1,#x do io.write(x:sub(i))end print()end

```

Try it online!

### Explanation

The arguments in Lua are stored in the table `arg` starting at index 1. The unary operator `#` returns the size of the table and function `s:sub(a,b)` returns a substring based on string `s` delimited by integers `a` and `b`, if b is not passed it will return the rest of the string.

I had to use `io.write()` instead of `print()` to avoid line breaking, and added `print()` at the end for the opposite reason.

# Answer
> 2 votes
# Python 3, ~~79~~ 74 bytes

*-5 bytes thanks to mypetlion*

```
print(*map(lambda x:''.join(x[n:]for n in range(len(x))),input().split()))

```

Try it online!

A full program that takes input from stdin and outputs to stdout.

# Answer
> 2 votes
# Perl 6, ~~44~~ 32 bytes

*-12 bytes thanks to nwellnhof!*

```
~*.words>>.&{[~] $_,{S/.//}...0}

```

Try it online!

An anonymous Whatever lambda that takes a string and returns a string.

### Explanation:

```
 *.words   # Split the given word by spaces
        >>.&{                  }  # Map each word to
                           ...  # A list composed of
                 $_              # The initial string
                   ,{S/.//}      # Remove the first character
                              0  # Until it's empty
             [~]   # All joined together
~   # Convert the list to a string, which joins by spaces

```

# Answer
> 2 votes
# C (gcc), 79 bytes

```
f(s,t)char*s,*t;{for(;*s;printf("%.*s",*s^32?t?t-s:~0:1,s),s++)t=strchr(s,32);}

```

Try it online!

# Answer
> 2 votes
# Ruby, 42 bytes

```
->s{s.map{|a|(w=a.b).chars{a[0]='';w<<a}}}

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 33 bytes

```
s=>s.replace(/\B(?=(\S+))/g,"$1")

```

Try it online!

I don't really know JavaScript, but I just copied Arnauld's syntax with an idea I had for the regex substitution :P

# Answer
> 2 votes
# MathGolf, 6 bytes

```
ÆÅ_╞↑

```

Try it online!

Outputs a trailing space, though you can add another byte to remove this.

~~Hopefully 6 bytes when implicit input is implemented.~~ Yay.

### Explanation:

```
        Implicit input
Æ       Implicit for loop over the next 5 instructions
 Å  ↑   While true without popping (empty string is false)
  _╞    Duplicate the top of stack and remove the first letter
        (space) Append a space to the stack
        Implicitly output the stack joined together

```

# Answer
> 2 votes
# Java (JDK 10), 90 bytes

```
s->{var r="";for(var x:s){for(int i=0;i<x.length();)r+=x.substring(i++);r+=" ";}return r;}

```

Try it online!

## Credits

* -11 bytes thanks to Kevin Cruijssen, notifying me of the rule change about the input.

# Answer
> 2 votes
# Powershell, ~~29~~ 23 bytes

Port of Javascript by @Arnauld

```
$args-replace'.',"$&$'"

```

Input and output are a list of word. Test script:

```
$f = {

$args-replace'.',"$&$'"

}

@(
    ,('illlll eelell', 'ill','eel')
    ,('laserasersererr batatt', 'laser','bat')
    ,('dartharthrththh vaderaderdererr', 'darth','vader')
) | % {
    $e,$s = $_
    $r = &$f @s
    $r = "$r"
    "$($r-eq$e): $r"
}

```

Output:

```
True: illlll eelell
True: laserasersererr batatt
True: dartharthrththh vaderaderdererr

```

# Answer
> 2 votes
# Scala, 97 bytes

Scala main that takes a single String argument containing all the words.

```
args(0).split(" ").foreach(x=>{for(i<-0 to x.length)print(x.substring(i,x.length));print(" ")})
```

Try it online!

# Answer
> 2 votes
# Python3, 86 bytes

Reduced a lot, thanks to @ElPedro and @manatwork

```
def f(a):return a+f(a[1:])if''<a else''
for x in input().split():print(f(x),end=' ')

```

P.S. I tried removing split but then nothing is printing, its probably required in python3

# Answer
> 2 votes
# Python3, 58 bytes

Takes a space-separated string of words from `stdin` and returns `stdout` likewise.

```
f=lambda x:x and x+f(x[1:])
print(*map(f,input().split()))

```

It works by splitting the string into a list of words and using `map()` to call the recursive function `f` on each element. Honestly, I don't know exactly how `f` works. When the stack reaches the end of the word, `x` becomes the empty string (`''`), so the `and` statement returns `False`, which I suspect acts as the base case to end recursion.

Here's the same idea but without the functional aspects:

```
def f(x):
    return x and x + f(x[1:])

print(*( f(word) for word in input().split() ))

```

# Answer
> 2 votes
# 78 38 bytes

```
" "sv{r::x;{x,r::1_r}/[count x;x]}each

```

# Answer
> 2 votes
# Attache, 28 bytes

```
Join&sp##Sum@Suffixes=>Split

```

Try it online!

## Alternatives

```
ReplaceF&(Sum@Suffixes)&/"\\w+"               ?? 31 bytes
ReplaceF«_,/"\\w+",Sum@Suffixes»              ?? 34 bytes, 32 chars
ReplaceF<~_,/"\\w+",Sum@Suffixes~>            ?? 34 bytes

```

## Explanation

```
Join&sp##Sum@Suffixes=>Split    input, e.g.: "abc defg"
                       Split    split the input on spaces
                                e.g.: ["abc", "defg"]
                     =>         on each word:
                                  e.g.: "abc"
             Suffixes             take the suffixes of that word
                                  e.g.: ["abc", "bc", "c"]
         Sum@                     join them together
                                  e.g.: "abcbcc"
       ##                       then
Join&                           join the result by:
     sp                           spaces

```

# Answer
> 2 votes
# Scala, 81 bytes

```
def e(s:List[String])=s.map(_.foldRight(("","")){(a,b)=>(a+b._1,a+b._1+b._2)}._2)

```

Try it online!

As per comments, this can receive and output a `List[String]`. This builds the output from right to left, starting with the rightmost letter, then prepending the two rightmost letters, and so on down the line.

# Answer
> 2 votes
# Pyth, ~~8~~ 6 bytes

```
m_s.__

```

Decreased byte(s?) thanks to @Steven H.

Try it online! Input and output are a list.

Expalanation:

```
        - implicit output
m       - map function d:
      _ -   ...d reversed...
    ._  -   ...get all prefixes of it...
  _s    -   ...joined and reversed
        - ...over implicit Q (input)

```

# Answer
> 2 votes
# Pascal (FPC), 129 bytes

```
var s:string;i,j:int32;begin read(s);repeat j:=Pos(' ',s);for i:=1to j do write(s[i..j-1]);write(' ');Delete(s,1,j)until s=''end.

```

Try it online!

Requires that the input ends in space, allowed in this comment.

# Answer
> 2 votes
# Twig, 73 bytes

Creates a macro with the function `f()` that receives an array of words, displaying the words separated by new lines.

```
{%macro f(a)%}{%for v in a%}{%for i in 0..v|length%}{{v[i:]}}{%endfor%}
{%endfor%}{%endmacro%}

```

To use it, just import:

```
{% import 'macro.twig' as a %}

{{ a.f(['a','sentence','is','a','list','of','words']) }}

{# to pass a string, you can split it #}
{{ a.f('a sentence is a list of words'|split(' ')) }}

```

You can try it on https://twigfiddle.com/8xech1
**Warning**: due to the way that output is handled in the link, I was forced to add a simple period (`.`) at the end of the line. This is ***NOT*** needed for normal operation.

# Answer
> 2 votes
# Brachylog, 7 bytes

```
{a₁ᶠc}ᵐ

```

Try it online!

### Explanation

```
{    }ᵐ          Map for each word:
 a₁ᶠ               Find all suffixes
    c              Concatenate into a single string

```

# Answer
> 2 votes
# Haskell, 24 bytes

This solution is not optimal in two ways: *1)* the other Haskell answer by nimi is *3* bytes shorter and *2)* the input is limited to 9223372036854775807 characters (*~36* exabytes), though I think it's an interesting find:

```
map.mconcat$drop<$>[0..]

```

Try it online! (sets a limit of *255* characters for TIO would time out otherwise)

### Explanation

Since `drop` has type `Int -> [a] -> [a]` it forces `[0..]` to be `[0..9223372036854775807]` which is finite and thus the program terminates (eventually).

And `mconcat` takes the list of `[drop 0, drop 1..]` and gives us a function `String -> String` which is equivalent to:

```
\str-> drop 0 str ++ drop 1 str ++ .. ++ drop 9223372036854775807 str

```

**Note:** Once the argument of `drop` is greater or equal to the length of `str` it just appends empty strings.

## Practical solution, 40 bytes

This won't take as long as the shorter solution but at a great cost of *16* bytes:

```
map$mconcat=<<map drop.zipWith pure[0..]

```

Try it online!

# Answer
> 2 votes
# C#, ~~193~~ 166 bytes

```
class a{static void Main(string[]b){foreach(var c in b)d(c,0);}static void d(string c,int e){if(e==c.Length)Console.Write(" ");else{Console.Write(c[e++..]);d(c,e);}}}

```

Try it Online!

Since .NET automatically splits the arguments at spaces, it's possible to loop over them without splitting them manually.
Other than that, this uses recursion to subtract one character at a time using the overload of `string.Substring` that takes only 1 argument which is the index to start at.

# Answer
> 2 votes
# Burlesque, 8 bytes

```
{iS\[}ww

```

Try it online!

```
{
 iS # All suffixes
 \[ # Concatenate
}ww # For each word

```

# Answer
> 2 votes
# APOL, 23 bytes

`ƒ(s(i) j(ƒ(∋ V(⋒ ∈)))))`

## Explanation

```
ƒ(         List-builder for loop
  s(       String-split instruction (splits at spaces by default)
    i      Input
  )
  j(       String join instruction
    ƒ(     List-builder for loop
      ∋    For item (the current word being processed)
      V(   Substring instruction
        ⋒  For iterator (the thing the current for loop is iterating through, in this case the current word)
        ∈  For counter
      )
    )
  )
)

```

# Answer
> 2 votes
# Mathematica (Wolfram Language): 71 Characters

```
(a=Characters@#;StringJoin@Array[a[[#;;]] &,Length@a])&/@StringSplit[#]&

```

TIO Link

There pretty much has to be a better solution than this, but it works.

Explanation:

Takes a string and splits on spaces/newlines/punctuation, then iterates over this list. Finds a list of characters of each "word", then uses the Array to take all the elements, then all but the first, and so on. Then, these are joined (taking advantage of the fact that StringJoin ignores nested lists) and the function moves to the next word.

# Answer
> 1 votes
# C (gcc), 94 bytes

```
f(char*s){char*e=s+strlen(s),*i=s;for(;i<e;*i++=*i-32?*i:0);for(i=s;i<e;i++)printf(*i?i:" ");}

```

Try it online!

Saves a pointer to the end of the string in `char *e`, then replaces spaces with null characters, then prints the string starting with each character and ending at the next null character, but printing a space if the current character is a null character.

# Answer
> 1 votes
# JavaScript (Node.js), 88 bytes

```
f=s=>s.split(' ').map(e=>[...e].map((_,i,a)=>a.slice(i,a.length).join``).join``).join` `

```

Try it online!

# Answer
> 1 votes
# C (gcc), 64 bytes

```
f(s,t)char*s,*t;{for(;*s;t+=*s<33)for(strcpy(t,s++);*t&31;t++);}

```

Take two char\* parameters: The first one for input, and the second one for output. The caller is responsible for malloc and free. Like most string functions in C, this one is designed to be vulnerable by overflow the buffer.

Try it online!

# Answer
> 1 votes
# Gema, 24 characters

```
<L>=@x{$0}
x:?*=?*@x{$2}

```

Sample run:

```
bash-4.4$ gema '<L>=@x{$0};x:?*=?*@x{$2}' <<< 'darth vader'
dartharthrththh vaderaderdererr

```

# Answer
> 1 votes
# Red, 67 66 bytes

```
func[s][foreach w split s" "[until[prin w take w tail? w]prin" "]]

```

Try it online!

# Answer
> 1 votes
# Kotlin, 87 bytes

```
fun f(s:String):String=if(s=="")s else s.split(" ").joinToString(" "){it+f(it.drop(1))}

```

# Answer
> 1 votes
# Python 2, 55 bytes

```
for x in input():
 y=""
 while x:y+=x;x=x[1:]
 print y,

```

Try it online!

Takes input as a list. output is separated by spaces.

# Answer
> 1 votes
# Java, 131 bytes

```
char[]e(char[]a){int b=0,l=a.length,c,d=0;char[]n=new char[l*(l+1)/2];for(;b<l;b++){for(c=l-b;c>0;c--){n[d]=a[l-c];d++;}}return n;}

```

I know there is a better Java answer but, wanted to do it just with char arrays

```
char[] e(char[]a){
    int b=0,l=a.length,c,d=0;      //l to keep length, b for each iteration, c for each letter in iteration
    char[] n= new char[l*(l+1)/2]; //Create new array with length based in triangular number sequence
    for(;b<l;b++) {
        for(c=l-b;c>0;c--) {
            n[d]=a[l-c];          //Fill it
            d++;                   //d keeps position in new array
        }
    }
    return n;
}

```

# Answer
> 1 votes
# Julia 0.7, ~~75~~ 65 bytes

```
p(a)=for i in a for j=1:endof(i) print(i[j:end])end;print(" ")end

```

Try it online!

First codegolf. Yay v0.7 becase it it just deprecates the `endof` method and 1.0 replaces it with `lastindex`.

Update: As mentioned in the comments I am not sure if an array of words as input is permitted. So I included the bytes to take a string as input

Update2: Apparently an array of strings is ok so here we go down to 65 bytes. Thx to @JonathanFrech for removing some more whitespace

# Answer
> 1 votes
# Kotlin, 48 bytes

Lambda takes a `List<String>` as input and returns a `List<String>` as output, which is allowed. The extra code in the footer is just so the input can be tested easily.

```
{it.map{it.indices.fold(""){a,v->a+it.drop(v)}}}

```

Try it online!

# Answer
> 1 votes
# GolfScript, 23 bytes

```
" "/{{""=!}{(;}/}/]" "*

```

Try it online!

# Answer
> 1 votes
# Multi User Forth(121 bytes), Protomuck variant.

```
" " explode_array { swap foreach nip { swap  begin dup 1 strcut nip dup not until }cat repeat }list " " array_join .tell

```

I guess if you want to require that I use entirely standard stuff, then `.tell` it becomes `me @ swap notify` which brings it up to 132 bytes. If you want to go the other direction, then I guess that swap could become `.s` and nip `.n`, dup `.d` etc, would turn it into

```
" " explode_array { .s foreach .n { .s  begin .d 1 strcut .n .d not until }cat repeat }list " " array_join .tell

```

Which has 113 bytes.

Luckily we can continue further, begin turns into `.b`, until `.u` and explode\_array `.e`, if we use our thinking caps we can turn foreach into `.f` by defining that into `foreach nip` (who needs the index of the array anyway?) and we end at 94 bytes.

```
" " .e { .s .f { .s  begin .d 1 strcut .n .d not until }cat repeat }list " " array_join .tell

```

But, this is getting silly, and probably only hurting any chance of this being seen as a meaningful first post on codegolf.

# Answer
> 1 votes
# C (clang), `-DT=t=strtok` `-DZ=" ")` ~~178~~ ~~113~~ ~~106~~ ~~105~~ ~~95~~ 91 bytes

```
i;f(*a){char*t;for(T(a,Z;t;printf(Z,T(0,Z)for(i=0;t[i];)printf(t+i++);}

```

Try it online!

# Answer
> 1 votes
# Scala, 81 bytes

```
def x(l:String):String=if(l=="")" "else l+x(l.tail)
println(args.map(x).mkString)

```

Try it online!

# Answer
> 1 votes
# Elixir, 122 bytes

```
a = ["Hello","World"]
f = fn n,f -> if(n != "") do "#{n}#{f.(String.slice(n, 1..-1), f)}" end end
Enum.map(a, &(f.(&1,f)))

# OUTPUT
["Helloellolloloo", "Worldorldrldldd"]

```

Try it online!

# Answer
> 1 votes
Kotlin Android**, 204 bytes**

```
fun f(s:String){ val a=s.split(" ".toRegex()).dropLastWhile{it.isEmpty()}.toTypedArray();for(i in a.indices){var t=0;while(t<a[i].length){for(j in t until a[i].length){print(a[i][j]+"")};t++};print(" ")}

```

}

Try online

This Program is written in Kotlin Android.

# Answer
> 1 votes
# sed, ~~42~~ 37+2 bytes

```
s:\b:_:g
:A
s:_(.(\w*_))|__:\1\2:g
tA

```

Try it online!

Repeatedly match parts of words between underscores:

```
_hello_ _world_
hello_ello_ world_orld_
helloello_llo_ worldorld_rld_
helloellollo_lo_ worldorldrld_ld_
helloellollolo_o_ worldorldrldld_d_
helloellolloloo__ worldorldrldldd__
helloellolloloo worldorldrldldd

```

# Answer
> 1 votes
# Javascript(ES6), 34 bytes

```
s=>s.map(k=x=>x?x+k(x.slice(1)):x)

```

Try it online!

Takes input as array of words, returns array of words.

Aaah, the power of recursion...

# Answer
> 1 votes
# JavaScript (V8), ~~46~~ 42 bytes

*-4 thanks to Redwolf*

```
w=>w.split` `.map(f=a=>a&&a+f(a.slice(1)))

```

Try it online!

# Answer
> 1 votes
# BQN, 4 bytes

```
∾∘↓¨

```

Anonymous tacit function that takes and returns a list of strings. Run it online!

### Explanation

```
∾∘↓¨
   ¨  For each element of the list:
  ↓     Get a list of its suffixes
 ∘      and
∾       join them into one string

```

# Answer
> 1 votes
# Thunno 2 , 3 bytes

```
€ṣṃ

```

Attempt This Online!

Input as a list of words. Output as a single string.

#### Explanation

```
€ṣṃ  # Implicit input
€ṣ   # Suffixes of each string in the list
  ṃ  # Reverse each inner list
     # Implicit output, joined

```

# Answer
> 0 votes
# Factor \+ `grouping.extras`, 46 bytes

```
[ " "split [ tail-clump concat ] map " "join ]

```

Try it online!

# Answer
> 0 votes
# sed, 52 bytes

```
s/[a-z]+/@&/g
:l
s/@([a-z]([a-z]+))/\1@\2/
tl
s/@//g

```

Try it online!

---
Tags: code-golf, string
---


title: In how many bits do I fit

text:
# Question
Title: In how many bits do I fit
For any positive 32-bit integer (`1 ≤ n ≤ 0xFFFFFFFF`) output the number of bits needed to represent that integer.

# Test cases

```
| n    | n in binary | bits needed |
|----------------------------------|
| 1    | 1           | 1           |
| 2    | 10          | 2           |
| 3    | 11          | 2           |
| 4    | 100         | 3           |
| 7    | 111         | 3           |
| 8    | 1000        | 4           |
| 15   | 1111        | 4           |
| 16   | 10000       | 5           |
| 128  | 10000000    | 8           |
| 341  | 101010101   | 9           |

4294967295 => 11111111111111111111111111111111 => 32

```

So `f(16)` would print or return `5`

This is . Shortest code in bytes wins

# Answer
> 30 votes
# 05AB1E, 2 bytes

```
bg

```

Try it online!

# Answer
> 35 votes
# JavaScript (ES6), 18 bytes

```
f=n=>n&&1+f(n>>>1)
```

```
<input type=number min=0 step=1 value=8 oninput="O.value=f(this.value)">
<input id=O value=4 disabled>
```

# Answer
> 28 votes
# x86 Assembly, 4 bytes

Assuming Constant in `EBX`:

```
bsr eax,ebx
inc eax

```

EAX contains the number of bits necessary for Constant.

Bytes: `☼¢├@`

Hexadecimal: `['0xf', '0xbd', '0xc3', '0x40']`

# Answer
> 18 votes
# Python, 14 bytes

```
int.bit_length

```

Try it online!

# Answer
> 15 votes
## Mathematica, 9 bytes

```
BitLength

```

Alternatively:

```
Floor@Log2@#+1&
#~IntegerLength~2&

```

# Answer
> 15 votes
## Labyrinth, ~~13~~ 12 bytes

```
 ?
_:
2/#(!@

```

Try it online!

### Explanation

The program simply repeatedly divides the input by 2 until it's zero. The number of steps are kept track of by duplicating the value at each step. Once it's reduced to zero we print the stack depth (minus 1).

The program starts at the `?` which reads the input. The main loop is then the 2x2 block below, going counter-clockwise:

```
:   Duplicate current value.
_2  Push 2.
/   Divide.

```

Once the value is zero after a full iteration, the linear bit at the end is executed:

```
#   Push stack depth.
(   Decrement.
!   Print.
@   Terminate.

```

# Answer
> 15 votes
# C, 31 bytes

```
f(long n){return n?1+f(n/2):0;}

```

... Then I thought about recursion. From obscure to obvious, and with one fourth of the length dropped off.

See it live on Coliru

---

# ~~C, 43 bytes~~

```
c;
#define f(v)({for(c=0;v>=1l<<c;++c);c;})

```

Calling `f` with an **unsigned** value (e.g. `f(42u)`) will "return" its bit length. Even works for `0u` !

**Ungolfed and explained:** (backslashes omitted)

```
c;
#define f(v)
    ({ // GCC statement-expression

        // Increment c until (1 << c) >= v, i.e
        // that's enough bits to contain v.
        // Note the `l` to force long
        // arithmetic that won't overflow.
        for(c = 0; v >= 1l << c; ++c)
            ; // Empty for body

        c; // Return value
    })

```

See it live on Coliru

# Answer
> 14 votes
# Perl 6, 7 bytes

```
*.msb+1

```

Try it

## Explanation:

`*` makes it become a WhateverCode lambda, and indicates where to put the input

`.msb` on an Int returns the index of the most significant bit (0 based)

`+1` is combined into the lambda, and adds one to the eventual result of calling `.msb`.

# Answer
> 13 votes
# C preprocessor macro (with gcc extensions), 26

```
#define f 32-__builtin_clz

```

Uses GCC's count-leading-zeros builtin.

Call this as a function, e.g. `f(100)`.

Try it online.

# Answer
> 12 votes
# Retina, 56 37 bytes

**This solution works with all the required input values.**

The biggest problem Retina faces in this challenge is the fact that its strings have a maximum length of 2^30 characters, so the usual way of dealing with numbers (unary representation) doesn't work with values greater than 2^30.

In order to solve this problem I adopted a different approach, keeping a sort of decimal representation of numbers, but where each digit is written in unary (I'll call this representation *digitunary*). For example the number `341` would be written as `111#1111#1#` in digitunary. With this representation we can now work with numbers of up to `2^30/10` digits (~ a hundred million digits). It is less practical than standard unary for arbitrary arithmetic, but with a bit of effort we could do any kind of operations.

> NOTE: digitunary in theory could use any other base (e.g. binary `110` would be `1#1##` in base 2 digitunary), but since Retina has builtins to convert between decimal and unary and no direct way to deal with other bases, decimal is probably the most manageable base.

The algorithm I used is making successive integer divisions by two until we reach zero, the number of divisions we made is the number of bits needed to represent this number.

So, how do we divide by two in digitunary? Here's the Retina snippet that does it:

```
(1*)(1?)\1#        We divide one digit, the first group captures the result, the second group captures the remainder
$1#$2$2$2$2$2      The result is put in place of the old number, the remainder passes to the next digit (so it is multiplied by 10) and is divided by two there -> 5 times the remainder goes to the next digit

```

This replacement is enough to divide a digitunary number by 2, we just need to remove possible .5s from the end if the original number was odd.

So, here's the full code, we keep dividing by two until there are still digits in the number, and put a literal `n` in front of the string at each iteration: the number of `n` at the end is the result.

```
.                  |
$*1#               Convert to digitunary
{`^(.*1)           Loop:|
n$1                    add an 'n'
(1*)(1?)\1#            |
$1#$2$2$2$2$2          divide by 2
)`#1*$                 |
#                      erase leftovers
n                  Return the number of 'n's in the string

```

Try it online!

---

**Updated solution, 37 bytes**

Big refactoring with many good ideas that golfed about a third of the length, all thanks to Martin Ender!

The main idea is to use `_` as our unary symbol: in this way we can use regular digits in our string, as long as we convert them back to `_`s when it is needed: this lets us save many bytes on division and on insertion of multiple digits.

Here's the code:

```
<empty line>    |
#               put a # before each digit and at the end of the string
{`\d            Loop:|
$*_                 Replace each digit with the corrisponding number of _
1`_                 |
n_                  Add an 'n' before the first _
__                  |
1                   Division by 2 (two _s become a 1)
_#                  |
#5                  Wherever there is a remainder, add 5 to the next digit
}`5$                |
                    Remove the final 5 you get when you divide odd numbers
n               Return the number of 'n's in the string

```

Try it online!

# Answer
> 11 votes
# Ruby, ~~19~~ 16 bytes

```
->n{"%b"%n=~/$/}

```

Thanks Jordan for golfing off 3 bytes

# Answer
> 10 votes
# JavaScript ES6, 19 bytes

```
a=>32-Math.clz32(a)

```

`Math.clz32` returns the number of leading zero bits in the 32-bit binary representation of a number. So to get the amount of bits needed, all we need to do is substract that number from 32

```
f=
  a=>32-Math.clz32(a)

```

```
pre {
    display: inline;
}
```

```
<input id=x type="number" oninput="y.innerHTML = f(x.value)" value=128><br>
<pre>Bits needed: <pre id=y>8</pre></pre>
```

# Answer
> 10 votes
# Jolf, 2 bytes

```
lB

```

Just convert to binary and then find the length.

# Answer
> 10 votes
# Julia 0.4, 14 bytes

```
!n=log2(2n)÷1

```

Try it online!

# Answer
> 10 votes
# bash / Unix tools, 16 bytes

```
dc<<<2o$1n|wc -c

```

Save this in a script, and pass the input as an argument. The number of bits required to represent that number in binary will be printed.

Here's an explanation:

dc is a stack-based calculator. Its input, parsed into tokens, is:

2 — Push 2 on the stack.

o — Pop a value off the stack (which is 2) and make it the output base (so output is now in binary).

The value of the argument to the bash program ($1) — Push that argument on the stack.

n — Pop a value off the stack (which is the input number) and print it (in binary, because that's the output base) with no trailing newline.

So the dc command prints the number in binary.

The output of dc is piped to the command wc with the -c option, which prints the number of characters in its input.

The end result is to print the number of digits in the binary representation of the argument.

# Answer
> 9 votes
# Google Sheets, 15 Bytes

Takes input from cell `A1` and outputs to the cell that holds the formula

```
=Len(Dec2Bin(A1

```

or

```
=Int(1+Log(A1,2

```

or

```
=Int(Log(2*A1,2

```

# Excel, 17 Bytes

Same as above but formatted for MS Excel

```
=Len(Dec2Bin(A1))

```

or

```
=Int(1+Log(A1,2))

```

or

```
=Int(Log(2*A1,2))

```

# Answer
> 8 votes
# Pyth, 3 bytes

```
l.B

```

Test suite available here.

### Explanation

```
l.BQ    Q is implicitly appended
   Q    eval(input)
 .B     convert Q to binary string
l       len(.B(Q))

```

# Answer
> 8 votes
# Jelly, 2 bytes

```
BL

```

Converts to binary, finds length.

# Answer
> 8 votes
# C#, ~~63~~ ~~45~~ 31 bytes

Saved 18 bytes, thanks to Loovjo, and TuukkaX

Saved 14 bytes, thanks to Grax

```
 b=>1+(int)System.Math.Log(b,2);

```

It uses, that a decimal number n has ⌊log2(n)⌋+1 bits, which is described on this page:

> ## Number of Bits in a Specific Decimal Integer
>
> A positive integer n has b bits when 2^(b-1) ≤ n ≤ 2^b – 1. For example:
>
> * 29 has 5 bits because 16 ≤ 29 ≤ 31, or 2^4 ≤ 29 ≤ 2^5 – 1
> * 123 has 7 bits because 64 ≤ 123 ≤ 127, or 2^6 ≤ 123 ≤ 2^7 – 1
> * 967 has 10 bits because 512 ≤ 967 ≤ 1023, or 2^9 ≤ 967 ≤ 2^10 – 1
>
> For larger numbers, you could consult a table of powers of two to find the consecutive powers that contain your number.
>
> To see why this works, think of the binary representations of the integers 2^4 through 2^5 – 1, for example. They are 10000 through 11111, all possible 5-bit values.
>
> ## Using Logarithms
>
> The above method can be stated another way: the number of bits is the exponent of the smallest power of two greater than your number. You can state that mathematically as:
>
> bspec = ⌊log2(n)⌋ + 1
>
> That formula has three parts:
>
> * log2(n) means the logarithm in base 2 of n, which is the exponent to which 2 is raised to get n. For example, log2(123) ≈ 6.9425145. The presence of a fractional part means n is between powers of two.
> * ⌊x⌋ is the floor of x, which is the integer part of x. For example, ⌊6.9425145⌋ = 6. You can think of ⌊log2(n)⌋ as the exponent of the highest power of two in the binary representation of n.
> * +1 takes the exponent to the next higher power of two. You can think of this step as accounting for the 2^0th place of your binary number, which then gives you its total number of bits. For our example, that’s 6 + 1 = 7. You might be tempted to use the ceiling function — ⌈x⌉, which is the smallest integer greater than or equal to x — to compute the number of bits as such:
>
> bspec = ⌈log2(n)⌉
>
> However, this fails when n is a power of two.

# Answer
> 5 votes
# C#, 32 bytes

```
n=>Convert.ToString(n,2).Length;

```

Converts the parameter to a binary string and returns the length of the string.

# Answer
> 4 votes
## Haskell, 20 bytes

```
succ.floor.logBase 2

```

Composes a function that takes logarithm base 2, floors, and adds 1.

# Answer
> 4 votes
# Befunge-93, ~~23~~ 21 Bytes

```
&>2# /# :_1>+#<\#1_.@

```

Befunge is a 2D grid-based language (although I'm only using one line).

```
&                      take integer input
 >2# /# :_             until the top of the stack is zero, halve and duplicate it
          1>+#<\#1_    find the length of the stack
                   .@  output that length as an integer and terminate the program

```

Try it online!

# Answer
> 3 votes
## Jellyfish, 4 bytes

```
p#bi

```

Try it online!

Print (`p`), the length (`#`) of the binary representation (`b`) of the input (`i`).

# Answer
> 3 votes
## CJam, 5 bytes

```
ri2b,

```

Try it online!

Read input (`r`), convert to integer (`i`), get binary representation (`2b`), get length (`,`).

# Answer
> 3 votes
# Octave, 19 bytes

```
@(x)ceil(log2(x+1))

```

Anonymous function that adds 1, computes binary logarithm and rounds up.

Try it online!

# Answer
> 3 votes
## QBIC, 18 bytes

```
:{~2^q>a|_Xq\q=q+1

```

That's incredible Mike! But how does it work?

```
:        Read input as integer 'a'
{        Start an infinite DO-LOOP
~2^q>a   If 2 to the power of q (which is 1 by default) is greater than a
|_Xq     Then quit, printing q
\q=q+1   Else, increment q
[LOOP is closed implicitly by QBIC]

```

# Answer
> 3 votes
# Java 8, ~~34~~ 27 bytes

For once, Java has some useful builtins! Now, we just need some shorter names...

```
x->x.toString(x,2).length()

```

**Try it online!**

Of course, you can do this without builtins (see Snowman's answer), but for a higher byte count.

# Answer
> 3 votes
# Octave, 19 bytes

```
@(x)nnz(dec2bin(x))    % or
@(x)nnz(de2bi(x)+1)    % or
@(x)nnz(de2bi(x)<2)    % or
@(x)numel(de2bi(x))    % or
@(x)rows(de2bi(x'))

```

Octave has two functions for converting decimal numbers to binary numbers.

**`dec2bin`** converts a number into a string of the characters `1` and `0` (ASCII-values `48` and `49`). The length of the string will be equal to the necessary number of bits, unless specified otherwise. Since the characters `1` and `0` are non-zero, we can use `nnz` to find the number of elements like this: `@(x)nnz(dec2bin(x))`. This is 19 bytes, so it's tied with Luis Mendo's other Octave answer.

**Can we do better using `de2bi`?**

**`de2bi`** is a function that returns the binary numbers as a vector with the numbers `1` and `0` as integers, not characters. `de2bi` is obviously two bytes shorter than `dec2bin`, but we can no longer use `nnz`. We *can* use `nnz` if we either add `1` to all elements, or makes it into a logical vector with only `true` values. `@(x)nnz(de2bi(x)+1)` and `@(x)nnz(de2bi(x)<2)` are both 19 bytes. Using `numel` will also give us 19 bytes, `@(x)numel(de2bi(x))`.

`rows` is one byte shorter than `numel`, but `de2bi` returns a horizontal vector, so it must be transposed. `@(x)rows(de2bi(x)')` just so happens to be 19 bytes too.

# Answer
> 2 votes
## Pyke, 3 bytes

```
b2l

```

Try it here!

# Answer
> 2 votes
# Retina,  ~~44~~  23 bytes

Requires too much memory to run for large input values. Converts to unary, then repeatedly divides by 2, counting how many times until it hits zero. Byte count assumes ISO 8859-1 encoding.

```
.*
$*
+`^(1+)1?\1
$1_
.

```

**Try it online**

# Answer
> 2 votes
# Perl, 21 bytes

### 21 bytes, (ab)use the fact that `$=` must be an integer

```
say$==1+log(<>)/log 2

```

### 25 bytes, naïve implementation

```
say length sprintf"%b",<>

```

### 28 23 byte version without whitespaces

```
$-++while$_>>=1;say++$-

```

```
1while($i//=<>)>=1<<++$_;say

```

---

**Usage**

```
$ echo 128 | perl -E '$-++while$_>>=1;say++$-'
8
$ echo 128 | perl -E 'say length sprintf"%b",<>'
8

```

# Answer
> 2 votes
# Python 2, 28 Bytes

`def f(a):print len(bin(a))-2`

# Answer
> 2 votes
## JavaScript (ES6), 17 bytes

```
f=
a=>-~Math.log2(a)
```

```
<input type=number min=0 oninput=o.textContent=f(this.value)><div>Bits: <span id=o>
```

Saved 2 bytes thanks to @edc65.

# Answer
> 2 votes
# PHP, 21 bytes

```
<?=-~log($argv[1],2);

```
* `log(x,2)` Computes log2(x)
* `~` is the binary negation operator that also cast to int
* `-` take opposite

### 28 bytes

```
<?=strlen(decbin($argv[1]));

```
* `decbin` convert to binary
* `strlen` takes length

### 28 bytes

```
<?=floor(log($argv[1],2))+1;

```
* `log(x,2)` compute log2(x)
* `floor ... +1` takes floor plus 1

### 32 bytes (Thanks Titus)

```
for(;2**++$i<=$argv[1];);echo$i;

```
* `2**$n` compute 2^n ie. pow(2,n) until superior to $argv\[1\]

# Answer
> 2 votes
# Java 8, 43 41

```
v->{int b=0;for(;v>0;++b,v/=2);return b;}

```

Counts the bits the old fashioned way and returns the count. Lambda fits into a `LongFunction<Integer>`.

# Answer
> 2 votes
# Actually, 2 bytes

```
├l

```

Try it online!

Explanation:

```
├l
├   binary representation (without leading zeroes)
 l  length

```

Since Actually uses arbitrary-width integers, this will work for any input, so long as there is enough memory and time.

# Answer
> 2 votes
### Japt, 2 bytes

```
¢l

```

`¢` converts the input into a base-2 string

`l` returns the length

Thanks ETHproductions for shaving off 3 bytes.

# Answer
> 1 votes
# APL, 6 bytes

`1+⌊2⍟⍵`

Omega is the right argument, which is replaced with the number in question.

Try it online!

# Answer
> 1 votes
# Julia, 16 bytes

```
n->endof(bin(n))

```

Anonymous function.

# Answer
> 1 votes
# C, ~~47~~ 39 bytes

```
int L(uint32_t X){return X?1+L(X/2):0;}

```

Not using a library function. The algorithm counts the number of bits needed by shifting right (or the equivalent divide by 2) until 0.

# Answer
> 1 votes
# RProgN, 4 Bytes.

```
~2BL

```

## Explained

```
~2BL    #
~        # Zero Space Segment, The rest of this code is interpreted as if it were a bunch of characters separated by spaces.
 2B     # Convert implicit input to Base 2
   L    # Get the length of that, and implicitly output.

```

Try it online!

# Answer
> 1 votes
# Pyth - 3 bytes

Alternative 3 byte answer. Takes `floor(log2(n))+1`

```
hsl

```

Test Suite.

# Answer
> 1 votes
## awk, 32 bytes

Iterate 2's exponent and see when it's greater than given value. Return the value in `exit`:

```
{for(;++i<=32;)if(2^i>$0)exit i}

```

Run it:

```
$ echo 4294967295| awk '{for(;++i<=32;)if(2^i>$0)exit i}'
$ echo $?
32

```

# Answer
> 1 votes
# C, 27 bytes

```
f(n){return n?1+f(n/2u):0;}

```

Inspired by the answer by Quentin. Uses an unsigned literal to avoid overflow when using 32-bit integers. Might be able to cut the unsigned part if `int` is 64-bit, but it's more interesting this way.

# Answer
> 1 votes
# Matlab, 21 Bytes

```
c=@(x)nnz(dec2bin(x))

```

Yay for anonymous functions!

Example usage:

```
c(6)

ans =

     3

```

# Answer
> 1 votes
# Julia, 15 bytes

```
n->ndigits(n,2)

```

This is an anonymous function that wraps Julia's built-in `ndigits` function that counts the number of digits of the input in the given base. Here we're giving it a base of 2.

Try it online!

# Answer
> 1 votes
# J, 11 bytes

```
2&(1+<.@^.)

```

This is a monadic verb that accepts input on the right.

```
2&(    @^.)  NB. Base 2 logarithm of the input
     <.      NB. Floor
   1+        NB. Add 1

```

Could likely be improved using `#` (tally) and `#:` (binary representation) but I haven't figured that part out yet.

Try it online!

# Answer
> 1 votes
# ForceLang, 88 bytes

Noncompeting, requires the latest interpreter release, which postdates the question. (The `ln` implementation used previously was too inaccurate with large values)

```
set i math.ln io.readnum()
set j math.ln 2
set k math.floor i.mult j.pow -1
io.write k+1

```

# Answer
> 1 votes
## Lithp, 30 bytes

```
 #N::((length(to-string N 2)))

```

Pretty simple. Convert the number to binary (`to-string N 2`) and return the length of the string.

Try it online!

## Alternate entry (no binary builtin), 38 bytes

```
 #N::((if(!= 0 N)((+ 1(x(>> N 1))))0))

```

Try it online!

Recursively shifts right by 1 each time the function is called, until we get to 0. This is an unsigned shift, so can support the full range of 0x0 - 0xFFFFFFFF. The Lithp `>>` operator is equivalent to Javascript's `>>>` operator.

# Answer
> 1 votes
## Powershell, ~~66~~ 48 bytes

*-18 bytes thanks to @briantist*

~~```
function l {[math]::floor([math]::log($args[0])/[math]::log(2))+1}

```~~
```
($m=[math])::floor(m::log($args[0])/m::log(2))+1

```

Doing anything in Powershell is complicated, but it's better than Batch! In just Batch, this challenge isn't even possible (no decimal numbers=no logarithms).

# Answer
> 1 votes
## VBScript, 45 bytes

```
Sub l(n)
WScript.Echo Log(n)/Log(2)+1
End Sub

```

See result by adding `l(whatever the number is)` to the end of the file. Run with `cscript.exe` if you want the result in a command window.

# Answer
> 1 votes
# Perl, 19 bytes

```
$_=0|1+(log)/log 2

```

The score includes **1 byte** for the `-p` switch the program requires.

Try it online!

# Answer
> 1 votes
### Javascript, 23 bytes

```
x=>x.toString(2).length

```

```
f=x=>x.toString(2).length
document.write(f(341)) // 9
```

# Answer
> 1 votes
# TI-Basic, 8 bytes

```
1+int(logBASE(Ans,2

```

# Answer
> 1 votes
# C, ~~39~~ 36 bytes

```
f(n,*p){*p=0;while(n){n/=2;(*p)++;}}

```

Ungolfed version:

```
 void f(long int n, int *p)
 {
   *p=0;
    while(n!=0)
    {
      n/=2;
     (*p)++;
    }
  }

```

The `main()` function that accepts number from `stdin`, would look like this:

```
   int main()
   {
       int b=0
       long int num;
       scanf("%ld",&num);
       f(num,&b);
       printf("%d\n",b);
       return 0;
   }
`

```

## Alternative:

```
f(long n){i=0;while(n!=0){n/=2;i++;}return i;}

```

Ungolfed version:

```
int f(int n)
{
  int i=0;

  while(n!=0)
  {
    n/=2;
    i++;

  }
   return i;
}

```

# Answer
> 1 votes
# SmileBASIC, 20 bytes

```
INPUT N?LEN(BIN$(N))

```

# Answer
> 1 votes
## Ruby, 19 bytes

```
->i{i.to_s(2).size}

```

# Answer
> 1 votes
# Python 2, 39 bytes

```
lambda x:__import__('math').frexp(x)[1]

```

Not even kind of the shortest, but it showcases a neat function that could be useful elsewhere!

`frexp(n)` represents n as `n = m * 2**e` with `0.5 <= abs(m) < 1` and then returns the tuple `(m, e)` as output. For positive integers, `e` is exactly the number of bits required to represent the number.

# Answer
> 1 votes
# Common Lisp, 39 bytes

```
(defun f(i)(length(format nil "~B" i)))

```

Try it online!

# Answer
> 1 votes
# Python 2, 22 bytes

```
lambda n:len(bin(n))-2

```

Try it online!

# Answer
> 1 votes
# Dodos, 60 bytes

```
	' S ' g
g
	S dab
	g S ' dab f
f
	f ' '
	S dab
'
	dip
S
	dot

```

Try it online!

(`S` computes the sum, `S ' dab f` divides by 2)

# Answer
> 1 votes
# Vyxal, 2 bytes

```
bL

```

Try it Online!

### Explained

```
bL
b  # binary
 L # length

```

# Answer
> 0 votes
# 68020 assembler, 2 4 bytes (I think)

```
BFFFO D0, D1
INC D1

```

The BFFFO instruction finds the position of the first set bit in parameter 1, and stores the result in parameter 2. I think it is a 2-byte instruction. Unfortunately, it is indexed from 0, not 1. Hence you need an INC on D1 afterwards.

# Answer
> 0 votes
# Pushy, 11 bytes

```
0{${h}2/;}#

```

**Try it online!**

This works by continually doing `x = x // 2` until `x = 0`, and counting the number of divisions taken:

```
0            \ Push a 0 (initial counter)
 {$     ;    \ While input > 0:
   {h}       \  Increment counter
      2/     \  Floordiv input by 2
         }#  \ Output final counter

```

# Answer
> 0 votes
# PowerShell v3+, ~~37~~ 34 bytes

```
param($n)(1..32|?{!($n-shr$_)})[0]

```

Try it online!

# Answer
> 0 votes
# Groovy, 32 bytes

```
{Long.toBinaryString(it).size()}

```

This is an unnamed closure.

Try it here !

# Answer
> 0 votes
# J, 4 bytes

```
#&#:

```

**Explanation:**

```
#      NB. Counts length of bit list
&      NB. Connects # and #:
#:     NB. Creates list of bits

```

# Answer
> 0 votes
# MATL, 2 bytes

```
Bn

```

The shortest solution in MATL seems to be just direct, by measuring the length of the binary representation (as a vector). Other options are `ZlkQ`, which takes the base-2 logarithm, floors it and adds 1, or `YBn` which converts the input to a binary string and finds the length.

# Answer
> 0 votes
## /Kona, 4 bytes

```
#2\:

```

`\:` gets the representation of right-hand in base left-hand - in this case, base 2 of the input. `#` then just counts this

```
k)2\:341
1 0 1 0 1 0 1 0 1
k)#2\:341
9

```

# Answer
> 0 votes
# Befunge-98 (PyFunge), ~~19~~ 16 bytes, Thanks to @JoKing

```
&#\<_$.@j3:/2\+1

```

Try it online!

19 bytes:

```
&0#;1+\2/:!3j@.$_\;

```

Try it online!

5 bytes shorter than Befunge-93 :)

# Answer
> 0 votes
# Whitespace, 70 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T   S S N
_If_0_jump_to_Label_PRINT][S S S T  S N
_Push_2][T  S T S _Integer_division][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer i = STDIN as integer
Integer r = 0
Start LOOP:
  if i is 0:
    Call function PRINT_AND_EXIT
  i = i integer-divided by 2
  r = r + 1
  Go to next iteration of LOOP

function PRINT_AND_EXIT:
  Print r as integer
  Exit with error

```

**Example run (`n=16`):**

```
Command   Explanation                 Stack       HEAP     STDIN   STDOUT  STDERR

SSSN      Push 0                      [0]
SNS       Duplicate top (0)           [0,0]
SNS       Duplicate top (0)           [0,0,0]
TNTT      Read STDIN as integer       [0,0]       {0:16}   16
TTT       Retrieve                    [0,16]      {0:16}
NSSN      Create Label_LOOP           [0,16]      {0:16}
 SNS      Duplicate top (16)          [0,16,16]   {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [0,16]      {0:16}
 SSSTSN   Push 2                      [0,16,2]    {0:16}
 TSTS     Integer-divide (16/2)       [0,8]       {0:16}
 SNT      Swap top two                [8,0]       {0:16}
 SSSTN    Push 1                      [8,0,1]     {0:16}
 TSSS     Add (0+1)                   [8,1]       {0:16}
 SNT      Swap top two                [1,8]       {0:16}
 NSNN     Jump to Label_LOOP          [1,8]       {0:16}

 SNS      Duplicate top (8)           [1,8,8]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [1,8]       {0:16}
 SSSTSN   Push 2                      [1,8,2]     {0:16}
 TSTS     Integer-divide (8/2)        [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 SSSTN    Push 1                      [4,1,1]     {0:16}
 TSSS     Add (1+1)                   [4,2]       {0:16}
 SNT      Swap top two                [2,4]       {0:16}
 NSNN     Jump to Label_LOOP          [2,4]       {0:16}

 SNS      Duplicate top (4)           [2,4,4]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [2,4]       {0:16}
 SSSTSN   Push 2                      [2,4,2]     {0:16}
 TSTS     Integer-divide (4/2)        [2,2]       {0:16}
 SNT      Swap top two                [2,2]       {0:16}
 SSSTN    Push 1                      [2,2,1]     {0:16}
 TSSS     Add (2+1)                   [2,3]       {0:16}
 SNT      Swap top two                [3,2]       {0:16}
 NSNN     Jump to Label_LOOP          [3,2]       {0:16}

 SNS      Duplicate top (2)           [3,2,2]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [3,2]       {0:16}
 SSSTSN   Push 2                      [3,2,2]     {0:16}
 TSTS     Integer-divide (2/2)        [3,1]       {0:16}
 SNT      Swap top two                [1,3]       {0:16}
 SSSTN    Push 1                      [1,3,1]     {0:16}
 TSSS     Add (3+1)                   [1,4]       {0:16}
 SNT      Swap top two                [4,1]       {0:16}
 NSNN     Jump to Label_LOOP          [4,1]       {0:16}

 SNS      Duplicate top (1)           [4,1,1]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [4,1]       {0:16}
 SSSTSN   Push 2                      [4,1,2]     {0:16}
 TSTS     Integer-divide (1/2)        [4,0]       {0:16}
 SNT      Swap top two                [0,4]       {0:16}
 SSSTN    Push 1                      [0,4,1]     {0:16}
 TSSS     Add (4+1)                   [0,5]       {0:16}
 SNT      Swap top two                [5,0]       {0:16}
 NSNN     Jump to Label_LOOP          [5,0]       {0:16}

 SNS      Duplicate top (0)           [5,0,0]     {0:16}
 NTSSN    If 0: Jump to Label_PRINT   [5,0]       {0:16}
NSSSN     Create Label_PRINT          [5,0]       {0:16}
 SNN      Discard top                 [5]         {0:16}
 TNST     Print as integer            []          {0:16}           5
                                                                            error

```

Program stops with an error: No exit found.

# Answer
> 0 votes
# Brain-Flak, 48 bytes

```
({<({<(({}[()]))>{()(<{}({}[()])>)}{}}{})>()}{})

```

Try it online!

Readable version:

```
({< # Start a loop

  #devide by two:
  ({<(({}[()]))>{()(<{}({}[()])>)}{}}{})

>()} # Count interations
{} # pop the zero
) # push the result

```

# Answer
> 0 votes
# Thunno 2 `L`, 1 byte

Attempt This Online!

converts to binary; the `L` flag takes the length.

---
Tags: code-golf, binary
---


title: Randomizing until 0

text:
# Question
Title: 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
* Your program must finish.
* `0` must be the final output, Optionally an empty line instead `0`

# Answer
# 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.

```
> 19 votes

# Answer
# 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

```
> 15 votes

# Answer
# , ~~66 60 56 43~~ 41 bytes

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

```

Try it online!
> 10 votes

# Answer
# 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)

```
> 6 votes

# Answer
# 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

```
> 6 votes

# Answer
# 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.
> 5 votes

# Answer
# Perl 5.10.0 `-pl`, 26 bytes

```
say;say while$_=int rand$_

```

Try it online!
> 5 votes

# Answer
# 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.

```
> 5 votes

# Answer
# 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

```
> 4 votes

# 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>
```
> 4 votes

# Answer
# 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`.
> 4 votes

# 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!
> 4 votes

# Answer
# 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);
}

```
> 4 votes

# Answer
# 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
> 4 votes

# Answer
# Factor, 21 bytes

```
[ [ random ] follow ]

```

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` has an example code that solves almost the same task, but it is actually longer since it tries to exclude zero at the end.
> 4 votes

# Answer
# Python 2, ~~64~~ ~~62~~ 60 bytes

```
from random import*
k=input()
while k:print k;k=randrange(k)

```

Try it online!

---

Saved

* -2 bytes, thanks to Jonathan Allan
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~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!

`{``}⍣=` 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)
> 3 votes

# 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!

**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.
> 3 votes

# Answer
# 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.
> 3 votes

# 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

```
> 3 votes

# 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

```
> 3 votes

# Answer
# TI-Basic (TI-84 Plus CE), ~~17~~ 13 bytes

```
While Ans
Disp Ans
int(randAns
End
Ans

```

-4 bytes from Misha Lavrov

Takes input in `Ans` as `50:prgmNAME`.

TI-Basic is a tokenized language. 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

```
> 3 votes

# Answer
# Python 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!
> 3 votes

# 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!

\>\<\>'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

```
> 3 votes

# Answer
# 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.
> 2 votes

# Answer
# PHP, ~~43~~ 42 bytes

```
<?while($a=$a?rand(0,$a-1):$argn)echo$a?>0

```

To run it:

```
echo '<input>' | php -nF <filename>

```

Or Try it online!

Example output:

```
10019128410

```

-1 byte thanks to Titus's suggestion.
> 2 votes

# Answer
# 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 :)
> 2 votes

# Answer
# Haskell, ~~74~~ 71 bytes

<sup>-3 bytes by actually doing what the specs say it should do.</sup>

```
import System.Random
f 0=pure[0]
f x=randomRIO(0::Int,x-1)>>=fmap(x:).f

```

Try it online!
> 2 votes

# Answer
# Java, 56 bytes

```
Object f(int n){return n<1?0:n+","+f(n*=Math.random());}

```

Try It Online

## Acknowledgments
> 2 votes

# 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:
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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).
> 2 votes

# Answer
# 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 :)
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~84~~ 82 bytes

```
var k=int.Parse(ReadLine());for(Write(k);k>0;)Write($",{k=new Random().Next(k)}");

```

Try it online!

-2 Bytes thanks to charliefox2

**Explenation:**

```
var k = int.Parse(ReadLine());   //1. Read a line from STDIN and convert it to int
for(Write(k);                    //2. Write the original value of k to STDOUT
        k>0;)                    //3. Loop while k > 0
    Write($",{                   //6. Write the separator and the new value to STDOUT
        k =                      //5. Assign it to k
        new Random().Next(k)}"); //4. Get a random int between 0 (inclusive) and k (exclusive)

```
> 2 votes

# Answer
# CJam, ~~7~~ 9 bytes

```
ri{_pmr}h

```

Try it online!

Annotated

```
r       e# read input token
i       e# convert to int
{       e# do {
    _   e# duplicate topOfStack
    p   e# pop topOfStack and print it
    mr  e# rand(0, topOfStack)
}h      e# } while(topOfStack != 0)
        e# implicitly convert stack to string and print it

```
> 2 votes

# Answer
# Bash, 65 58 56 50 bytes

```
f()(echo ${a=$1};for((;a;)){ echo $[a=RANDOM%a];})

```

Try it online!

(Improved thanks to manatwork)

**Recursive approach**

50  28

```
f()(echo $1&&f $[RANDOM%$1])

```

Try
> 2 votes

# Answer
# Atari 400/800 6502 Assembler – 16 bytes

`K` set initially to `#$FF` (but can set to any byte value), then calls the `POKEY` PRNG at `$D20A`, if greater than or equal, try again, else save as the new upper limit. Keep going until it reaches zero.

```
define K $FF
* = $600
    LDA #K
.1: STA $80
    BEQ .3
.2: LDA $D20A
    CMP $80
    BCC .1
    BCS .2
.3: BRK       ; if you assume memory is cleared, can omit for 15 bytes

```

Which, when assembled, is:

```
a9 ff 85 80 f0 09 ad 0a d2 c5 80 90 f5 b0 f7 00

```

Output is by running a monitor, single stepping, and spying on `$80`! The rules indicated “output format as you wish”!
> 2 votes

# Answer
# C# (.NET Core), 71 bytes

Using recursion.

```
static int f(int k){Console.WriteLine(k);return k==0?k:f(r.Next(0,k));}

```

Try it online!

Output:

```
100
9
3
0

```
> 2 votes

# Answer
# \>\<\>, 147 + 2 bytes

```
 :0=?\:0&:0=?\:2%-2,&1+&80.
   ;n/       \r:r&:0=?\1-&2*\
          /oan:{/?(}:~/44+\ v
<         \:0=?;>{~00.\*1.^0x
                          \1/

```

Try it online!

The idea is the same as @Sasha's—generate random bits, making sure not to exceed the original number—but just in a different layout. My solution uses the register to record the number of bits of n.

There is unfortunately a certain amount of wasted space, particularly on the last line.

**How it works:**

```
 :0=?\:0&                      n = 0?   No: duplicate n; let reg = 0
   ;n/                                  Yes: print then end

         :0=?\:2%-2,&1+&80.    n = 0?   No: n = floor(n / 2); increment reg; loop to (8,0)
             \                          Yes: enter loop to construct random number r

              r:r&:0=?\1-&2*\  reg = 0? No: r = 2 * r + (0 or 1); loop to (16, 1)
                      /44+\ v           Yes: check if r <= n
<                     \*1.^0x
                          \1/

          /oan:{/?(}:~         r > n?   No: print r and newline;
          \:0=?;>

                 {~00.         Go back to (0,0), using either r or n

```
> 2 votes

# Answer
# Kotlin, 60 bytes

```
fun f(k:Int){println(k);if(k>0)f((Math.random()*k).toInt())}

```

Try it online!

Solution with recursion.
> 2 votes

# Answer
# , 8 bytes

```
?^:*^:a:

```

Try it online!

### How it works

`f^:g^:_` is a J idiom for "do while", which means to repeatedly apply `f` to the input while `g` gives true. `g` should always give 0 or 1. Change the last `_` (infinity) to `a:` (boxed empty), and the resulting verb gives the list of intermediate values.

Monadic `?` is "roll", i.e. given `N`, generates a random integer between 0 and `N-1` inclusive. Monadic `*` is "signum", i.e. gives 1 for positive, 0 for zero, -1 for negative input.
> 2 votes

# Answer
# Vyxal `M`, 4 bytes

```
{℅…|

```

Try it Online!

the M flag generates a range 0-n implicitly

```
{         # while true
 ℅        # random in range 0-n
  …|      # print w/o popping

```
> 2 votes

# Answer
# Charcoal, 11 bytes

```
ＩθＷ⊟θＩ⊞Ｏθ‽ι

```

Try it online! Link is to verbose version of code. Slightly unusual input format. Explanation:

```
Ｉθ

```

Cast the input to string and print it.

```
Ｗ⊟θ

```

While the input is non-zero...

```
⊞Ｏθ‽ι

```

... replace it with a random number in the implicit range...

... and cast the result to string and print it.

13-byte version with more standard input format:

```
θＮθＷθ«≔‽θθ⸿Ｉθ

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# Jelly, 6 bytes

```
X’$¹Ð¿

```

Try it online!
> 1 votes

# Answer
# JavaScript, 34 bytes

Outputs a space-delimited string of integers.

```
f=n=>n&&n+" "+f(Math.random()*n|0)

```

Try it online
> 1 votes

# Answer
# Ruby, ~~31~~ 29 bytes

```
->n{n=rand p n until 1>n;p 0}

```

Try it online!
> 1 votes

# Answer
# Red, 41 bytes

```
func[n][print n if 0 < n[f random n - 1]]

```

Try it online!
> 1 votes

# Answer
## Batch, 54 bytes

```
@echo %1&if %1 gtr 0 set/an=%random%%%%1&call %0 %%n%%

```

Four `%`s in a row... just a typical day for Batch. Only works up to 32768 (and not terribly uniform at that) due to limitations of Batch's random number generator. See my Batch answer to Pick a random number between 0 and n using a constant source of randomness for large uniform randomness.
> 1 votes

# Answer
# Japt, 10 bytes

Outputs an array of integers.

```
_Ì}f@NpU=ö

```

Try it

---

## Explanation

```
               :Implicit input of integer U
  }f           :Loop until left function returns falsey and return final value of right function
    @          :Right function
         ö     :  Random integer in the range [0,U)
       U=      :  Reassign to U
      p        :  Push
     N         :   To the array of inputs
_              :Left function
 Ì             :Get the last element of N. If it's 0, which is falsey, then the loop will be broken

```

---

## Alternative, 8 bytes

A direct port of my JavaScript solution.

```
©U+S+ßUö

```

Try it
> 1 votes

# Answer
# Excel VBA, 42 bytes

An anonymous function that takes input from range `[A1]` and outputs to the console.

```
k=[A1]:?k:While k:y=Int(k*Rnd):?y:k=y:Wend

```
> 1 votes

# Answer
# Python 2.7, 112 bytes

```
from random import randint
k=int(raw_input())
def r(k):
    y=randint(0, k-1)
    print y
    if y!=0:
        r(y)
r(k)

```
> 1 votes

# Answer
## F#, 70 bytes

```
let r=System.Random()
let rec x K=printfn"%i"K;if K>0 then r.Next K|>x

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 33 bytes

```
~n=(println(n);n>0&&~rand(0:n-1))

```

Try it online!

Defines the function as an operator `~` (to save bytes). Print the given number, and if we haven't reached 0, call itself recursively with a new uniformly random number from range `0:n-1`.

(Could've used `@show` instead of `println` since OP says "output format as you wish" (`@show` prints the variable name before the value every time, eg. `n = 8` instead of `8`), but the 2 byte saving doesn't seem worth it relative to total bytecount, and I like this neater output.)
> 1 votes

# Answer
# AWK, 56 bytes

```
{print($0);k=$0;for(srand();k>0;)print(k=int(k*rand()))}

```

Try it online!
> 1 votes

# Answer
# Pascal (FPC), 89 bytes

```
var K:word;begin Randomize;read(K);repeat writeln(K);K:=Random(K)until K<1;writeln(K)end.

```

Try it online!

Not only Pascal code is as long as usual, you also need to `Randomize;` beforehand...

Instead of writing of the initial value before the loop, 0 is written after the loop. This approach saves a byte because `1end.` isn't valid; instead od separating this into 2 tokens, it tries to find a meaningful scientific notation.
> 1 votes

# Answer
# Ruby, 23 bytes

```
f=->k{k<1||f[rand p k]}

```

Try it online!

### Non-recursive, 25 bytes

```
->k{k=rand p k while k>0}

```

Try it online!

```
->k{(k=rand p k)>0&&redo}

```

Try it online!
> 1 votes

# Answer
# MATLAB, 36 bytes

```
K
Y=1;while Y>0,Y=randi(K)-1;K=Y,end

```

**Sample output:** For `K = 25`

```
K =

    25

K =

    15

K =

    11

K =

     6

K =

     4

K =

     1

K =

     0

```
> 1 votes

# Answer
# Racket, 52 bytes

```
(define(f n)(println n)(unless(= n 0)(f(random n))))

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 49 bytes

```
~x=(println(x);x-1)
!x=(y=rand(0:~x))>0 ? !y : ~0

```

Try it online!

If one were willing to accept outputting all output except the last to STDOUT, and the last 0 as returning false, then it can be

```
~x=(println(x);x-1)
!x=(y=rand(0:~x))>0&&!y

```

Which is a bit short. But I think mixing outputs like that is not really in spirit.
> 1 votes

# Answer
# K4, ~~13~~ ~~12~~ 11 bytes

**Solution:**

```
(*1?)\[0<;]

```

**Examples:**

```
q)k)(*1?)\[0<;] 100
100 77 30 17 12 2 0
q)k)(*1?)\[0<;] 100
100 37 28 20 2 0
q)k)(*1?)\[0<;] 100
100 77 61 55 53 6 2 0
q)k)(*1?)\[0<;] 100
100 12 1 0

```

**Explanation:**

Iterate over expression while x is greater than zero.

```
(*1?)\[0<;] / the solution
(   )\[0<;] / iterate over brackets whilst 0< evaluates true
  1?        / 1 choose (returns a 1-item list)
 *          / take the first

```

**Bonus:**

A **14 byte** solution that also works in K (oK); this one is an if/else version of the same theme:

```
{$[x;*1?x;x]}\

```

Try it online!
> 1 votes

# Answer
# Elixir, 157 148 bytes

-9 bytes from Okx

```
defmodule N do def f(0,k)do IO.puts 0 end;def f(n,k)do IO.puts n;f Enum.random(0..k),k end end;k=String.to_integer IO.gets"";N.f Enum.random(0..k),k

```

Try it online!

Formatted:

```
defmodule N do
    def f(0,k) do
      IO.puts n
    end

    def f(n,k) do
      IO.puts n
      f Enum.random(0..k), k
    end
end
{k,_} = Integer.parse IO.gets""
N.f Enum.random(0..k),k

```

We define a module with 2 functions - one is recursive, the other is the base case with a guard so it only executes when our random is 0 (Elixir doesn't necessarily assign anything, it does pattern matching for e.g. arguments- and thus f(0,k) only matches when n=0, otherwise f(n,k) matches). After defining that module (since functions can't be defined outside a module), we parse an integer from input and start our recursive looping.

Notably, `k=String.to_integer IO.gets""` is the same length as the other method I've found to parse integers from input, `{k,_}=Integer.parse IO.gets""`, which is kinda neat.
> 1 votes

# Answer
# Common Lisp - 52 Bytes

```
(loop while (/= a 0) do (print (setf a (random a))))

```

Assumes `a` is already defined.

Test case:

```
(setf a 5000000)
(loop while (/= a 0) do (print (setf a (random a))))

```
> 1 votes

# Answer
# Elixir, 87 bytes

```
fn n->[n]++Enum.take_while(Stream.repeatedly(fn->Enum.random(0..n)end),&(&1>1))++[0]end

```

Try it online!
> 1 votes

# Answer
# PHP, 44 bytes

```
<?=$a=$argn;while($a--)echo _,$a=rand(0,$a);

```

or

```
<?for(;$a=&$argn;$a=rand(0,$a))echo$a--,_?>0

```

print integers delimited by underscore. Save to file, run as pipe with `-nF`.
> 1 votes

# Answer
# Noether, 9 bytes

```
I~n0(nRP)

```

**Try it online!**

Output is given in the form

```
735920

```

## Explanation:

```
I~n        - Store input in the variable n
   0(   ) - Loop until the top of the stack equals zero
     nR    - Push a random integer between 0 and n
       P   - Print the top of the stack

```
> 1 votes

# Answer
# Swift 4, 30 bytes

```
while n>0{n=rand()%n;print(n)}

```

Try it online!

`n` is the value of input
> 1 votes

# Answer
# Forth (gforth), 57 bytes

```
include random.fs
: f begin dup . random dup 0= until . ;

```

Try it online!

### Explanation

Get Random integer in range, loop until result is 0.

### Code Explanation

```
include random.fs     \ import the file that implements the "random" word
:f                    \ start a word defintion
  begin               \ start an indefinite loop
    dup .             \ duplicate the top of the stack and print it
    random            \ get random int between 0 and n - 1
    dup 0=            \ duplicate the top of the stack and then check if it's 0
  until               \ if it's zero end the loop
  .                   \ output the top of the stack (always 0)
;                     \ end the word definition

```
> 1 votes

# Answer
# Julia 1.0, 53 bytes

```
function q(N)println(N);if N>0;q(rand(0:N-1));end;end

```

Try it online!
> 1 votes

# Answer
# Pyt, 5 bytes

```
`0⇹ɾł

```

Try it online!

### Explanation:

```
         Implicit input
`   ł    Do ... while top of stack is not 0:
 0          Push 0
  ⇹         Swap top two elements on stack
   ɾ        Get random number in [0,top of stack)
         Implicit print

```
> 1 votes

# Answer
# Fortran 90, 56 bytes

```
read(*,*)i
do while(i>0)
i=rand(i)*i
print*,i
enddo
end

```

Trying to golf Fortran is always fun.

Also, because seeding the RNG in Fortran is a pain and costs a lot of bytes (and `RAND()` uses a particularly poor algorithm but has a nice short name), the output is pretty much deterministic - but I'm hoping to get away with it.

## Example

Input:

```
10000000

```

Output:

```
 2636923
 1681125
  264113
   17707
    2453
      47
       0

```
> 1 votes

# Answer
**PHP 5.6**

$k = $y = 5; do { echo $k. "\n"; $k = rand(0, $y-1); } while($k \> 0)
> 0 votes

# Answer
# MathGolf, 4 bytes

```
orw∟

```

Try it online.

**Explanation:**

```
   ∟  # Do-while true without popping:
o     #  Print the current integer with trailing newline (without popping)
      #  (which will be the implicit input-integer in the first iteration)
 r    #  Pop and push a list in the range [0,K)
  w   #  Pop and push a random integer from this list

```

Note: builtin `w` of itself works with an integer argument as well, but it'll output a random integer in the range \\$\[0,K\]\\$ instead of \\$\[0,K)\\$, hence the need for the explicit `r`.
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
(ß;Lɼ

```

Attempt This Online!

#### Explanation

```
(ß;Lɼ  # Implicit input
( ;    # While loop
 ß     # (condition)  Print TOS without popping
   Lɼ  # (body)       Choose a random integer in the range [0..TOS)

```
> 0 votes

---
Tags: code-golf, random
---