37
\$\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
    Commented Dec 7, 2012 at 16:23
  • \$\begingroup\$ This is cool. What font can be used to get a similar image? \$\endgroup\$
    – daniero
    Commented Dec 9, 2012 at 19:24
  • 2
    \$\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
    Commented 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
    Commented Mar 5, 2018 at 20:49
  • 1
    \$\begingroup\$ It's a general pro tip: for(;;) is always shorter than a while \$\endgroup\$
    – Kaddath
    Commented Jul 13, 2021 at 15:49

75 Answers 75

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\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented Oct 4, 2016 at 14:02
  • 1
    \$\begingroup\$ 53 bytes by switching to System.out.write and replacing '/' with 47 \$\endgroup\$ Commented 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\$
2
\$\begingroup\$

Python, 61 bytes

from random import*
while 1:print('/\\'[randint(0,1)],end='')

Pretty self explanatory. Had to use the double backslash since backslashes are escape characters in Python.

Try it Online!

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

R, 33

Just interested to see whether this can be made smaller.

while(1)cat(sample(c('/','\\'),1))
\$\endgroup\$
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\$
5
  • \$\begingroup\$ Welcome to the site! \$\endgroup\$ Commented Mar 21, 2018 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
    Commented Mar 21, 2018 at 20:32
  • \$\begingroup\$ @manatwork Thanks! Updated. \$\endgroup\$
    – 1024x2
    Commented Mar 22, 2018 at 15:17
  • \$\begingroup\$ You can also write for(;;) instead of while(1) \$\endgroup\$ Commented Mar 22, 2018 at 15:19
  • \$\begingroup\$ Thank you as well. Added. \$\endgroup\$
    – 1024x2
    Commented Mar 22, 2018 at 15:41
2
\$\begingroup\$

BRASCA, 13 12 bytes

