# Output a random unary string

Your task is simple: output the letter x a random number of times. Every possible length of xs must have a non-zero probability of being output.

Of course, there must be some lengths whose probabilities tend to $$\ 0 \$$, in order for the total probabilities to sum to $$\ 1 \$$, but all must still be theoretically possible.

• You may choose whether to include the empty string as a possible output
• You may have any consistent separator between the xs, and you may output the separator more than once. The separator may not contain the unary character
• You may use any other consistent single character instead of x
• Per standard rules, your program must always halt in finite time. (Terminating "with probability 1" is allowed, though)
• You can assume your language's random number generator is perfectly random. If it is supposedly continuous, you may assume it has infinite precision.

This is , so the shortest code wins.

• Sandbox Mar 1, 2022 at 11:33
• I'd like to emphasize how well specified this challenge is. This is not common for challenges involving randomness Mar 1, 2022 at 16:25
• @DominicvanEssen "You may choose whether to include the empty string as a possible output" Mar 1, 2022 at 16:31
• @LuisMendo A sandbox success story! It went through several revisions there. Mar 1, 2022 at 17:21
• "Of course, there must be some lengths whose probabilities tend to 0" This is a bit of an odd phrase. The probability of a single event can't really tend towards anything. But if we are talking about sequences, for every sequence of lengths whose probabilities don't tend towards zero that sequence must repeat some length an infinite number of times. :) Mar 1, 2022 at 17:33

# C++, 112 86 bytes

-26 bytes thanks to Unrelated String

#include<iostream>
main(){srand(time(0));for(int i=0;i<rand()%100;i++){std::cout<<1;}}


Try It Online!

• Shorter without the #define and typedef (and you can even remove the return type of main for a warning). Mar 4, 2022 at 3:08
• 81 bytes Mar 6, 2022 at 9:05

# Zsh, 19 bytes

grep -oam1 x /*/ur*

Attempt This Online!

Explanation:

• /*/ur*: glob for /dev/urandom, an infinite stream of random bytes
• grep x: search for the letter x
• -o: print only the letter xs
• -a: force output even though /dev/urandom is a binary file
• -m1: quit after the first matching line

# Pure Zsh, 20 bytes

for ((;RANDOM;))<<<x

Attempt This Online!

Loop breaks with probability $$\ \frac 1 {32768} \$$ for each iteration.

Explanation:

