g | x | w | all
Bytes Lang Time Link
040ShellScript jot + mawk240130T053602ZRARE Kpo
033Awk240131T024807ZcamelCas
016Perl 5220328T035811ZXcali
029JavaScript Node.js220301T115337Zl4m2
022Yabasic240130T172610ZTaylor R
020VBA240130T173017ZTaylor R
007Volatile230908T205433Zbluswimm
004Befunge93230724T203214ZJoe
008Ly230723T081747Zcnamejj
031Fish230722T063636ZThe Zip
030Racket230721T182307ZEd The &
017Thue230721T163247ZDadsdy
005Thunno 2230714T083111ZThe Thon
050Python 3220301T150559Zsolid.py
017Alice220713T222408ZJulian
020APL220713T050002ZVadim Tu
005Jelly220713T232900Zais523
048Nim220418T062949ZQaziquza
010TIBasic TI84220304T002137ZMarcMush
020Emmental220412T040239ZOhentis
076C 76 Bytes220328T022952Zuser1117
022x86 32bit machine code Linux220315T190750Zuser3604
074PHP220305T210734ZLucianDe
031Bash220305T030315Zsinvec
019Zsh220302T092423Zpxeger
041Python 3220302T193112ZAmir rez
nanC++220304T030557Zoeuf
006Random Brainfuck220302T150208ZConor O&
024Wolfram Language Mathematica220301T211944ZRoman
023INTERCAL220303T183704ZUnrelate
044Java220301T171936ZSeggan
028MSXBASIC220303T140516ZKonamima
022Julia 1.0220303T125433ZMarcMush
006Cascade220303T064001ZUnrelate
020Thue220303T000827ZDLosc
056Haskell220302T233119ZBubbler
003MathGolf220302T143615ZKevin Cr
020R220302T160157ZDominic
026Pure Bash no external utilities220301T175937ZDigital
014Alchemist220302T154403ZNitrodon
007Brachylog220302T144456ZFatalize
028Batch220302T110835ZNeil
00505AB1E220302T080223ZKevin Cr
009J220301T131248Zsinvec
070Haskell220301T211515ZAZTECCO
003><>220301T204902Zje je
043Pari/GP220301T185744ZDLosc
006Vyxal 2.4.1220301T190258Zemanresu
006Retina220301T124451ZNeil
017Excel220301T155001ZAxuary
021Factor + random.c220301T172552Zchunes
004Pip220301T180837ZDLosc
025MATLAB220301T140623ZGroger
005MATL220301T162012ZLuis Men
029C gcc220301T154719ZAZTECCO
017R220301T131525ZGiuseppe
006Jelly220301T122312ZJonathan
004Charcoal220301T123717ZNeil

ShellScript: jot + mawk: 40 bytes

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

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!

Perl 5, 18 16 bytes

say while.9>rand

Try it online!

Saved two bytes by making the unary character a newline.

JavaScript (Node.js), 29 bytes by noodle man

_=>''.padEnd(1/Math.random())

Try it online!

JavaScript (Node.js), 30 bytes

f=_=>Math.random()>.5?'':1+f()

Try it online!

Simple

Yabasic, 22 bytes

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

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

Try it online!

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

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.

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.

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

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

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

Thue 17 bytes

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

On the interpreter that I use, it is randoms

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

Python 3, 50 bytes

lambda:'x'*int(1/(1-random()))
from random import*

Attempt This Online!

Thanks to users pxeger and DominicVanEssen for their clarifications.

Outputs the character x a random number of times. Random sequences of xs are separated by the newline character.

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

APL, 20 bytes

∇X←P
X←⍬
X,←'x'
→?4∇

The output strings are usually extremely short, but hypothetically they could be any length.

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Ŀ).

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.

TI-Basic (TI-84), 11 10 bytes

