# Make a Spiky Box

Given two positive integers, W and H, output an ASCII-art box whose border is made of slashes (/ and \) with W "spikes" on the top and bottom edges, and H "spikes" on the left and right edges. The box's interior is filled with spaces.

A "spike" is simply two slashes coming together to form an arrow shape:

/\    \/

/      \
\      /


So the output for W = 4, H = 3 would be

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


as there are 4 spikes on the top pointing up, 4 on the bottom pointing down, 3 on the left pointing left, and 3 on the right pointing right.

Here are some other input/output pairs:

W H
[spiky slash box]

1 1
/\
\/

1 2
/\
\/
/\
\/

2 1
/\/\
\/\/

2 2
/\/\
\  /
/  \
\/\/

1 3
/\
\/
/\
\/
/\
\/

3 1
/\/\/\
\/\/\/

2 3
/\/\
\  /
/  \
\  /
/  \
\/\/

3 2
/\/\/\
\    /
/    \
\/\/\/

10 1
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/

10 2
/\/\/\/\/\/\/\/\/\/\
\                  /
/                  \
\/\/\/\/\/\/\/\/\/\/

4 5
/\/\/\/\
\      /
/      \
\      /
/      \
\      /
/      \
\      /
/      \
\/\/\/\/


No lines in the output should have leading or trailing spaces. There may optionally be one trailing newline.

The shortest code in bytes wins.

• Can someone who javascripts make a stack snippet for this? Dec 23, 2017 at 20:17

# Charcoal, 9 bytes

Ｂ×²Ｎ×²Ｎ/\


Try it online!

### Explanation

Ｂ           Box
×²Ｎ       Next input as number * 2
×²Ｎ   Next input as number * 2
/\ With border "/\"

• Of course Charcoal has a built-in for 'draw box' Aug 10, 2017 at 4:24
• @benzene It was somewhat fortunate that he recently added the ability to draw an arbitrary string around the box, but even before then there were answers such as codegolf.stackexchange.com/a/120065
– Neil
Aug 10, 2017 at 7:37
• @Neil wait recently? When? (Do I know Charcoal less well thank you do? Haha) Aug 10, 2017 at 9:26
• @ASCII-only My bad! I got confused because of the change that regressed the cursor positioning. (The change that introduced the arbitrary border string was ca904b0 which was almost a year ago.)
– Neil
Aug 10, 2017 at 16:45
• @benzene Without the box builtin it's still only 13 bytes: Ｆ²«↷Ｐ…\/Ｎ»‖Ｍ¬ (takes input in height, width order).
– Neil
Aug 11, 2017 at 12:53

# MATL, 18 bytes

'\/',iE:]!+)O6Lt&(


Try it at MATL Online!

### Explanation

Consider inputs W = 4, H = 3. The code builds the row vectors [1 2 3 4 5 6 7 8] (range from 1 to 2*W) and [1 2 3 4 5 6] (range from 1 to 2*H). Transposing the latter and adding to the former with broadcast gives the matrix

2  3  4  5  6  7  8  9
3  4  5  6  7  8  9 10
4  5  6  7  8  9 10 11
5  6  7  8  9 10 11 12
6  7  8  9 10 11 12 13
7  8  9 10 11 12 13 14


Modular indexing into the string \/ produces the desired result in the matrix border:

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


To remove the non-border values, we set them to 0 (when interpreted as char it is displayed as space):

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


Commented code:

'\/'    % Push this string. Will be indexed into
,       % Do twice
i     %   Input a number
E     %   Multiply by 2
:     %   Range
]       % End
!       % Transpose
)       % Index
O       % Push 0
6L      % Push [2 -1+1j]. As an index, this means 2:end
t       % Duplicate
&(      % Write 0 into the center rectangle. Implicit display


# Python 2, 69 68 bytes

-1 thanks to Kevin Cruijssen

lambda w,h:'/\\'*w+'\n'+'\\%s/\n/%s\\\n'%(('  '*~-w,)*2)*~-h+'\\/'*w


Try it online!

• \\%s can become \%s and \\/ can become \/. Feb 9, 2018 at 20:43

1 6 bytes saved thanks to Lynn

a#b=[1..a]>>b
x!y|i<-(x-1)#"  "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"]


Try it online!

Still feels really long, I'll see what I can do.

• Defining a#b=[a..b] and replacing all occurences saves one byte: a#b=[a..b];x!y|i<-2#x>>" "=(1#x>>"/\\"):(2#y>>['\\':i++"/",'/':i++"\\"])++[1#x>>"\\/"]
– Lynn
Aug 10, 2017 at 17:00
• Oh, a#b=[1..a]>>b;x!y|i<-(x-1)#" "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"] actually saves 6~
– Lynn
Aug 10, 2017 at 17:02
• @Lynn Thanks! You've really been catching my slack lately. Aug 10, 2017 at 17:03
• @Lynn I got it to work but at the cost of another byte. Aug 10, 2017 at 17:06

# 05AB1E, 14 bytes

„/\|∍S¦).B∞∊


