# 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter) Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement: 10 PRINT CHR$(205.5+RND(1)); : GOTO 10


It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

while(1) { echo chr(47 + 45 * rand(0,1)); }


chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

• You can lose the {} braces, but that's about as concise as you can make it. Commented Dec 7, 2012 at 16:23
• This is cool. What font can be used to get a similar image? Commented Dec 9, 2012 at 19:24
• This (picture) reminds me of the first "program" I ever wrote on my commodore 64 straight out of the manual :) ah happy days
– Dale
Commented Apr 9, 2013 at 13:31
• @daniero I think the actual typeface is called Terminal, but I found it online as "Windows Command Prompt" codepen.io/nickforddesign/pen/WMqQdM?editors=0110 Commented Mar 5, 2018 at 20:49
• It's a general pro tip: for(;;) is always shorter than a while Commented Jul 13, 2021 at 15:49

Since this has been migrated to codegolf...

### PHP 30 bytes

<?for(;;)echo rand(0,1)?~Ð:~£;


The Ð is character 208, and the £ is character 163.

Sample usage (on a Windows box):

color 18 & php maze.php


Produces something similar to:

It works best with a monospace font that is exactly square (here I've chosen the standard system font 8x8). To go back to your default color, you can type color again without any parameters.

• Can save an extra byte with rand()%2 (nobody stated how pseudo-random it had to be) - Also doesn't work on Unicode terminals (like OSX) Commented Jan 9, 2013 at 17:16
• @Leigh Due to its implementation, rand()%2 will alternate between zero and one. mt_rand()%2 would work, however. Commented Jan 9, 2013 at 17:54
• Ðis is really nice. Bring back þorn! Commented Sep 29, 2022 at 22:59

# Mathematica 157 bytes

Lacking PETSCII, I rolled my own "\" and "/".

No cigar for brevity here.

Graphics[{Thickness[.005],RGBColor[0.73,0.55,1.],Line/@Flatten[Table[RandomChoice[{{{x,y},{x+1,y+1}},{{x+1,y},{x,y+1}}}],{x,40},{y,25}],1]},Background->Blue]


• This image does the grey dot optical illusion!! Commented Feb 2, 2018 at 20:33

The goto operator was added to PHP from version 5.3.0 so you could use the same method as you would in BASIC:

a: echo chr(47 + 45 * rand(0,1)); goto a;


# Brainfuck - 534

>+[->>>>>>[<<<<<<+>>>>>>-]>[<<<<<<+>>>>>>-]<<<<+++++++[<+++++++++++>-]
<[<<[>>>>>>+<<<+<<<-]>>>[<<<+>>>-]<<[>>>>>+<<<+>+<<<-]>>>[<<<+>>>-]<[>
>>>+[<<<+>+>>-]<<[>>+<<-]+<[>-<[-]]>[>+<-]<<-]<-]++++++[>++++++++<-]>-
[<<[>>>>>+<<<<+<-]>[<+>-]>-]<<<[-]>[-]+++++[<+++++>-]<[>>>>>>>+[<<<<<<
+>+>>>>>-]<<<<<[>>>>>+<<<<<-]+<[>-<[-]]>[>>>>+<<<<-]<<-]++++++[>>>>>>+
++++++++<<<<<<-]>>>>>>[<<<<<<<+>+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]++<[->-
[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<[<<+>+>-]<<[>>+<<-]+>>[-]<[++++[>+
+++<---]>.[-]<<->]<[[>+<+++++]>----.[-]<]>+]


My prng (from here) is both large and extremely slow. Perhaps a simpler LFSR or similar would suffice, but this works:

• I think this is not random, though, since this is brainfuck. Commented Oct 4, 2016 at 13:43
• most of these are relying on built-in prngs. Yeah, this will output the same every time. Could allow it to be seeded from keyboard at cost of a couple extra chars, but thats not really the point here, I think. Commented Oct 4, 2016 at 16:22

# Befunge, 1298 7 Bytes

Edit: James Holderness figured out an insane solution that uses three quotes instead.

?\","/"


Overflows the stack with a lot of excess characters for each symbol, but who cares when you can golf that 1 byte?

### Old version

"/\"?>,#


(Note the trailing space) Trailing space apparently not needed (thanks MercyBeaucou)

Try It Online

"/\" Adds both / and \ to the stack
? Chooses a random direction to go in. Both up and down loop back around to the ? so it's 50% chance to go in either direction.
Going left
"/\"  >,#  Adds \ and / to the stack but only print the second, the / before heading back
Going right
>,# Prints the top of the stack, the \ before heading back


This does start to fill up the stack, with one extra symbol for every symbol printed.

• looks like you can get rid of the extra space, as the # is at the end of a line. It's not consistent behavior, but the interpreter you're using allows it: tio.run/##S0pNK81LT/3/X0k/RsneTkf5/38A Commented Nov 28, 2017 at 22:40
• I also wonder if you are able to use only one ", but my attempts have been futile. Because you need a / on one side of the ", you will have to divide half the time. Commented Nov 28, 2017 at 22:41
• @MistahFiggins Space definitely shouldn't be required for any standard Befunge-93 implementation. The code may fail in some Funge-98 interpreters, where the spec is more ambiguous, but adding a space wouldn't help in those cases anyway - you'd need a < after the # to make it work. Commented Nov 28, 2017 at 23:13
• @MistahFiggins As for getting rid of one of the quotes, you can kind of do that in Befunge-98 by using ' instead. Try it online! Commented Nov 28, 2017 at 23:21
• @JoKing Just realised you can actually do better with three quotes! ?\","/" Only downside it it'll overflow the stack much faster I think. Commented Nov 28, 2017 at 23:44

print has a return value of 1, so if you use that you can just wrap the whole expression in the while:

while(print chr(47 + 45 * rand(0,1));

You can probably golf it further too.

## C, 39 chars (38 on MSVC)

main(){while(putchar(rand()%2?47:92));}


On MSVC, we can replace putchar() with _putch() and save a byte, but it doesn't work in IDEOne.

main(){while(_putch(rand()%2?47:92));}


## Common Lisp, 33

(loop(princ(elt"/\\"(random 2))))


# Jelly, 5 bytes

Ø^XȮß


Try it online!

XØ^ß is a byte shorter, but prints a 0 before the slashes.

  X      Choose a random element from
Ø^       "/\",
Ȯ     print it,
ß    then call this link again.

• I forgot ß can loop infinitely -_- Commented Mar 15, 2021 at 9:26

## Python 3, 59 51 bytes

Using only 1 line (in the spirit of the original 10 PRINT):

from random import*;exec("while 1:print(end=choice('\/'))")

while 1:from random import*;print(end=choice('\/'))


Or (possibly not that random) using hash for just 47 bytes (but on 2 lines):

x=0
while 1:x=hash(str(x));print(end='\/'[x%2])


Try it online!

• Welcome to Code Golf! Nice first answer. Commented Jul 2, 2022 at 22:24
• It's 52 bytes by using __import__ (still on one line) Commented Jul 2, 2022 at 22:25
• @Steffan Great improvement! Also helps slow it down to something more like the original :) Commented Jul 3, 2022 at 7:00
• Here's a 46-byte version of your hash solution that's back to being a one-liner. :) Commented Sep 29, 2022 at 17:16
• @DLosc Brilliant!!! Of course now I'm going to spend far to much time trying to shave another byte off ;) Commented Sep 30, 2022 at 18:10

# Vyxal, 5 bytes

{k/℅₴


No trying it online

It was a smart choice adding all of the two byte constants of 05ab1e and Jelly.

# C (gcc), 47 bytes

main(){while(putchar(47+45*(rand()/(1<<30))));}


Try it online!

• 38 bytes: main(){main(putchar(rand()%2?92:47));}
– jdt
Commented Aug 11, 2021 at 12:38
• Very nice! I have lots to learn golfing c, recursive main seems to be quite handy and rand mod 2 puts my monstrosity to shame! Commented Aug 13, 2021 at 3:22

## ruby, 27 23 chars

loop{$><<"/\\"[rand 2]}  $><< is 'print to stdout'.

• You should be able to replace "/\\" with '\/'. Ruby 1.8 requires [rand(2),1] to produce the character instead of the ascii code. Commented Dec 18, 2012 at 10:22

# C++, 45 Chars

int main(){for(;;)cout<<(rand()%2?"/":"\\");}


Not going to win any awards for shortness, but I had already written this when I heard about the mentioned book, so I just golfed it.

The putchar trick also works in C++, getting you down to 43, but you can't avoid declaring the return type on main.

i try create using css style, and it's work

<style>
body {
font-family: monospace;
line-height:75%;
letter-spacing:-3px;
}
</style>


this php code :

<?php
$i=10000; while($i) {
if($i%200 == 0) echo '<br/>'; echo chr(47 + 45 * rand(0,1));$i--;
}
?>

• I'd like to suggest an alternative style: font-family: courier; line-height: 0.75em; letter-spacing: -0.25em; Using -0.25em for letter-spacing seems to match up better than -3px, which has artifacts due to an inexact pt to px conversion. Commented Dec 13, 2012 at 5:14

# Common Lisp - 68

(defun s(l)(elt l(random(length l))))(loop do(format t"~a"(s"/\\")))

• Loop allows both a complex and a simple syntax, the simple one being like a progn, but looping forever. You can drop the do. Commented Oct 4, 2016 at 13:13

## Python, 68

In the "my language sucks at this" category, we've got Python!

import random,sys
while 1:sys.stdout.write(random.choice('/\\'))


Thanks to Ivo for a few chars on imports and choice.

• Well, you're not saving anything with 'from sys import*' - if you instead write 'import sys,random' and use sys.stdout and random.random, you'll save 5 bytes.
– Ivo
Commented Jan 10, 2013 at 11:55
• Python3: import random while 1:print(random.choice('/\\'),end='')
– Ivo
Commented Jan 10, 2013 at 12:02
• @Ivo, Thanks, I forgot about choice! You can keep py3, though. ;) Commented Jan 12, 2013 at 4:49
• If you reverse your string, you do not have to escape the backslash, thus saving a byte. Commented Nov 28, 2017 at 22:51

## 16-bit x86 assembly code, 10 bytes

I don't remember if this one ended up in the book.

init:
scasb            ;read from where ES:DI points and compare to AL
;this sets flags similar to a subtraction
salc             ;set mask in AL to 00 or FF
and   al,'\'-'/' ;begin choosing character (AL is 00 or 2D)
writec:
int   29h        ;write char in AL
jmp   init       ;loop endlessly

# 05AB1E, 7 bytes

["/\"Ω?


Try it online!

["/\"Ω?  - Full program
[          Start an infinite loop
"/\"      ... Push the string "/\" on the stack
Ω     ... Pick a character from the top of the stack, at random
?    ... Print without a newline

• [„/\Ω? is better Commented Sep 27, 2021 at 15:15

# Befunge-98 (PyFunge), 7 bytes

? '/,\'


Try it online!

the ? sends the IP either left or right, so either / or \ is pushed before printing with ,. When executing the '/ or \' in the wrong order after printing, it just does things to the stack (divides or swaps), and then pushes an irrelevant character before repeating.

• I was just proposing a different 7 byte Befunge-98 solution on Jo King's answer. But this approach looks neater. Commented Nov 28, 2017 at 23:29

# PHP, 26 31 bytes

eight three bytes shorter than yours (without whitespace or braces),
two bytes shorter than primo´s solution (without the tag)
.

PHP 5.4.9 was the current version in December 1012, so ...

for($s="\/";;)echo$s[rand()%2];


requires PHP 5.5 or later for literal string indexing.

Run with -r or try it online.

• PHP 5.5 didn't exist at the time of the challange posting, but have a +1 anyway. Also, try rand()&1 on a PHP build for Windows. You might be surprised. Commented Feb 2, 2018 at 13:18

## Keg, 12 bytes

You do not have to worry about the evenness 0f the output, because the range is 0 to 32767, and 32767+1 = 32768; it is an even number.

{~2%[\\|\/],


# HTML+JS, 186

<pre style="letter-spacing:-3.5px;line-height:9px;;white-space: pre-wrap;line-break: anywhere;" onclick="setInterval(_=>this.innerHTML+='/\\'[2*Math.random()|0])">C l i c k   m e !</pre>

# Uiua, 15 bytes

⍢(&pf⊡⁅⚂"\\/")1


This goes in an infinite loop, so to try this without having your browser hang, first go to the Uiua pad, click the settings icon, and change "Exec limit" to a low number like 0.5 seconds. Then paste this code in and click Run.

Explanation: ⊡⁅⚂"\\/" gets a random number between 0 and 1, rounds it to the nearest integer, and picks either \ or / based on that. &pf prints that character without a newline. ⍢(…)1 is do … while 1.

I've found a couple other 15 byte solutions:

Not much better. Needs php 5.5+ for the array dereferencing feature.

while(1) { echo ['/', '\\'][rand(0, 1)]; }

• Never even thought of that, thanks!
– Judy
Commented Dec 7, 2012 at 16:29
• Actually PHP supports subscripts for strings: while(1)echo'/\\'[rand(0,1)];. Commented Oct 4, 2016 at 13:06
• it means the for version would be the same length than the current shortest PHP answer: for(;;)echo'/\\'[rand(0,1)]; Commented Jul 13, 2021 at 15:55

## Perl

This one looks funny for me :

perl -pe '$_="~"ge$_?"/":"\\"' </dev/urandom


(Sorry to be out of subject here. I know this is not PHP)

# ><>, 14 bytes

I was hoping I could restrict it to a 3*3 square but didn't succeed.

"/\
~x/
o</
!


You can try it here.

# Cubix, 12 bytes

D<^<!"/\"B!o


View in the online interpreter!

This maps out to the following cube net:

    D <
^ <
! " / \ " B ! o
. . . . . . . .
. .
. .


## Explanation

Setup:

The IP begins heading east at the first !. This is the 'skip if truthy' command, which is False when there is nothing on stack, so no commands are skipped. "/\" enters stringmode and appends these two character codes to the stack. B!o is mostly a no-op here, only reversing the stack.

The IP now loops back around to the first !. However, there are now positive integers on stack, so the first " is skipped. This means / is no longer a character, but a mirror, sending the IP north into the main loop.

Main Loop:

The D command is the only source of randomness in Cubix. It sends the IP in a random direction. By blocking off South and East with arrows, we make sure the IP has a 50% chance of heading North, and a 50% chance of heading West.

If it heads West, the stack is reversed. If it heads North, the top character is printed.

This creates the random sequence of slashes, as desired.

# SmileBASIC, 20 bytes

?"/\"[RND(2)];
EXEC.


# PowerShell, 1089086545337 36 bytes

for(){Write-Host "\/"[(Random 2)]-n}


Try it online!

• Welcome to Code Golf. Tips for golfing in PowerShell Commented Jul 20, 2019 at 9:40
• Commented Jul 20, 2019 at 10:50
• for also makes while a bit shorter Commented Jul 20, 2019 at 10:53
• you can more... more precisely, less :) Commented Jul 20, 2019 at 13:44
• and less Commented Jul 20, 2019 at 15:55