Repeat checkTmr(startTmr
Disp 1
End

the program can only end when the check checkTmr(startTmr happens between two seconds (checkTmr(startTmr) = 1 instead of 0). This way, any number of ones is possible (the shortest I got was 3 ones, the longest printed during approx 10 seconds)

Repeat always executes the loop the first time, so the empty string is not included (repeat until or do while not)

For calculators without time (TI-83), replace checkTmr(startTmr with rand>.9 but it's not true randomness (same output on each reset of the calculator)

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.

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.

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!

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!

Bash, 31 bytes

while(($RANDOM));do echo 1;done

Try it online!

Zsh, 19 bytes

grep -oam1 x /*/ur*

Attempt This Online!

Explanation:


Pure Zsh, 20 bytes

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

Attempt This Online!

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

Explanation:

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!

Python 3, 62 60 59 45 43 41 bytes

import os
while os.urandom(1)[0]:print(1)

Try online!

Thanks to @pxeger, @mvirts, @MarcMush and @loopywalt.

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!

Random Brainfuck, 7 6 bytes

-1 byte thanks to je je's observation that Null bytes are accebtale as output.

+[>.?]

Try it online!

Outputs at least 1 0x01 character, and terminates each iteration with a 1/256 chance. ? sets the current cell to a random byte, and this will only terminate when that byte is 0.

Detailed Explanation

+       set first cell to 1
[       while the current cell is non-zero:
  >         move right one cell
  .         output it (0x00)
  ?         set current cell to a random byte from 0 to 255
]       end while

Wolfram Language (Mathematica), 28 24 bytes

Dot@@Table[x,1/Random[]]

Thanks to att for –4!

Try it online!

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).

Java, 58 45 44 bytes

String f(){return.5<Math.random()?"":1+f();}

Attempt This Online!

-1 thanks to @Kevin Cruijssen

Same strategy as the NodeJS answer. Previous answer did not fit challenge spec, this version turned out to be shorter as well.

MSX-BASIC, 28 bytes

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

Julia 1.0, 22 bytes

!_=.1<rand()&&!show(1)

Try it online!

Cascade, 6 bytes

$/
.x/

Try it online!

Cascade, 6 bytes

\$
.|x

Try it online!

Likely optimal, considering one row has to have width at least 3 for $ to produce distinct random outcomes.

Both programs consist of two random branches from $, one of which returns the codepoint of x, and the other of which prints (the character value of) and returns the return value of (a fresh evaluation of) the $.

Thue, 20 bytes

x::=xx
x::=~x
::=
x

Try it online! (I'm not sure why the final blank line is necessary, but the program doesn't output anything if I delete it.)

Explanation

Thue starts with an initial string and executes rewriting rules nondeterministically until it cannot execute any more, at which point it halts. This program consists of two rules:

x::=xx

Replace an x in the string with xx.

x::=~x

Delete an x from the string and output x.

The program's starting string is:

x

Thus, at each stage of execution, the string consists of one or more xs; it can either get longer by one x, or get shorter by one x and output an x. Once all the xs have been output, the program halts. This occurs with probability 1, although in practice sometimes the interpreter segfaults.

Haskell, 56 bytes

import System.Random
main=print 1>>randomIO>>=([main]!!)

Try it online!

Random improvements applied to AZTECCO's answer. Halts by non-recoverable error, so it needs to be a full program. Prints at least once, but has \$\frac{1}{2^{64}}\$ chance of continuing to print. (The return type of randomIO is inferred to be Int, which is a signed 64-bit integer in TIO's environment.)

Haskell, 59 bytes

import System.Random
f=do print 1;n<-randomIO;mapM_ id[f|n]

Try it online!

A function that terminates gracefully and has 1/2 chance of continuing. [f|n] becomes [f] or [] with 1/2 chance each, and mapM_ id (one byte shorter than sequence_) runs all monads in the list sequentially. Deleting _ results in a type inference error.

MathGolf, 4 3 bytes

⌂v▲

Pushes * with a probability of \$\frac{4\text{,}294\text{,}967\text{,}294}{4\text{,}294\text{,}967\text{,}295}\$ (99.999999999767%) each iteration, and won't include the empty output (so will always output at least one *).

Don't try it online.

Previous 4 byter:

⌂v¶▼

Pushes * with a probability of \$\frac{837\text{,}973\text{,}946}{858\text{,}993\text{,}459}\$ (~97.55%) each iteration, and won't include the empty output (so will always output at least one *).

Try it online.

Explanation:

  ▲   # Do while falsey with pop:
⌂     #  Push character '*'
 v    #  Push a random integer in the range [-2³¹, 2³¹)
      #  (only 0 is a falsey integer in MathGolf)
      # (after which the entire joined stack is output implicitly as result)
   ▼  # Do while truthy with pop:
⌂     #  Push character '*'
 v    #  Push a random integer in the range [-2³¹, 2³¹)
  ¶   #  Pop and check if this integer is a (positive) prime number
      # (after which the entire joined stack is output implicitly as result)

The mentioned probability is basically the amount of non-prime numbers within the range \$[-2^{31},2^{31})\$ (which is \$4\text{,}189\text{,}869\text{,}730\$ according to WolframAlpha) as numerator and total amount of integers within the range \$[-2^{31},2^{31})\$ (basically \$2^{32}-1=4\text{,}294\text{,}967\text{,}295\$) as denominator (and then simplified by dividing both by their greatest common divisor \$5\$).

R, 20 bytes

while(rexp(1))cat(1)

Try it online!

3 bytes longer than Giuseppe's R answer, but can output unary values greater than 2147483647.

In fact, it will nearly always output unary values that are significantly greater than 2147483647, since the chance of stopping after any outputted 1 character is about 1e-324 (the lower limit of R's double-precision numeric type, below which values are truncated to zero).
This will also nearly always exceed the output limit on TIO, so here is a link using a modified version of the rexp function with only 1 decimal place of precision.

Pure Bash (no external utilities), 30 26

for((;RANDOM;));{ echo x;}

Try it online!

Alchemist, 14 bytes

_->Out__+_
_->

Try it online!

Breaks the loop with probability \$\frac12\$ at each iteration.

Explanation

The program starts with a single _ atom. Since both instructions consume only a _ atom, they are both satisfied and one is chosen randomly. The first outputs the number of _ atoms remaining (0) and produces another _ atom to continue the loop. The second just consumes the atom, ending the loop.

Brachylog, 7 bytes

9w9ṙ9|↰

Try it online!

Explanation

9w         Write 9
  9ṙ       Pick a random integer in 0..9
    9      If it is 9, terminate
     |↰    Else, recurse

Batch, 28 bytes

@if %random% gtr 9 echo x&%0

Outputs an average of about 3276 xs, assuming CMD.EXE doesn't stack overflow first.

05AB1E, 5 bytes

[?₄Ω#

Outputs 0s with a probability of \$\frac{3}{4}\$ each time. Could be a probability of \$\frac{2}{3}\$ or \$\frac{1}{2}\$ for the same byte-count by replacing the with т or T respectively.

Try it online.

Explanation:

[      # Loop indefinitely:
 ?     #  Print an empty string without newline in the first iteration,
       #  or the 0 that was previously on the stack in other iterations
  ₄    #  Push 1000 (or 100 for `т` or 10 for `T`)
   Ω   #  Pop and push a random digit from this integer
    #  #  If it's 1: stop the infinite loop

J, 10 9 bytes

1#~>.@%?0

-1 byte by using Reflex ~ instead of Bond &1

Try it online!

Haskell, 75 70 bytes

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

Try it online!

><>, 3 bytes

x7n

Terminates on an error once x sends the IP left.

Try it online!

4 bytes:
x7
n

Try it online!

This will terminate with an error when n has been executed more times than 7, which has probability 1 of eventually occurring, thought there is no upper limit on how many times 7 will be executed first.

Pari/GP, 43 bytes

setrand(getwalltime)
while(random,print(1))

(Don't) Try it online! This version is very likely to time out on TIO; here's a slightly longer version that produces nicer results: Try it online!

Explanation

setrand(getwalltime)

Seed the random number generator with getwalltime, which is "time in ms since UNIX Epoch."

while(random,print(1))

While a random integer in the range \$[0,2^{31})\$ is not equal to zero, print 1 with a trailing newline.

Vyxal 2.4.1, 6 bytes

{×₴₀℅|

Try it Online!

We use v2.4.1 because it seems in 2.6 and later there's no way to get a random bit in two bytes.

{      # Forever...
 ×₴    # Print an asterisk
     | # While...
   ₀℅  # A random bit is nonzero

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.

Excel, 19 17 bytes

=REPT(1,1/RAND())

-2 bytes excluding 0 length string

Link to Spreadsheet

Factor + random.c, 26 25 21 bytes

[ 1 . rand 9 > ] loop

Try it online!

This uses similar logic as flipping a coin until it lands on tails. Only you're using a severely weighted coin, so you usually get heads, leading to fairly long runs. rand is C's rand() function, returning an integer between 0 and 2147483647 (probably, though it doesn't matter). Each iteration of the loop, print 1 followed by a newline. If the output of rand is greater than 9, perform another iteration; otherwise, end the program.

Pip, 4 bytes

1X/r

Outputs one or more 1s (usually not very many of them). Attempt This Online!

Explanation

   r  Random number in [0, 1)
  /   Invert
1X    Repeat 1 that many times

Theoretically, I think it's possible for this to output nothing if r returns exactly 0, but that's within the rules anyway.

MATLAB, 28 25 bytes

while rand<.5 disp(1),end

Outputs "1" a random number of times, with newline in between. Each length l of has half the probability of length l-1.

Thanks @Luis Mendo for the 3 bytes!

MATL, 5 bytes

`1rEk

Outputs 1 separated by newlines n times, where n is a (shifted) geometric random variable with parameter 1/2. This means n is 1,2,3... with probability 1/2,1/4, 1/8 ... The program halts with probability 1.

Try it online!

`     % Do...while
  1   %   Push 1
  r   %   Push uniform random number in the interval (0,1)
  E   %   Multiply by 2
  k   %   Round down. This gives 0 or 1 with probability 1/2
      % End (implicit). The top of the stack is used as loop condition
      % If 1 a new iteration is executed, otherwise the loop is exited
      % Display stack (implicit)

C (gcc), 29 bytes

f(){putchar(63)&rand()&&f();}

Try it online!

R, 19 17 bytes

strrep(1,rexp(1))

Try it online!

Samples from an \$Exp(1)\$ distribution to determine the length. This allows any positive real number to be generated, which strrep truncates, though most of them will be rather small.

Jelly,  7  6 bytes

2ȮX$’¿

A niladic Link that prints 2s as a side-effect (it also yields 1). Only prints strictly positive numbers (as allowed in the specification).

Try it online! (The footer suppresses the printing of 1 that a full program would otherwise do implicitly.)
Or see forty at once (plus a single trailing newline).

How?

2ȮX$Ḋ¿ - Link: no arguments
2      - two - let's call this V
     ¿ - while...
    ’  - ...condition: decrement V (V=2 -> 1 (truthy); V=1 -> 0 (falsey))
   $   - ...do: last two links as a monad - f(V):
 Ȯ     -   print V, yield V
  X    -   random integer in [1,V] -> next V = 1 or 2 (probability = 0.5)

Previous @ 7 bytes:

2XȮß$Ị¡

A niladic Link that prints 1s as a side-effect (it also yields 2). This one includes the empty output (i.e. zero).

Try it online! (The footer suppresses the printing of 2 that a full program would otherwise do implicitly.)

Charcoal, 4 bytes

W‽φx

Try it online! Link is to verbose version of code. Prints an average of 999 xs. (Other average counts from 1 to 9 are also possible by substituting an appropriate character for φ.)