Try it online!

### Explanation

„/\|∍S¦).B∞∊   Arguments: x, y
„/\              Push the string "/\"
|             Push inputs as array: [x,y]
∍            Push the string extended/shortened to those lengths
           Flatten
S          Push seperate chars of second string
¦        Remove first char and flatten again
)       Wrap stack to an array
.B     Squarify
∞∊   Mirror on both axes


This only creates the top left corner, x characters wide and y characters tall. It then mirrors this on both axes:

x=3, y=2

/\/|
\  |
---+


## JavaScript (ES6), 84 bytes

Takes input in currying syntax (w)(h).

w=>h=>'/\\'[R='repeat'](w)+
${\${p=' '[R](w-1)}/ /{p}\\ [R](h-1)}+'\\/'[R](w)  ### Demo let f = w=>h=>'/\\'[R='repeat'](w)+ {$$/extract_itex]{p=' '[R](w-1)}/ /{p}\\ [R](h-1)}+'\\/'[R](w) function upd() { O.innerHTML = W.value+'x'+H.value+'\n\n'+f(W.value)(H.value) } upd() <input id=W type=range value=5 min=1 max=10 oninput="upd()"> <input id=H type=range value=5 min=1 max=10 oninput="upd()"> <pre id=O> # Swift 3, 166 bytes func f(a:Int,b:Int){let k=String.init(repeating:count:),n="\n";var r="\\"+k(" ",a-1)+"/";print(k("/\\",a)+n+k(r+n+String(r.characters.reversed())+n,b-1)+k("\\/",a))}  Full test suite. The closure version is a bit longer, unfortunately (175 bytes): var g:(Int,Int)->String={let k=String.init(repeating:count:),n="\n";var r="\\"+k(" ",0-1)+"/";return k("/\\",0)+n+k(r+n+String(r.characters.reversed())+n,1-1)+k("\\/",0)}  Test suite with the closure version. # Retina, 77 73 bytes \d+ * 1+|1(?=1* (1+)) 1¶ 1 /\ .((..)*.) /1¶1/ ¶ (?<=¶.+).(?=.+¶)  Try it online! Link includes test cases. Takes input in the format <height> <width>. Explanation: \d+ *  Convert the inputs to unary.  1+|1(?=1* (1+)) 1¶  Multiply the inputs, but add a newline so that the result is a rectangle. 1 /\  Create the spiky top. .((..)*.) /1¶1/  Duplicate each spiky row, but with the spikes offset on the second row. ¶  Delete trailing newlines. (?<=¶.+).(?=.+¶)  Delete the inside of the box. (Note space on last line.) # Excel, 95 bytes =REPT("/\",A1)&" "&REPT("\"&REPT(" ",2*A1-2)&"/ /"&REPT(" ",2*A1-2)&"\ ",B1-1)&REPT("\/",A1)  # APL (Dyalog), 41 39 bytes Prompts for a list of [H,W] '\'@2@1⊢¯1⌽@1{⌽⍉⍵,'/\'⍴⍨≢⍵}⍣4⊢''⍴⍨2×⎕-1  Try it online! ⎕-1 prompt for input (mnemonic: stylized console) and subtract 1 2× multiply by two ''⍴⍨ use that to reshape an empty string (pads with spaces) ⊢ yield that (serves to separate it from 4) {}⍣4 apply the following function four times: ≢⍵ tally (length of) the argument '/\'⍴⍨ cyclically reshape "/\" to that length ⍵, append that to the right side of the argument ⌽⍉ transpose and mirror (i.e. turn 90°) ¯1⌽1 cyclically rotate the 1st row one step to the right ⊢ yield that (serves to separate it from 1) '\'@2@1 put a backslash at the 2nd position of the 1st major item. # C (gcc), 170166158155108 105 -3 bytes thanks to cleblanc x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);}  Try it online! I think this can be golfed further with a less straightforward approach, I'll see what I can do when I find the time. Ok I cannot find any other way to reduce the number of bytes for that code. Explanation: a simple double-loop printing the box char by char. When printing a border: if both x and y coordinates are either even or odd, it displays a /, otherwise, a \ is displayed If not a border, a space character is displayed instead • You can shave off another 3 bytes by moving the puts("") into the first for loop like this x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);} Aug 11, 2017 at 15:57 # ///, 172 117 bytes So, because the output consists of ///s and whitespaces, there should be submissions in those 2 languages. Put the input after the code in W,H as unary number (unary for /// is allowed, thanks to Challenger5 for suggestion) (use * to represent digit, separate with ,) format. /W/VV//V/\\\////\\\\\\\\\\\\\V/,/W>+ V/\>+W !V!WV>+WV- V\ \W+ V/ /W-!V\ W\\V\V>!//!*/+%-%!//*/ //%/ Try it online! (with input W=4, H=3) • You can skip the parsing by taking input in Unary. Sep 19, 2017 at 2:08 • Also, I should mention that this is very impressive! Good job! Sep 19, 2017 at 2:11 # Python 3, 87 82 bytes Edit: Saved 5 bytes thanks to @officialaimm, @Mr.Xcoder and @tsh def f(a,b,n="\n"):r="\\"+" "*~-a+"/";print("/\\"*a+n+(r+n+r[::-1]+n)*~-b+"\\/"*a)  Try it online! • 81 bytes in python 2 after some improvements Aug 10, 2017 at 5:11 • If you want to keep it in Python 3, *(b-1) can be *~-b, for -2 bytes. Aug 10, 2017 at 5:50 • @officialaimm Why " "*2*~-a? Just "__"*~-a. – tsh Aug 10, 2017 at 5:52 • @tsh Yes, you are right... Haha didn't realize that... Aug 10, 2017 at 5:59 • @officialaimm will keep it Python 3, did however save some bytes due to you, Mr.Xcoder and tsh Aug 10, 2017 at 6:25 # J, 48 bytes ' '&((<,~<<0 _1)})@(+:@[(1&|.,:])@('\/'~+:)@])  ## ungolfed ' '&((< ,~ <<0 _1)}) @ (+:@[ (1&|. ,: ])@('\/' ~ +:)@])  ## explanation  (+:@[ (1&|. ,: ])@('\/' ~ +:)@]) creates box, but interior filled with slashes ('\/' ~ +:)@] take right arg, W, doubles it, then fills that @ many characters with '\/' repeating (1&|. ,: ]) stacks (,:) the above on top of itself rotated by one char, producing top and bottom spikes reshape to.. (+:@[ double the length of the left arg, height this creates the sides, as well as a filled interior @ ' '&((< ,~ <<0 _1)}) removes slashes from interior by using the complement form of amend }. ie, replace everything but the first and last row and first and last col with a space  Try it online! • 33 bytes ' '(<,~<<0 _1)}'\/'{~=/&(2|i.)&+:. Amend is great here. Aug 10, 2017 at 15:28 • ooooh, very nice improvement Aug 10, 2017 at 15:34 • 30 bytes '/\ '{~2(<,~<<0 _1)}2|+/&i.&+: with some refactoring Aug 12, 2017 at 20:37 # 05AB1E, 19 bytes 4FNÈi¹}·„\/NÉiR}N·Λ  Try it online! Takes arguments reversed. • Hmm, I smell... Canvas Mode? Aug 10, 2017 at 10:09 # Haskell, 84 79 bytes w%h=[[last"/\\"!!mod(x+y)2:[' '|x>1,y>1,x<2*w,y<2*h]|x<-[1..2*w]]|y<-[1..2*h]]  Try it online! Example usage: 3%6 yields a list of lines. Use mapM putStrLn 3%6 to pretty-print the box. # Java 8, 141 bytes A curried lambda from width to height to output. w->h->{String f="/",b="\\",t=f,o=b,p="";char i=1;for(;i++<w;t+=b+f,o+=f+b)p+=" ";t+=b;o+=f;for(i=10;--h>0;)t+=i+b+p+f+i+f+p+b;return t+i+o;}  Try It Online (no, return t+i+o; was not intentional) ## Ungolfed lambda w -> h -> { String f = "/", b = "\\", t = f, o = b, p = "" ; char i = 1; for (; i++ < w; t += b + f, o += f + b) p += " "; t += b; o += f; for (i = 10; --h > 0; ) t += i + b + p + f + i + f + p + b; return t + i + o; }  This solution is atypically picky about input size since a char is used to count up to the width input. Fortunately, the algorithm is bad enough that at those sizes program completion is probably already an issue. I chose to use char for the loop index so I could reuse it later as a cheap alias for '\n'. # SOGL V0.12, 2221 13 bytes /\”m;HΙ»mč+╬¡  Try it Here! (expects both inputs on stack so .. (and " because a string hasn't been explicitly started) - take number input twice is added for ease-of-use) Explanation: /\” push "/\" m mold to the 1st inputs length ; get the other input ontop of stack H decrease it Ι push the last string - "/\" » rotate it right - convert to "\/" m mold "\/" to the length of 2nd input - 1 č chop into characters + prepend the 1st molded string to the character array of the 2nd ╬¡ quad-palindromize  • >:D it isn't beating Charcoal here Aug 10, 2017 at 9:54 • @ASCII-only because charcoal has a built-in for this :p (and SOGLs really made for complicated & long challenges anyway) Aug 10, 2017 at 10:02 # Mathematica, 87 bytes Table[Which[1<i<2#2&&1<j<2#," ",OddQ[i+j],"\\",1>0,"/"],{i,2#2},{j,2#}]~Riffle~" "<>""&  Try it in Mathics (it prints extra spaces at the start of most lines for some reason), or at the Wolfram sandbox! Takes two integers as input. It's a fairly naïve solution, but all of the clever things I tried had more bytes. Something that nearly works is ArrayPad[Array[" "&,2#-2],1,{{"/",s="\\"},{s,"/"}}]~Riffle~"\n"<>""&  except it fails if either dimension is 1 (input is a list containing the dimensions). # Pyth, 40 39 38 bytes +++*Q"/\\"b*tE+++K++\\*d*2tQ\/b_Kb*"\/  This takes the two integers separated by a newline. Full test suite. # Ruby, 62 61 60 bytes ->r,c{["/\\"*c]+["\\#{w=" "*~-c}/",?/+w+?\$$*~-r+["\\/"*c]}  -1 byte thanks to Arnauld Try it online! # Actually, 38 bytes "/\"*;.R;l¬' *"\/"@j;R(D(╗WD(;.(;.(Wé╜  Try it online! # J, 39 bytes (' \/'{~=/&(2&|)(*>:)~0=*/&(*|.))&i.&+:  Try it online! Takes two arguments as height on the LHS and width on the RHS. • Nice work, as usual. Interesting approach, too. Aug 10, 2017 at 15:18 • @Jonah No, your idea is much better using amend. If combined with half of mine... Aug 10, 2017 at 15:27 # ><>, 180 Bytes 0&0\ a*+>i68*-:0(?v$
/)\^0&1v?)0&~/
? 0 v:$< / \:<-1oo'/\' \~$:@2*0&\
'/'1>&o1->a\ /'/'>o$:2*>1-:1)?\~$&1=?\
'\'0//?(3:o/?/'\'/     \o*48  /      \
/?)0\ &:&1=/;
\  \:~
'/'/\<oo'\'


