23
\$\begingroup\$

Write a program or function that takes in a positive integer N.

When N is 1, output

/\
\/

When N is 2, output

/\/\
\/ /
/ /
\/

When N is 3, output

/\/\/\
\/ / /
/ / /
\/ /
/ /
\/

When N is 4, output

/\/\/\/\
\/ / / /
/ / / /
\/ / /
/ / /
\/ /
/ /
\/

For larger N the pattern continues, a new layer is added every time N is incremented.

  • "Output" means print the slash pattern or return it as a string.
  • A single trailing newline in the output is allowed.
  • Trailing spaces in the output are allowed but leading spaces are not.

The shortest code in bytes wins.

\$\endgroup\$
0

22 Answers 22

10
\$\begingroup\$

Pyth, 25 bytes

j_+t.iJ*R"/ "SQ+L\\J*Q"/\

Try it online: Demonstration or Test Suite

Explanation:

j_+t.iJ*R"/ "SQ+L\\J*Q"/\   implicit: Q = input number
             SQ             create the list [1, 2, ..., Q]
       *R"/ "               repeat "/ " accordingly to this numbers
      J                     assign this list of strings to J
               +L\\J        create a 2nd list, which contains the same strings
                            as in J, just with a "\" prepended
    .i                      interleave these two lists
   t                        remove the first element
                    *Q"/\   repeat the string "/\" Q times
  +                         append it to the list
 _                          reverse it
j                           print each string on a separate line
\$\endgroup\$
10
\$\begingroup\$

CJam, 32 30 29 28 bytes

ri_"/\ /"2/f*)@,\f>+_z..e>N*

Test it here.

I was trying to help Reto golf his CJam answer but ended up with a solution that had nothing to do with his, so I figured I might as well post it myself.

Explanation

This makes use of the symmetry of the output. In particular, the fact that the output is the same as its transpose.

First, we generate the first N+1 lines, but without the left edge:

ri       e# Read input and convert to integer N.
_        e# Duplicate.
"/\ /"2/ e# Push an array with two strings: ["/\" " /"]
f*       e# Repeat each of the two strings N times. That gives the first two rows.
)        e# Detach the second row.
@,       e# Pull up the other copy of N and turn into range [0 1 ... N-1].
\f>      e# For each element i in that range, discard the first i characters of
         e# the second row.
+        e# Add all those lines back to the first row.

Now we've got an array of strings representing the following grid:

/\/\/\/\
 / / / /
/ / / /
 / / /
/ / /

The transpose of that looks like this:

/ / /
\/ / 
/ / /
\/ / 
/ / /
\/ /
/ /
\/

Together, these have all the non-space characters that we need. We can now make use of Dennis's rad tip to combine two ASCII grids into one, by taking the maximum of each corresponding pair of characters. In all positions where the two grids differ, one will have a space (or nothing at all) and the other will have the character we're looking for. When one list in a vectorised operation is longer than the other, the additional elements of the longer list will simply be kept, which is just what we're looking for. In the other cases, the non-space character will always be the maximum of the two characters:

_z   e# Duplicate the grid and transpose it.
..e> e# For each pair of characters in corresponding positions, pick the maximum.
N*   e# Join the lines by linefeed characters.
\$\endgroup\$
7
\$\begingroup\$

Japt, 46 44 41 40 bytes

Uo-U £Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} ·

Try it online!

Ungolfed and explanation

Uo-U mXYZ{Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} qR

The core of the program makes a list of U * 2 items, maps each to one row of the pattern, then joins them with newlines:

Uo-U    // Build an array of all integers in the range [-U, U).
mXYZ{   // Map each item X and index Y in this array with the following function.
 ...
} qR    // Join the resulting array with newlines.

As for the pattern itself, here's how I have broken it up:

/\/\/\/\

\/   / / /
/    / / /
\/   / /
/    / /
\/   /
/    /
\/

As you can see here, this now devolves into three simple patterns. The first one is the easiest, generated with this code:

Y? ... :  // If Y, the current index, is 0,
"/\\"pU   // return the pattern "/\" repeated U*2 times.

