35
\$\begingroup\$

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:

enter image description here

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

\$\endgroup\$
6
  • 1
    \$\begingroup\$ You can lose the {} braces, but that's about as concise as you can make it. \$\endgroup\$
    – Michael
    Dec 7, 2012 at 16:23
  • \$\begingroup\$ This is cool. What font can be used to get a similar image? \$\endgroup\$
    – daniero
    Dec 9, 2012 at 19:24
  • 1
    \$\begingroup\$ This (picture) reminds me of the first "program" I ever wrote on my commodore 64 straight out of the manual :) ah happy days \$\endgroup\$
    – Dale
    Apr 9, 2013 at 13:31
  • 1
    \$\begingroup\$ @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 \$\endgroup\$
    – nickford
    Mar 5, 2018 at 20:49
  • \$\begingroup\$ What a strange coincidence that this Code Golf repo on Github happens to have the exact same challenge... github.com/noops-challenge/golfbot \$\endgroup\$ Jul 20, 2019 at 18:51

61 Answers 61

22
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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) \$\endgroup\$
    – Leigh
    Jan 9, 2013 at 17:16
  • \$\begingroup\$ @Leigh Due to its implementation, rand()%2 will alternate between zero and one. mt_rand()%2 would work, however. \$\endgroup\$
    – primo
    Jan 9, 2013 at 17:54
  • 1
    \$\begingroup\$ Ðis is really nice. Bring back þorn! \$\endgroup\$
    – Qaziquza
    Sep 29, 2022 at 22:59
20
\$\begingroup\$

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]

blue maze

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This image does the grey dot optical illusion!! \$\endgroup\$ Feb 2, 2018 at 20:33
11
\$\begingroup\$

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;
\$\endgroup\$
11
\$\begingroup\$

Brainfuck - 534

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

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

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ I think this is not random, though, since this is brainfuck. \$\endgroup\$ Oct 4, 2016 at 13:43
  • \$\begingroup\$ 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. \$\endgroup\$
    – captncraig
    Oct 4, 2016 at 16:22
6
\$\begingroup\$

Befunge, 12 9 8 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.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Nov 28, 2017 at 22:40
  • \$\begingroup\$ 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. \$\endgroup\$ Nov 28, 2017 at 22:41
  • \$\begingroup\$ @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. \$\endgroup\$ Nov 28, 2017 at 23:13
  • \$\begingroup\$ @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! \$\endgroup\$ Nov 28, 2017 at 23:21
  • 2
    \$\begingroup\$ @JoKing Just realised you can actually do better with three quotes! ?\","/" Only downside it it'll overflow the stack much faster I think. \$\endgroup\$ Nov 28, 2017 at 23:44
5
\$\begingroup\$

C, 39 chars (38 on MSVC)

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

enter image description here See it run.

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));}
\$\endgroup\$
0
5
\$\begingroup\$

Common Lisp, 33

(loop(princ(elt"/\\"(random 2))))
\$\endgroup\$
5
\$\begingroup\$

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.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I forgot ß can loop infinitely -_- \$\endgroup\$
    – Razetime
    Mar 15, 2021 at 9:26
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Vyxal, 5 bytes

{k/℅₴

No trying it online

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

\$\endgroup\$
4
\$\begingroup\$

C (gcc), 47 bytes

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

Try it online!

\$\endgroup\$
2
  • 3
    \$\begingroup\$ 38 bytes: main(){main(putchar(rand()%2?92:47));} \$\endgroup\$
    – jdt
    Aug 11, 2021 at 12:38
  • \$\begingroup\$ 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! \$\endgroup\$
    – M Virts
    Aug 13, 2021 at 3:22
4
\$\begingroup\$

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!

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

ruby, 27 23 chars

loop{$><<"/\\"[rand 2]}

$><< is 'print to stdout'.

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

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.

\$\endgroup\$
3
\$\begingroup\$

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--;
  }
?>
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – primo
    Dec 13, 2012 at 5:14
3
\$\begingroup\$

Common Lisp - 68

