| Bytes | Lang | Time | Link |
|---|---|---|---|
| 040 | ShellScript jot + mawk | 240130T053602Z | RARE Kpo |
| 033 | Awk | 240131T024807Z | camelCas |
| 016 | Perl 5 | 220328T035811Z | Xcali |
| 029 | JavaScript Node.js | 220301T115337Z | l4m2 |
| 022 | Yabasic | 240130T172610Z | Taylor R |
| 020 | VBA | 240130T173017Z | Taylor R |
| 007 | Volatile | 230908T205433Z | bluswimm |
| 004 | Befunge93 | 230724T203214Z | Joe |
| 008 | Ly | 230723T081747Z | cnamejj |
| 031 | Fish | 230722T063636Z | The Zip |
| 030 | Racket | 230721T182307Z | Ed The & |
| 017 | Thue | 230721T163247Z | Dadsdy |
| 005 | Thunno 2 | 230714T083111Z | The Thon |
| 050 | Python 3 | 220301T150559Z | solid.py |
| 017 | Alice | 220713T222408Z | Julian |
| 020 | APL | 220713T050002Z | Vadim Tu |
| 005 | Jelly | 220713T232900Z | ais523 |
| 048 | Nim | 220418T062949Z | Qaziquza |
| 010 | TIBasic TI84 | 220304T002137Z | MarcMush |
| 020 | Emmental | 220412T040239Z | Ohentis |
| 076 | C 76 Bytes | 220328T022952Z | user1117 |
| 022 | x86 32bit machine code Linux | 220315T190750Z | user3604 |
| 074 | PHP | 220305T210734Z | LucianDe |
| 031 | Bash | 220305T030315Z | sinvec |
| 019 | Zsh | 220302T092423Z | pxeger |
| 041 | Python 3 | 220302T193112Z | Amir rez |
| nan | C++ | 220304T030557Z | oeuf |
| 006 | Random Brainfuck | 220302T150208Z | Conor O& |
| 024 | Wolfram Language Mathematica | 220301T211944Z | Roman |
| 023 | INTERCAL | 220303T183704Z | Unrelate |
| 044 | Java | 220301T171936Z | Seggan |
| 028 | MSXBASIC | 220303T140516Z | Konamima |
| 022 | Julia 1.0 | 220303T125433Z | MarcMush |
| 006 | Cascade | 220303T064001Z | Unrelate |
| 020 | Thue | 220303T000827Z | DLosc |
| 056 | Haskell | 220302T233119Z | Bubbler |
| 003 | MathGolf | 220302T143615Z | Kevin Cr |
| 020 | R | 220302T160157Z | Dominic |
| 026 | Pure Bash no external utilities | 220301T175937Z | Digital |
| 014 | Alchemist | 220302T154403Z | Nitrodon |
| 007 | Brachylog | 220302T144456Z | Fatalize |
| 028 | Batch | 220302T110835Z | Neil |
| 005 | 05AB1E | 220302T080223Z | Kevin Cr |
| 009 | J | 220301T131248Z | sinvec |
| 070 | Haskell | 220301T211515Z | AZTECCO |
| 003 | ><> | 220301T204902Z | je je |
| 043 | Pari/GP | 220301T185744Z | DLosc |
| 006 | Vyxal 2.4.1 | 220301T190258Z | emanresu |
| 006 | Retina | 220301T124451Z | Neil |
| 017 | Excel | 220301T155001Z | Axuary |
| 021 | Factor + random.c | 220301T172552Z | chunes |
| 004 | Pip | 220301T180837Z | DLosc |
| 025 | MATLAB | 220301T140623Z | Groger |
| 005 | MATL | 220301T162012Z | Luis Men |
| 029 | C gcc | 220301T154719Z | AZTECCO |
| 017 | R | 220301T131525Z | Giuseppe |
| 006 | Jelly | 220301T122312Z | Jonathan |
| 004 | Charcoal | 220301T123717Z | Neil |
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"}
It is possible for awk's rand() to return 0, but very unlikely.
Thanks to Marius_Couet for the byte!
JavaScript (Node.js), 29 bytes by noodle man
_=>''.padEnd(1/Math.random())
JavaScript (Node.js), 30 bytes
f=_=>Math.random()>.5?'':1+f()
Simple
Yabasic, 22 bytes
Function that outputs a sequence of newline literals of random length.
While(ran()>.5):?:Wend
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
?@#.
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
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))
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))
Thunno 2, 5 bytes
(¢TLɼ
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*
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
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ĿȮ
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
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.
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";}
PHP, 52 bytes
while(0<$r=rand(0,9)){echo str_repeat('p',$r)."\n";}
Zsh, 19 bytes
grep -oam1 x /*/ur*
Explanation:
/*/ur*: glob for/dev/urandom, an infinite stream of random bytesgrep x: search for the letterx-o: print only the letterxs-a: force output even though/dev/urandomis a binary file-m1: quit after the first matching line
Pure Zsh, 20 bytes
for ((;RANDOM;))<<<x
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: printx
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
Python 3, 62 60 59 45 43 41 bytes
import os
while os.urandom(1)[0]:print(1)
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;}}
Random Brainfuck, 7 6 bytes
-1 byte thanks to je je's observation that Null bytes are accebtale as output.
+[>.?]
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
INTERCAL, 23 bytes
DOREADOUT#0DO%9TRYAGAIN
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();}
-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
RNDwith a negative value gets the first value from the pseudo-random sequence whose seed is the passed value.TIMEis a system 16 bit variable that increases continuously (and goes back to 0 on overflow) at 50 or 60Hz.?is a convenient shortcut forPRINT.
Cascade, 6 bytes
$/
.x/
Cascade, 6 bytes
\$
.|x
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]!!)
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]
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 *).
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)
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.
Alchemist, 14 bytes
_->Out__+_
_->
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|↰
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.
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
Haskell, 75 70 bytes
import System.Random
f=do n<-randomIO;putStr"x";if n then pure()else f
- Saved 5 thanks to @pxeger suggestions to use pure instead of return and semicolons;
><>, 3 bytes
x7n
Terminates on an error once x sends the IP left.
x7
n
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
{×₴₀℅|
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.
Factor + random.c, 26 25 21 bytes
[ 1 . rand 9 > ] loop
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.
` % 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)
R, 19 17 bytes
strrep(1,rexp(1))
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 φ.)