Now for the left half. Odd indices should map to \/, and even to /, so we use this code:

"\\/"s  // Otherwise, slice the pattern "\/" at 
Yv)     //  if Y is even, 1; otherwise, 0.

This makes the right half way easier; all we need to do is repeat  / a few times:

" /"p  // Repeat the pattern " /"
U-Y/2  //  floor(U - (Y/2)) times.

Suggestions welcome!

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

GNU Sed, 59

Score includes +2 for '-nr' options to sed.

s|1|/\\|gp
y|/\\| /|
s| |\\|p
:
s|\\(..)|\1|p
s|/ |\\|p
t

Input in unary as per this meta answer.

Test output:

$ sed -nrf slantcake.sed <<< 111
/\/\/\
\/ / /
/ / /
\/ /
/ /
\/
$ 
\$\endgroup\$
3
\$\begingroup\$

Python 2, 80 bytes

n=input()
print"/\\"*n
for i in range(n*2,1,-1):print"\\"*(1-i%2)+"/ "*(i/2+i%2)
\$\endgroup\$
3
\$\begingroup\$

CJam, 36 35 34 bytes

ri_"/\\"*N@,W%{'\'/@" /"*+_N\N}/;;

Try it online

Thanks to @NinjaBearMonkey for pointing out the extra ;.

While this looks relatively inelegant, I tried a couple of other options, and they did not end up any shorter.

Explanation:

ri_     Get input, convert to integer, and copy.
"/\\"   Pattern for first line.
*N      Repeat N times, and add a newline.
@,      Rotate N to top, and create [0 .. N-1] sequence.
W%      Invert sequence to [N-1 .. 0].
{       Loop over counts, creating two lines for each.
  '\      Leading character for first in pair of lines. Rest will be the same
          for both lines.
  '/      First character for repeated part.
  @       Rotate count to top.
  " /"    Repetitive pattern.
  *       Replicate it by count.
  +       Concatenate with '/.
  _       Copy whole thing for use as second in pair of lines.
  N\      Put a newline between the pair of lines.
  N       Add a newline after second line.
}/      End of loop over counts.
;;      Created an extra line, get rid of it.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Now you can just remove one of the last ;s. \$\endgroup\$ Commented Nov 29, 2015 at 18:01
  • \$\begingroup\$ Or replace ;;; with +; \$\endgroup\$
    – GamrCorps
    Commented Nov 29, 2015 at 18:17
2
\$\begingroup\$

Mathematica, 123 122 121 bytes

""<>(#<>"
"&/@Normal@SparseArray[{{i_,j_}/;2∣(i+j)&&i+j<2#+3->"/",{i_,j_}/;i~Min~j<2&&2∣i~Max~j->"\\"},{2#,2#}," "])&

Could probably be golfed further.

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

Java - 141 bytes

Not the shortest of course, but nice to have a Java solution :

String a(int a){String s="";int b=-1,c,e;for(a*=2;++b<a;){for(c=-1;++c<a;)s+=(e=b+c)>a?" ":e%2==0?"/":b==0||c==0?"\\":" ";s+="\n";}return s;}

Ungolfed

String a(int a){
    String s ="";
    int b=-1,c,e;
    for (a*=2;++b < a;){
        for (c = -1 ; ++c < a ;)
            s+= (e=b+c)>a?" ": e%2==0? "/" : b==0||c==0? "\\" : " ";
        s+="\n";
    }
    return s;
}

Input

System.out.println(a(5));

Output

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

Pyth, 30 Bytes

*"/\\"QVr*2Q1+*\\!%N2*s.DN2"/ 

Try it here.

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

JavaScript, 128 125 123 114 bytes

n=>{r='';for(i=0;i<n;i++)r+='/\\';for(j=0;j<2*n-1;j++){r+='\n'+(j%2?'':'\\');for(i=n-j/2;i>0;i--)r+='/ '}return r}

De-golf (also converted to ES5) + demo:

function c(n) {
    r = '';
    for (i = 0; i < n; i++) r += '/\\';
    for (j = 0; j < 2 * n - 1; j++) {
        r += '\n' + (j % 2 ? '' : '\\');
        for (i = n - j / 2; i > 0; i--) r += '/ '
    }
    return r
}

alert(c(prompt()));

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

Ruby, 50 bytes

->n{s='/\\'*n
n.times{|i|puts s,?\\+s='/ '*(n-i)}}

In test program:

f=->n{s='/\\'*n
n.times{|i|puts s,?\\+s='/ '*(n-i)}}
f[gets.to_i]

The loop prints 2 rows for every iteration from i=0 to i=n-1.

The second row is always '\' followed by n-i incidences of '/ '.

The first row is the same as the second row of the previous iteration, but with the '\' missing (so we store this value in s when we print the second row of the previous iteration.)

The only exception is iteration zero, which is handled by initializing s to '/\'*n.

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

Javascript (ES6), 107 104 100 98 97 91 90 bytes

p=>{s=`/\\`.repeat(p++)+`
`;for(i=p;i>2;s+='\\'+o+o)o=`/ `.repeat(--i)+`
`;return s+'\\/'}

First post here!

Used to use Array(len).join(str) but now uses String.repeat(len), similar to Ruby's operator*(str,len).

Ungolfed:

len => {
    var str = `/\\`.repeat(len++) + '\n';

    for (var i = len, mid; i > 2; str += '\\' + mid + mid) {
        mid = `/ `.repeat(--i) + '\n';
    }

    return str + '\\/';
}


Thanks to:
107 => 104 bytes: @insertusernamehere
97 => 90 bytes: @user81655

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You can save 3 bytes: p=>{s=Array(++p).join('/\\')+'\n';for(i=p;i>2;i--,s+='\\'+o+o)o=Array(i).join('/ ')+'\n';return s+'\\/'}. \$\endgroup\$ Commented Nov 29, 2015 at 19:49
  • \$\begingroup\$ I deleted my answer since it was so similar but was posted after yours. \$\endgroup\$
    – user81655
    Commented Nov 30, 2015 at 2:16
  • \$\begingroup\$ @user81655 Ah, sorry about that. Thank you for showing me the repeat method. \$\endgroup\$
    – rgajrawala
    Commented Nov 30, 2015 at 2:20
1
\$\begingroup\$

Python 2, 66 bytes

n=input();b=1
print'/\\'*n
while~-n+b:print'\\'*b+'/ '*n;b^=1;n-=b

Pretty straightforward. The value n is the number of / on the line, and b says whether the line starts with \. The value of b alternates between 0 and 1, and n decreases every second step. The ugly termination condition stops when n=1, b=0. The alternative of an exec loop would have the issue of needing lots of escapes for "'\\\\'".

I was surprised to find this approach shorter than using a single number k=2*n+b. This is 68 bytes:

k=2*input()+1
print k/2*"/\\"
while k>2:print k%2*'\\'+k/2*'/ ';k-=1

An alternative strategy would avoid a separate print for the top line, but I didn't see a concise way.

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

Minkolang 0.14, 46 bytes

I'm sure this could be golfed, but it's 4 am here and I need to go to bed.

n$z"/\"z$D$OlOz[" /"zi-$Dlr$d"\"zi1+-3&5$X$O].

Try it here.

Explanation

n$z               Take number from input (n) and store it in the register (z)
   "/\"           Push these characters (in reverse)
       z$D        Push register value and duplicate the whole stack that many times
          $O      Output whole stack as characters
            lO    Output newline

z                                   Push n from register
 [                                  Open for loop that repeats n times
  " /"                              Push these characters (in reverse)
      zi-                           n - loop counter
         $D                         Pop k and duplicate whole stack k times
           l                        Push 10 (for newline)
            r                       Reverse stack
             $d                     Duplicate whole stack
               "\"                  Push this character
                  zi1+-             0 if n = loop counter + 1, truthy otherwise
                       3&           Do the next three characters if top of stack is 0
                         5$X        Dump the bottom-most five items of the stack
                            $O      Output whole stack as characters
                              ].    Close for loop and stop
\$\endgroup\$
1
\$\begingroup\$

Batch, 121 bytes

@echo off
set/an=%1-1
if %1==1 (echo /\%2) else call %0 %n% /\%2
set a=/\%2
echo \%a:\= %
if not \%2==\ echo %a:\= %

Or if unary is acceptable, 107 bytes:

@echo off
set a=%1
echo %a:1=/\%
:a
echo \%a:1=/ %
set a=%a:~1%
if not %a%1==1 echo / %a:1=/ %&goto a

Invoke with the appropriate number of 1s.

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

Vyxal, 27 bytes

`/\\`*,ɾṘƛ\/*fṄ;:ƛ\\p;$YṪ⁋,

Try it Online!

`/\\`                       # '/\'
     *,                     # Input times
       ɾṘ                   # n...1
         ƛ     ;            # Map...
          \/*               # That many slashes
             fṄ             # Joined by spaces
                :           # Duplicate
                 ƛ\\p;      # Prepend a backslash to each
                      $Y    # Swap and interleave
                        Ṫ   # Cut off last
                         ⁋, # Joined by newlines
\$\endgroup\$
0
\$\begingroup\$

Matlab, 122 bytes

M=2*input('');
z=zeros(M);[y,x]=ndgrid(1:M);
z(~mod(x+y,2)&x+y<M+3)=1;v=2-mod(1:M,2);
z(1,:)=v;z(:,1)=v;disp([15*z.^2+32,''])
\$\endgroup\$
0
\$\begingroup\$

Haskell, 99 bytes

Two solutions of equal length.

Call f.

f n=mapM_ putStrLn$[[x?y|x<-[0..2*n-y-0^y]]|y<-[0..2*n-1]]
x?y|mod(x+y)2==0='/'|x*y==0='\\'|0<1=' '

and

f n=mapM_ putStrLn$[[x?y|x<-[y..2*n-0^y]]|y<-[0..2*n-1]]
x?y|mod x 2==0='/'|mod y x==0='\\'|0<1=' '
\$\endgroup\$
0
\$\begingroup\$

Haskell, 96

f=g.(*2)
g m=unlines$t m(c"/\\"):[t n l|(n,l)<-zip[m,m-1..2]$c['\\':p,p]]
p=c"/ "
c=cycle
t=take

This is not actually competitive against the existing Haskell solution because it saves 5 characters by returning instead of printing a string. I am posting it only to show how the infinite pattern approach compares to the coordinate-based approach. Notes:

  • p can be inlined for no change in length.
  • [t n l|(n,l)<-...] saves 2 over (map(uncurry t)$...).
\$\endgroup\$
0
\$\begingroup\$

Ceylon, 100

String s(Integer n)=>"\n".join{"/\\".repeat(n),for(i in 2*n+1..3)"\\".repeat(i%2)+"/ ".repeat(i/2)};

This features an "named argument list" for join (without any named arguments, but an iterable comprehension instead), and several uses String.repeat (one of which actually means "include only for odd i").

Formatted:

String s(Integer n) =>
        "\n".join{
            "/\\".repeat(n),
            for (i in 2*n + 1 .. 3)
                "\\".repeat(i % 2)
                        + "/ ".repeat(i / 2)
        };
\$\endgroup\$
0
\$\begingroup\$

PHP, 117 bytes

<?$n=$argv[1];$r=str_repeat;echo$r("/\\",$n);for(;$i++<$n*2-1;)echo"\n".($i%2?"\\":'').$r("/ ",$n-floor(($i-1)/2));?>

Assumes notices are turned off and input is taken from command line.

Ungolfed:

<?php
error_reporting(E_ALL & ~E_NOTICE);

$n = $argv[1];
$r='str_repeat';
echo $r("/\\",$n);
for(;$i++<$n*2-1;){
    echo"\n".(($i%2)?"\\":'') . $r("/ ",$n-floor(($i-1)/2));
}
?>

Comments are welcome :)

\$\endgroup\$
0
\$\begingroup\$

Japt -R, 24 bytes

õç'/ú2)cÈ·p'\+XÃÅÔiUç"/\

Try it

\$\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.