• for ((;RANDOM;)): loop while $RANDOM (which is a random integer in the range $$\ [0, 32768) \$$, is nonzero • <<<x: print x Here's a version for 2 bytes more with a probability of $$\ \frac 1 2 \$$, and is much more easy to demonstrate: for ((;RANDOM%2;))<<<x Attempt This Online! # x86 32-bit machine code (Linux), 22 bytes 00000000: 31db f7e3 4243 6a31 89e1 0404 cd80 580f 1...BCj1......X. 00000010: c7f0 a801 75ea ....u.  Asssembly: section .text global main main: ;call write(fd=ebx, *buf=ecx, count=edx) xor ebx, ebx ;ebx=0 mul ebx ;eax=edx=0 inc edx ;edx=1 inc ebx ;ebx=1 push 0x31 ;push '1' mov ecx, esp ;ecx=ptr to '1' add al, 4 ;eax=4 int 0x80 ;syscall to print '1' pop eax ;fix stack ;get rand & loop rdrand eax ;eax=rand() test al, 1 ;eax%2==0? jnz main ;if so, jmp to main  There is a 50% probability for each character printed for another one to print. Try it online! • test al, 1/jnz => inc eax/jp – l4m2 Jul 6, 2023 at 8:48 # Jelly, 5 bytes 2XĿȮ  Try it online! Function submission. There are two functions defined in the above code; the one being submitted is 1Ŀ, with 2Ŀ being a helper function. Outputs strings of 2 to standard output (the TIO link has a footer to suppress implicit output of the function's return value, because that isn't part of the output). ## Explanation Jelly isn't very good at this challenge, as golfing languages go, but I managed to beat the existing Jelly answer by one byte. The function 1Ŀ is defined as 2XĿȮ. 2X generates a random number, either 1 or 2. Then Ŀ runs the function with that number – this is either a recursive call if 1 was chosen as the random number, or a call to 2Ŀ if 2 was chosen. Finally, it produces output (Ȯ) – the output will always be 2 because that's the argument implicitly chosen for the function calls. If 1Ŀ calls itself many times recursively, it'll output from every recursive level, which is what produces a random-length string of 2s. The function 2Ŀ is defined with zero-length source code, and returns its input (i.e. the 2 that it was provided as input when called by 1Ŀ). # Excel, 19 17 bytes =REPT(1,1/RAND())  -2 bytes excluding 0 length string Link to Spreadsheet • "You may choose whether to include the empty string as a possible output", so I think you can shave that -1... Mar 1, 2022 at 16:34 • It was right there and I missed it. Doh! Mar 1, 2022 at 18:31 • You can shave off 1 byte by switching Excel language to Polish: =POWT(1,1/LOS()). Mar 2, 2022 at 13:19 • @pajonk And would Reverse Polish be = 1 1 LOS / POWT? – Neil Mar 3, 2022 at 13:54 • @Neil My HP 12C salutes you. Mar 3, 2022 at 16:17 # Retina, 6 bytes ?+$
x


Try it online! Outputs an average of 1 x. Explanation: The ? causes the loop created by + to run with a geometric distribution with a mean of 1. Each iteration of the loop appends an x to current value, which is then output when the loop terminates.

import System.Random
f=do n<-randomIO;putStr"x";if n then pure()else f


Try it online!

• Saved 5 thanks to @pxeger suggestions to use pure instead of return and semicolons;
• return can be pure, and you can smush the whole do block onto one line using semicolons, for -5 bytes in total: Try it online! Mar 1, 2022 at 21:16
• Thanks @pxeger I forgot to use ; .. I was struggling to find an alternative to return, I was sure there were some. I also read in some docs of a do block similar to list comprehension syntax but not sure if is just a proposal or what.. Forgot where it was unfortunately Mar 1, 2022 at 21:36

# MSX-BASIC, 28 bytes

1IFRND(-TIME)<.9THEN?1:GOTO1

• RND with a negative value gets the first value from the pseudo-random sequence whose seed is the passed value.
• TIME is a system 16 bit variable that increases continuously (and goes back to 0 on overflow) at 50 or 60Hz.
• ? is a convenient shortcut for PRINT.

# INTERCAL, 23 bytes

DOREADOUT#0DO%9TRYAGAIN


Try it online!

Prints a nonempty string of underscores separated by triple newlines, running a loop that continues 9% of the time (insert another digit if you want better odds).

## C - 76 Bytes

j;main(i){for(;j++<2+rand()%10;puts(""))for(i=0;i++<1+rand()%10;printf("x"));}


Ungolfed

j;

main(i)
{
for(; j++ < 2 + rand() % 10; puts(""))
for(i = 0; i++ < 1 + rand() % 10; printf("x"));

}


Explanation

A simple but complete program that prints a random number of strings of character 'x' of indeterminate length.

# Alice, 22 17 bytes

2' e+EUw.n$@t'xoK  Try it online! My first Alice attempt, I'm keen to see what can be made shorter! ## Explanations: 2' e+E Pushes max int on the stack 2^(32-1) U Random between max int and 0 w.n$@     K  While the top of the stack is not 0
t       -1 to the top of the stack
'x     Pushes x on the stack
o    Prints the top of the stack as a character


# Awk, 33 34 bytes

END{for(srand();rand();)print"x"}


Try it online!

It is possible for awk's rand() to return 0, but very unlikely.

Thanks to Marius_Couet for the byte!

# PHP, 74 bytes

With "include the empty string as a possible output".

while(0<$r=rand(0,100)/10){echo$r<0.1?'':str_repeat('p',round($r))."\n";}  Try it online! # PHP, 52 bytes while(0<$r=rand(0,9)){echo str_repeat('p',$r)."\n";}  Try it online! # Nim, 48 bytes import random;randomize();while rand(1)<1:echo 1 Attempt This Online! This program has a newline as a separator and a '1' as the character. wc -c was utilized to count the number of bytes. I am reasonably certain this is optimal for Nim; I therefore will offer a bounty of 50 rep to the person who outgolfs it. # APL, 20 bytes ∇X←P X←⍬ X,←'x' →?4∇  The output strings are usually extremely short, but hypothetically they could be any length. # Racket, 30 bytes (do()((>(random).5))(print 1))  Try it online! ## Explanation Creates a do loop that will only run if the randomly generated number is less than .5. The first argument of the do loop are the local variables and/or iterators. The second argument is the stop?-expr. If this argument returns true (#t), the loop will stop. Otherwise the body of the loop will be run. (do () ((> (random) .5)) (print 1))  # Fish, 31 bytes while [ (random) = 0 ];echo;end  This uses the newline (U+000A) as the unary character. random returns any value from 0-32768 without arguments, so on most runs this will echo nothing. However, it is technically possible for this to echo an unlimited number of characters, just not very likely # Befunge-93, 4 bytes ?@#.  Try it online! ## Explanation The ? instruction sends the program counter (PC) in a random direction. If the PC goes right, it hits the @ instruction, which terminates the program. If it goes up or down, it makes a new random choice. If it goes left, it hits the . instruction, which pops the top of the stack and prints it as an integer. There is no stack underflow in Befunge (or at least not in the implementation tio uses), so the value popped is the default value, zero (0). So the program prints 0, with a single space ( ) as a separator. The bridge command # makes sure that another random choice will occur and the @ isn't immediately triggered. # VBA, 20 bytes Anonymous immediate window function that outputs a sequence of newline literals of random length to the immediate window console. While(rnd>.5):?:Wend  # Perl 5, 18 16 bytes say while.9>rand  Try it online! Saved two bytes by making the unary character a newline. # Bash, 31 bytes while(($RANDOM));do echo 1;done


Try it online!

• This doesn't output anything longer than 32767, does it? Mar 5, 2022 at 6:35
• @pxeger Yes, it does. Mar 5, 2022 at 6:48
• So then it's an invalid answer. Read the question again: it needs to be possible to output strings of any arbitrary length Mar 5, 2022 at 7:08
• @pxeger One question, why your code in Pure Zsh is valid? It doesn't output anything longer than 32767 as well, does it? Mar 5, 2022 at 7:15
• No, mine doesn't just loop $RANDOM times; it's a while loop - each time it loops, it checks if $RANDOM is zero, and if so, stops the loop. So it's possible for it to loop more than that many times, if \$RANDOM takes 32769 or more iterations before reaching zero Mar 5, 2022 at 7:28

# Emmental, 20 bytes

When the computer runs out of stack space it will crash.

;#58:#46#35#63#!#1#?


Try it online! When the computer runs out of stack space it will crash.

# Thunno 2, 5 bytes

(¢TLɼ


Attempt This Online!

#### Explanation

(      # loop while the following is true:
¢     #  print a 0 without a trailing newline
TL   #  push the range [1..10]
ɼ  #  choose a random item from that list


# Thue 17 bytes

E::=
E::=E*
::=
E


On the interpreter that I use, it is randoms

# Ly, 8 bytes

1?[01?]p


Try it online!

Pushes the number 1 onto the stack a random number of times then exits. The accumulated numbers are printed automatically with a space between them. The probabilities favor small (or zero) numbers, but there's a non-zero change of any length output.

1?        - Push "1" on the stack, replace with 0|1 randomly
[   ]   - Loop while the top of the stack is non-zero
01?    - Push "0 1", pop them and push 0|1 randomly
p  - Pop the "0" that ended the loop off the stack


# Volatile, 7 bytes

~(:-.~)


Assumes that the . instruction is present in the interpreter. Prints a random length of 0 characters. Empty string is possible. Zeroes may be separated by another character, depending on the implementation you're using.

jot 19 | mawk 'NF+=int(rand()*19)' OFS=x


1xxxxxxx
2xxxxxxxxxx
3xxxxx
4
5xxxxxxxxxxxxxxx
6xxxxxxxxx
7xxxxxxx
8xxxxx
9xxxxxxxxx
10xxxxxx
11xxx
12xxxxx
13xxxxxxxx
14x
15xxxxxxxxx
16xxxxxxxx
17xxxxxxxxxxxxxxxxxx
18xxxxx
19


# Yabasic, 22 bytes

Function that outputs a sequence of newline literals of random length.

While(ran()>.5):?:Wend
`

Try it online!