23
\$\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 alternative between the two, ad nauseum.

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\$
  • 1
    \$\begingroup\$ You can lose the {} braces, but that's about as concise as you can make it. \$\endgroup\$ – Michael Dec 7 '12 at 16:23
  • \$\begingroup\$ This is cool. What font can be used to get a similar image? \$\endgroup\$ – daniero Dec 9 '12 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 '13 at 13:31
  • \$\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 '18 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\$ – Geza Kerecsenyi Jul 20 at 18:51

45 Answers 45

9
\$\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\$
18
\$\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\$
  • \$\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 '13 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 '13 at 17:54
15
\$\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\$
  • \$\begingroup\$ This image does the grey dot optical illusion!! \$\endgroup\$ – Magic Octopus Urn Feb 2 '18 at 20:33
8
\$\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\$
  • \$\begingroup\$ I think this is not random, though, since this is brainfuck. \$\endgroup\$ – Erik the Outgolfer Oct 4 '16 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 '16 at 16:22
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\$
5
\$\begingroup\$

Common Lisp, 33

(loop(princ(elt"/\\"(random 2))))
\$\endgroup\$
3
\$\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\$
3
\$\begingroup\$

ruby, 27 23 chars

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

$><< is 'print to stdout'.

\$\endgroup\$
  • 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 '12 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\$
  • \$\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 '12 at 5:14
3
\$\begingroup\$

Common Lisp - 68

(defun s(l)(elt l(random(length l))))(loop do(format t"~a"(s"/\\")))
\$\endgroup\$
  • \$\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 '16 at 13:13
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\$
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\$
  • \$\begingroup\$ I was just proposing a different 7 byte Befunge-98 solution on Jo King's answer. But this approach looks neater. \$\endgroup\$ – James Holderness Nov 28 '17 at 23:29
3
\$\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 Mistah Figgins)

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\$
  • 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\$ – MildlyMilquetoast Nov 28 '17 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\$ – MildlyMilquetoast Nov 28 '17 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\$ – James Holderness Nov 28 '17 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\$ – James Holderness Nov 28 '17 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\$ – James Holderness Nov 28 '17 at 23:44
2
\$\begingroup\$

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

while(1) { echo ['/', '\\'][rand(0, 1)]; }
\$\endgroup\$
  • \$\begingroup\$ Never even thought of that, thanks! \$\endgroup\$ – Judy Dec 7 '12 at 16:29
  • 1
    \$\begingroup\$ Actually PHP supports subscripts for strings: while(1)echo'/\\'[rand(0,1)];. \$\endgroup\$ – manatwork Oct 4 '16 at 13:06
2
\$\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\$
  • \$\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 '13 at 11:55
  • \$\begingroup\$ Python3: import random while 1:print(random.choice('/\\'),end='') \$\endgroup\$ – Ivo Jan 10 '13 at 12:02
  • \$\begingroup\$ @Ivo, Thanks, I forgot about choice! You can keep py3, though. ;) \$\endgroup\$ – boothby Jan 12 '13 at 4:49
  • \$\begingroup\$ If you reverse your string, you do not have to escape the backslash, thus saving a byte. \$\endgroup\$ – Jonathan Frech Nov 28 '17 at 22:51
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\$

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\$
  • \$\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 '18 at 13:18
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\$
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\$
  • 1
    \$\begingroup\$ Java. 60. Bytes. Wow. \$\endgroup\$ – Erik the Outgolfer Oct 4 '16 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\$ – Kevin Cruijssen Oct 4 '16 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\$ – Erik the Outgolfer Oct 4 '16 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\$ – Kevin Cruijssen Oct 4 '16 at 14:02
  • 1
    \$\begingroup\$ 53 bytes by switching to System.out.write and replacing '/' with 47 \$\endgroup\$ – Benjamin Urquhart Jul 21 at 21:55
2
\$\begingroup\$

JavaScript (Node.js), 59 55 54 bytes

Original Answer

while(1){process.stdout.write(Math.random()>=0.5?"/":"\\")}

-4 bytes thanks to manatwork

while(1)process.stdout.write(Math.random()<.5?"/":"\\")

-1 byte thanks to Conor O'Brien

for(;;)process.stdout.write(Math.random()<.5?"/":"\\")
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! \$\endgroup\$ – caird coinheringaahing Mar 21 '18 at 20:30
  • \$\begingroup\$ No need for braces around a single instruction block; in JavaScript the 0 integer part can be left out; reverse the conditional to use single character operator: while(1)process.stdout.write(Math.random()<.5?"/":"\\"). \$\endgroup\$ – manatwork Mar 21 '18 at 20:32
  • \$\begingroup\$ @manatwork Thanks! Updated. \$\endgroup\$ – 1024x2 Mar 22 '18 at 15:17
  • \$\begingroup\$ You can also write for(;;) instead of while(1) \$\endgroup\$ – Conor O'Brien Mar 22 '18 at 15:19
  • \$\begingroup\$ Thank you as well. Added. \$\endgroup\$ – 1024x2 Mar 22 '18 at 15:41
1
\$\begingroup\$

I guess you can use recursion.

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

I guess you can use recursion.

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

...
\$\endgroup\$
  • \$\begingroup\$ stack space is not infinite. \$\endgroup\$ – codaddict Dec 7 '12 at 16:25
  • \$\begingroup\$ @codaddict so it will timeout. \$\endgroup\$ – Neal Dec 7 '12 at 16:26
  • \$\begingroup\$ Assuming a considerably high timeout your snippet is not equivalent to the OP's. \$\endgroup\$ – codaddict Dec 7 '12 at 16:31
  • 1
    \$\begingroup\$ @codaddict lol the OPs times out as well. it is an infinite loop! \$\endgroup\$ – Neal Dec 7 '12 at 16:31
  • 1
    \$\begingroup\$ Yours would create a run time error before the timeout. \$\endgroup\$ – codaddict Dec 7 '12 at 16:33
1
\$\begingroup\$

chopped off one character:

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

then remove the curly braces:

while(1) echo chr(2+45*rand(1,2));

another trick, with the same length:

while(1) echo chr(rand()%2*45+47);
\$\endgroup\$
  • 1
    \$\begingroup\$ Due to the algorithm it employs, rand()%2 will result in an alternation of 0s and 1s. Not incredibly random. You'd need to use rand(0,1) or mt_rand()%2 instead. \$\endgroup\$ – primo Dec 8 '12 at 15:06
1
\$\begingroup\$

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)

\$\endgroup\$
1
\$\begingroup\$

Powershell, 37 bytes

for(){Write-Host(Random("\","/"))-N}

unfortunately there seem to be no shorter aliases for Write-Host that don't cause a new line after every char.

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

Fission, 12 bytes

[#"\"R
W\"/"

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 23 bytes

loop {<\ />.pick.print}
  • loop loops forever.
  • <\ /> is a list of the strings \ and /.
  • .pick picks one of the two strings randomly.
  • .print prints that random string.
\$\endgroup\$
  • \$\begingroup\$ instead of loop, you can use xx* \$\endgroup\$ – Jo King Jul 20 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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