(defun s(l)(elt l(random(length l))))(loop do(format t"~a"(s"/\\")))
\$\endgroup\$
1
  • \$\begingroup\$ Loop allows both a complex and a simple syntax, the simple one being like a progn, but looping forever. You can drop the do. \$\endgroup\$
    – coredump
    Oct 4, 2016 at 13:13
3
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$
    – Ivo
    Jan 10, 2013 at 11:55
  • \$\begingroup\$ Python3: import random while 1:print(random.choice('/\\'),end='') \$\endgroup\$
    – Ivo
    Jan 10, 2013 at 12:02
  • \$\begingroup\$ @Ivo, Thanks, I forgot about choice! You can keep py3, though. ;) \$\endgroup\$
    – boothby
    Jan 12, 2013 at 4:49
  • \$\begingroup\$ If you reverse your string, you do not have to escape the backslash, thus saving a byte. \$\endgroup\$ Nov 28, 2017 at 22:51
3
\$\begingroup\$

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) 
add   al,'/'     ;finish choosing character 
writec:
int   29h        ;write char in AL 
jmp   init       ;loop endlessly
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ [„/\Ω? is better \$\endgroup\$
    – Fmbalbuena
    Sep 27, 2021 at 15:15
3
\$\begingroup\$

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.

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – primo
    Feb 2, 2018 at 13:18
3
\$\begingroup\$

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%[\\|\/],
\$\endgroup\$
3
\$\begingroup\$

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>

\$\endgroup\$
2
\$\begingroup\$

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

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

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 20 bytes

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

PowerShell, 108 90 86 54 53 37 36 bytes

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

Try it online!

\$\endgroup\$
5
2
\$\begingroup\$

Java 8, 60 59 54 53 bytes

v->{for(;;)System.out.write(Math.random()<.5?47:92);}

-1 byte thanks to @BenjaminUrquhart by replacing print with write, so '/' can be 47.

Explanation:

Try it online (times out after 60 sec).

v->{                     // Method with empty unused parameter and no return-type
  for(;;)                //  Loop indefinitely
    System.out.write(    //   Print:
      Math.random()<.5?  //    If the random decimal value in range [0,1) is below 0.5:
       47                //     Print forward slash
      :                  //    Else:
       92);}             //     Print backward slash
\$\endgroup\$
7
  • 1
    \$\begingroup\$ Java. 60. Bytes. Wow. \$\endgroup\$ Oct 4, 2016 at 13:50
  • \$\begingroup\$ @EriktheGolfer Hehe. I hadn't even noticed I'm about average in byte-count. Usually I'm just assuming Java is one of the highest byte-counts, only slightly competeable with BrainFuck or C# sometimes. xD (PS: I even golfed it to 59 :P) \$\endgroup\$ Oct 4, 2016 at 13:58
  • \$\begingroup\$ You are not average, you have a too small byte count (assuming Java, not that too small isn't good). But, at least, this isn't JAVA 8, where I think it's longer... \$\endgroup\$ Oct 4, 2016 at 14:00
  • \$\begingroup\$ @EriktheGolfer Hmm, isn't Java 8 shorter with c->{for(;;)System.out.print(Math.random()<.5?'/':92);} (54 bytes) Or did you mean Java 7 is longer than Java 8? In that case you are indeed correct. \$\endgroup\$ Oct 4, 2016 at 14:02
  • 1
    \$\begingroup\$ 53 bytes by switching to System.out.write and replacing '/' with 47 \$\endgroup\$ Jul 21, 2019 at 21:55
2
\$\begingroup\$

Cubix, 10 bytes

Du\'^>o$/;

Watch it run

    D u
    \ '
^ > o $ / ; . .
. . . . . . . .
    . .
    . .

Was an interesting one to do as i haven't played with the random direction generator much.

  • ^D redirect to the random direction pointer

Directed north

  • o\> loops around the cube, print empty stack and redirecting back into the print commands (stack is empty)

Directed west

  • ^ redirected back into the random direction pointer

Directed south

  • \'/> reflected to the east, push / onto the stack and redirect into the print commands

Directed east

  • u'\> uturn to the right, push \ onto the stack and redirect into the print commands

Print commands

  • o$/;^ output top of stack, skip over the reflect, pop from the stack and redirect into the random direction pointer
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.