1[`/\`1?#$o]

Try it online!

Explanation

1[         ]  - While 1:
  `/\`       -   Push \ and /
      1?      -   Push rand(0,1)
        #$    -   If truthy, swap the top two items, else skip.
          o   -   Print it!

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

Add++, 19 bytes

D,f,,"\/"BX
Dx,$f,o

Try it online!

How it works

D,f,,    ; Define a function, f
    "\/" ; Push "\/"
    BX   ; Random choice

Dx,      ; Do, while x:
   $f,   ; Set x to the result of f
   o     ; Output with no newline
\$\endgroup\$
2
\$\begingroup\$

Python 3, 52 51 bytes

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

Try it online!

Saves at least 9 bytes over other python solutions here.

Edit: saved a byte via ayreguitar's comment

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice use of end! But as @Jonathan Frech pointed out in the first Python entry, no need to escape the \ if you reverse the order, saving 1 byte: while 1:print(end=choice('\/')) \$\endgroup\$
    – ayreguitar
    Commented Jul 2, 2022 at 21:50
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\$
7
  • \$\begingroup\$ stack space is not infinite. \$\endgroup\$
    – codaddict
    Commented Dec 7, 2012 at 16:25
  • \$\begingroup\$ @codaddict so it will timeout. \$\endgroup\$
    – Naftali
    Commented Dec 7, 2012 at 16:26
  • \$\begingroup\$ Assuming a considerably high timeout your snippet is not equivalent to the OP's. \$\endgroup\$
    – codaddict
    Commented Dec 7, 2012 at 16:31
  • 1
    \$\begingroup\$ @codaddict lol the OPs times out as well. it is an infinite loop! \$\endgroup\$
    – Naftali
    Commented Dec 7, 2012 at 16:31
  • 1
    \$\begingroup\$ Yours would create a run time error before the timeout. \$\endgroup\$
    – codaddict
    Commented Dec 7, 2012 at 16:33
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\$

Fission, 12 bytes

[#"\"R
W\"/"

Try it online!

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

Tcl, 53 bytes

while 1 {puts -nonewline [expr rand()<.5?"/":"\\\\"]}

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\$
1
  • \$\begingroup\$ instead of loop, you can use xx* \$\endgroup\$
    – Jo King
    Commented Jul 20, 2019 at 13:16
1
\$\begingroup\$

Pyth - 12 9 bytes

#@,\/\\O2

Tested without loop code because the online interpreter dislikes infinite loops

Explanation:

#@,\/\\O2
#             Repeat until Error
 @            Implicitly print item number
       O2     random number between zero and two exclusive
  ,           of two item list containing
   \/         One character string /
     \\       One character string \
\$\endgroup\$
1
\$\begingroup\$

Add++, 24 bytes

+1
W,R2,-1,*45,+47,H,x:1

Try it online!

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

q/kdb+, 18 bytes

Solution:

while[1;1"\\/"1?2]

Explanation:

A simple while(true) loop...

while[1;1"\\/"1?2] / the solution
while[1;         ] / while true do ...
              1?2  / 1 choose 2 (0 or 1)
         "\\/"     / string \/, index in at 0 or 1
        1          / print to stdout without newline

Extras:

Another 18 byte solution: {1"\\/"1?2}\[::;1]

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

MathGolf, 8 bytes

1Æû\/wq∟

Try it online!

Explanation

1          push 1
 Æ     ∟   do-while-true without popping using 5 operators
  û\/      push "\/"
     w     random char from string
      q    print without newline

Implicit popping doesn't seem to be working as intended when using do-while-true, or any other loop type. With this working correctly, the first 1 could be removed.

For a "working" 7-byter, you could do t{û\/wq, which replaces the do-while-true with a simple for loop, and begins the script by pushing the current timestamp in milliseconds to the stack. Currently, that means about \$1.56*10^{12}\$ iterations, which is "infinite" for most applications. However, this is not a valid answer, so the official answer is still 8 bytes.

\$\endgroup\$
1
+100
\$\begingroup\$

APL (Dyalog Unicode), 12 bytes

→≢⍞←'/\'[?2]

Try it online!

Tradfn body that prints indefinitely.

Thanks to @Adám for 5 bytes, and for pointing out that, with a little bit of CSS magic, TIO can print the actual pattern like in the image.

How:

→≢⍞←'/\'[?2] ⍝ Tradfn body
         ?2  ⍝ Roll (randomly select) an integer between 1 and 2
        [  ] ⍝ Use the result to index...
    '/\'     ⍝ ...the string containing the two slashes
  ⍞←         ⍝ Print it to the same line
 ≢           ⍝ Tally the result (yields 1)
→            ⍝ then 'goto' that line
\$\endgroup\$
5
  • \$\begingroup\$ This is eligible for 200 rep, no? \$\endgroup\$
    – Adám
    Commented Jul 24, 2019 at 20:18
  • \$\begingroup\$ @Adám is it? I've no idea why it would. \$\endgroup\$
    – J. Sallé
    Commented Jul 24, 2019 at 20:37
  • \$\begingroup\$ This. \$\endgroup\$
    – Adám
    Commented Jul 24, 2019 at 20:38
  • 1
    \$\begingroup\$ Oh, I see. I guess it is, then? There were no answers in any APL flavour before mine, and it meets all the conditions in the post. I'll add my request to it. \$\endgroup\$
    – J. Sallé
    Commented Jul 24, 2019 at 20:49
  • \$\begingroup\$ Cool, and feel free to dig up any of your posts from since February. I have way too much rep. \$\endgroup\$
    – Adám
    Commented Jul 24, 2019 at 20:51
1
\$\begingroup\$

Runic Enchantments, 13 bytes

`/-R`A*+k$!;

Try it online!

Slightly ungolfed for readability, with spaces to separate operational segments:

'/  2'RA  '- *+k $ !;

The difference of 45 is encoded in the - char literal, as chars are implicitly converted to integers when fed into a operator expecting a number value.

2'RA randomly generates a 0 or a 1, multiplied against the - and added to the / char resulting in either / or \, which is then printed after being coerced back to a char from an int. In the golfed version the  (0x02) serves as the 2.

Then the program loops forever by skipping the terminator, !;.

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

><>, 12 bytes

x!\"/!
^o< <

Try it online!

The idea here is to use x in combination with the ^ below to both loop and choose a random horizontal direction. If the IP goes left from the x, it will skip the mirror / and quote the string "\!x!/", reflect upwards with \, wrapping around to the <, which redirects the IP to output the result and begin the loop again. If the IP goes right from the x, a similar thing will happen.

This is all thanks to the nice happenstance that / and \ are control flow modifiers in ><>, allowing us to save a ".

An alternative solution for 13 bytes is slightly more generic and generates a lot fewer side effects.

xa!o"/\"o!a
^

(You can replace the as with spaces; I have them placed here for clarity. In production code, you would want to do this replacement to avoid unnecessary stack population.)

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

Clojure, 34 bytes

(loop[](pr(rand-nth"\\/"))(recur))
\$\endgroup\$
1
\$\begingroup\$

Zsh, 42 bytes

for ((;;))printf ${(#)$((RANDOM%2?47:92))}

try it online

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

AppleSoft BASIC, 33 bytes

33 bytes, verified here

1?MID$("\/",RND(1)+1.5,1);:GOTO1

35 bytes, using CHR$ conversion similar to C64.

1?chr$(47+45*int(2*rnd(1)));:goto1
\$\endgroup\$
1
\$\begingroup\$

Factor + qw, 33 bytes

[ qw{ / \ } random write t ] loop

Try it online!

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

Lua 5.4, 49 bytes

::a::io.write(2>math.random(2)and"\\"or"/")goto a

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ also 49 bytes: ::a::io.write(({"\\","/"})[math.random(2)])goto a \$\endgroup\$
    – c--
    Commented Apr 29, 2023 at 23:35
1
\$\begingroup\$

Yabasic, 27 bytes

-1 byte thanks to @ayreguitar

Mid$("\/",...) is used over Chr$() as the character codes for / and \ are 47 and 92, respectively.

While the GoTo structure of the original could easily be used for this answer, Do...Loop ends up being shorter due to the the structure of the Mid$ call.

Do?Mid$("\/",Ran(3),1);Loop

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I don't know Yabasic, but from the TIO link you can save a byte by using "\/" instead of "/\\", like you can in Python (and I guess this works in some other languages) \$\endgroup\$
    – ayreguitar
    Commented Aug 29, 2022 at 20:45
1
\$\begingroup\$

Rust, 143 bytes, std only

use std::hash::*;fn main(){loop{print!("{}",b"/\\"[std::collections::hash_map::RandomState::new().build_hasher().finish()as usize%2]as char);}}

Attempt This Online!

This mess is because the Rust stdlib (at the time of writing) has no "proper" RNG API. So, I had to use the workaround described here to get a random number.

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

Go, 78 bytes (fixed seed)

package main
import."math/rand"
func main(){for{print(string(`/\`[Intn(2)]))}}

Attempt This Online!

Prints to STDERR.

Random seed, 107 bytes

package main
import(."math/rand";."time")
func main(){Seed(Now().Unix())
for{print(string(`/\`[Intn(2)]))}}

Attempt This Online!

Also prints to STDERR.

\$\endgroup\$

Your Answer

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

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