制作一个尖尖的盒子


31

给定两个正整数W和H,输出一个ASCII艺术框,其边框由斜杠(/\)组成,顶部和底部边缘带有W“尖峰”,而左侧和右侧边缘则带有H“尖峰”。盒子的内部充满了空间。

一个“尖峰”就是两个斜线一起形成一个箭头形状:

/\    \/

/      \
\      /

因此,输出W = 4, H = 3将是

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

因为顶部有4个尖峰,向上有4个尖峰,底部有4个尖峰,左侧有3个尖峰,右侧有3个尖峰。

以下是一些其他输入/输出对:

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
/\/\/\/\
\      /
/      \
\      /
/      \
\      /
/      \
\      /
/      \
\/\/\/\/

输出中的任何行都不应有前导或尾随空格。可能有一个尾随换行符。

以字节为单位的最短代码获胜。


可以使用JavaScript的人为此添加一个代码段吗?
FantaC

Answers:


15

木炭,9字节

BײNײN/\

在线尝试!

说明

B           Box
  ײN       Next input as number * 2
      ײN   Next input as number * 2
          /\ With border "/\"

3
当然,木炭有一个内置的“抽水箱”

1
@苯幸运的是,他最近添加了在框周围绘制任意字符串的功能,但即使在此之前,也有诸如codegolf.stackexchange.com/a/120065的
Neil

1
@Neil最近等吗?什么时候?(我知道木炭不好吗,谢谢吗?哈哈)
ASCII码,仅ASCII

@ ASCII-only我不好!由于更改了光标位置,我感到困惑。(引入了任意边界字符串的更改大约是一年前的ca904b0。)
Neil

@苯没有内置框,它仍然只有13个字节:(F²«↷P…\/N»‖M¬以高度,宽度顺序输入)。
尼尔

11

MATL,18字节

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

MATL在线上尝试一下

说明

考虑输入W = 4H = 3。该代码构建行向量[1 2 3 4 5 6 7 8](范围从12*W)和[1 2 3 4 5 6](范围从12*H)。转换后者并通过广播将其添加到前者中,得出矩阵

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

字符串中的模块化索引\/在矩阵边界中产生了所需的结果:

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

要删除非边界值,我们将它们设置为0(当解释为char时,它显示为空格):

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

注释代码:

'\/'    % Push this string. Will be indexed into
,       % Do twice
  i     %   Input a number
  E     %   Multiply by 2
  :     %   Range 
]       % End
!       % Transpose
+       % Add
)       % 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


7

Haskell90 88 87 82字节

1由于Lynn节省了6个字节

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

在线尝试!

感觉还很长,我拭目以待。


定义a#b=[a..b]和替换所有事件将节省一个字节:a#b=[a..b];x!y|i<-2#x>>" "=(1#x>>"/\\"):(2#y>>['\\':i++"/",'/':i++"\\"])++[1#x>>"\\/"]
Lynn

哦,a#b=[1..a]>>b;x!y|i<-(x-1)#" "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"]实际上可以节省
Lynn

@琳恩谢谢!您最近真的很懒惰。
小麦巫师

@Lynn我让它工作了,但是又花了一个字节。
小麦巫师

5

05AB1E,14个字节

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

在线尝试!

说明

„/\|∍`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

这只会创建左上角,宽x个字符,高y个字符。然后在两个轴上镜像:

x=3, y=2

/\/|
\  |
---+

4

JavaScript(ES6),84个字节

以currying语法接受输入(w)(h)

w=>h=>'/\\'[R='repeat'](w)+`
${`\\${p='  '[R](w-1)}/
/${p}\\
`[R](h-1)}`+'\\/'[R](w)

演示版


3

雨燕 3,166字节

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))}

完整的测试套件。

不幸的是,闭包版本更长(175字节):

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)}

具有封闭版本的测试套件。


3

视网膜77 73字节

\d+
$*
 1+|1(?=1* (1+))
$1¶
1
/\
.((..)*.)
/$1¶$1/
¶$

(?<=¶.+).(?=.+¶)
 

在线尝试!链接包括测试用例。接受格式为的输入<height> <width>。说明:

\d+
$*

将输入转换为一元。

 1+|1(?=1* (1+))
$1¶

将输入相乘,但添加换行符,使结果为矩形。

1
/\

创建尖顶。

.((..)*.)
/$1¶$1/

复制每个尖刺行,但尖峰在第二行偏移。

¶$

删除尾随换行符。

(?<=¶.+).(?=.+¶)
 

删除框的内部。(请注意最后一行上的空格。)


3

Excel, 95 bytes

=REPT("/\",A1)&"
"&REPT("\"&REPT(" ",2*A1-2)&"/
/"&REPT(" ",2*A1-2)&"\
",B1-1)&REPT("\/",A1)

3

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

 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.


3

C (gcc), 170 166 158 155 108 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


1
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);}
cleblanc

@cleblanc Thanks!
scottinet

3

///, 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.
Esolanging Fruit

Also, I should mention that this is very impressive! Good job!
Esolanging Fruit

2

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!



If you want to keep it in Python 3, *(b-1) can be *~-b, for -2 bytes.
Mr. Xcoder

2
@officialaimm Why " "*2*~-a? Just "__"*~-a.
tsh

@tsh Yes, you are right... Haha didn't realize that...
officialaimm

@officialaimm will keep it Python 3, did however save some bytes due to you, Mr.Xcoder and tsh
Halvard Hummel

2

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!


1
33 bytes ' '(<,~<<0 _1)}'\/'{~=/&(2|i.)&+:. Amend is great here.
miles

ooooh, very nice improvement
Jonah

1
30 bytes '/\ '{~2(<,~<<0 _1)}2|+/&i.&+: with some refactoring
miles



2

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


2

SOGL V0.12, 22 21 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
ASCII-only

@ASCII-only because charcoal has a built-in for this :p (and SOGLs really made for complicated & long challenges anyway)
dzaima

1

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





1

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

@Jonah No, your idea is much better using amend. If combined with half of mine...
miles

1

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
Taylor Scott

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
Taylor Scott

1

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

The s function is what you call to make the spikey box
Mark

1
Got it. You can get down to 152 bytes if you remove whitespace and the s= bit. Anonymous functions are allowed.
BLT

Good to know anon functions are allowed
Mark

0

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!


1
Currently the longest answer here. I thought that was Java's job...
R. Kap

Don't worry, there's now a Java solution, and it's longer.
Jakob

0

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~#
Jonathan Frech

I know infix notation and I always use it when I really need 1 byte.In this case I just let it go... ;-)
J42161217

2
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.
Jonathan Frech


0

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));

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.