VBA (Excel) , 161 Bytes

Sub a()
c=[A2]*2
r=[B2]*2
For i=1To r
For j=1To c
b=IIf(i=1 Or j=1 Or i=r Or j=c,IIf((i+j) Mod 2,"\","/")," ")
d=d & b
Next
d=d & vbCr
Next
Debug.Print d
End Sub

• Golfed Sub (139 Bytes): Sub b c=[2*A1] r=[2*B1] For i=1To r For j=1To c Debug.?IIf(i=1Or j=1Or i=r Or j=c,IIf((i + j)Mod 2,"\","/")," "); Next Debug.? Next End Sub Dec 22, 2017 at 19:43
• Anonymous immediate window function version of above (113 Bytes): c=[2*A1]:r=[2*B1]:For i=1To r:For j=1To c:?IIf(i=1Or j=1Or i=r Or j=c,IIf((i + j)Mod 2,"\","/")," ");:Next:?:Next Dec 22, 2017 at 19:44

# R, 160 bytes 152 bytes

p=function(x,n){paste(rep(x,n),collapse='')}
function(w,h){f=p(' ',w*2-2)
cat(paste0(p('/\\',w),'\n',p(paste0('\\',f,'/\n/',f,'\\\n'),h-1),p('\\/',w)))}


Try it online!

Thanks BLT for shaving off 8 bytes.

• Do you ever use the s function?
– BLT
Sep 19, 2017 at 3:17
• The s function is what you call to make the spikey box
– Mark
Sep 19, 2017 at 9:49
• Got it. You can get down to 152 bytes if you remove whitespace and the s= bit. Anonymous functions are allowed.
– BLT
Sep 19, 2017 at 16:20
• Good to know anon functions are allowed
– Mark
Sep 19, 2017 at 16:50

# dc, 123 bytes

?1-sesf[/\]su[lfsh[lunlh1-dsh0<q]dsqx]dsrx[[
\]P[lf2*2-st[32Plt1-dst0<z]dszx]dsmx[/
/]Plmx92Ple1-dse0<l]slle0<l10P[\/]sulrx


It's far from the shortest, but, if one takes the last two lines and rotates them pi/2 radians clockwise to an "upright" position, it kind of looks like a totem pole.

Takes input as two space-separated integers.

Try it online!

• Currently the longest answer here. I thought that was Java's job... Aug 10, 2017 at 6:25
• Don't worry, there's now a Java solution, and it's longer. Aug 11, 2017 at 4:19

# Mathematica, 116 bytes

(c=Column;o=Table;v=""<>o[" ",2*#-2];w=""<>o["/\\",#];c[{w,c@o[c[{"\\"<>v<>"/","/"<>v<>"\\"}],#2-1],Rotate[w,Pi]}])&

• Rotate[w,Pi] is equivalent to w~Rotate~Pi, as is o["/\\",#] to "/\\"~o~# Sep 19, 2017 at 12:58
• I know infix notation and I always use it when I really need 1 byte.In this case I just let it go... ;-) Sep 19, 2017 at 14:11
• I did not doubt your knowledge of infix notation; I just wanted to reduce the byte count. You know, in the spirit of golfing and such. Sep 19, 2017 at 17:05

# V, 18 bytes

Ài/\Ùæ\$Àäkllòjjkè


Answer wouldn't require the ll if <M-h>ollow left 2 char columns alone :(

Try it online!

# C# (.NET Core), 188 bytes

a=>b=>string.Join("\n",new int[2*b].Select((x,i)=>string.Concat(string.Concat(new int[a].Select(y=>i%2==0?"/\\":"\\/")).Select((y,j)=>i>0&i<2*b-1&j>0&j<2*a-1?" ":""+y))))


Byte count also includes:

using System.Linq;


Try it online!

I started making explanation command-by-command but it stopped making sense midway... Basic gist is to make full spiky box, and then hollow out the middle. I used Linq for the sake of using Linq, probably can be shorter using just standard iterations.

Here's explanation going middle-out (the inner-most command first):
First, create rows for the full box, and concatenate to a single string

string.Concat(new int[a].Select(y => i % 2 == 0 ? "/\\" : "\\/"))


Then get each character in a row, and if it isn't the outline of the box, replace with space, concatenate them back into one string for each row

string.Concat(PREVIOUS_STEP.Select((y, j) => i > 0 & i < 2 * b - 1 & j > 0 & j < 2 * a - 1 ? " " : "" + y))


Finally, get each row and concatenate them together with newlines (also includes generating of a collection for rows)

string.Join("\n", new int[2 * b].Select((x, i) => PREVIOUS_STEP));
`