画一个大斜线X


21

给定一个非负整数,打印出X那么大的整数。X是input的输出0,您将在每个方向上添加等于输入的斜线以扩展X较大的输入。

测试用例

0

X

1个

\ /
 X
/ \

2

\   /
 \ /
  X
 / \
/   \

...

10

\                   /
 \                 /
  \               /
   \             /
    \           /
     \         /
      \       /
       \     /
        \   /
         \ /
          X
         / \
        /   \
       /     \
      /       \
     /         \
    /           \
   /             \
  /               \
 /                 \
/                   \

规则

您可以打印输出,或从函数返回字符串或字符串列表。允许尾随换行符以及不影响显示的额外内部空白。

这是,因此最短答案以字节为单位!



6
...我只是要等待1字节的木炭解决方案。
Leaky Nun

@LeakyNun如果木炭可以轻松地X在中间处理(我添加它的部分原因),我会感到惊讶,但谁知道:D
Stephen


Answers:


6

画布,3 个字节

╵\┼

在这里尝试!

木炭答案的一半大小:D

╵    increment the input
 \   create a diagonal that long
  ┼  and quad-palindromize, mirroring what's required, with 1 overlap;
     This overlaps the `/` and `\`, resulting in `X`

那个矮。
dylnan '18

:||||||| 高尔夫运动+1
仅ASCII的

我也想知道基于堆栈的语言是否基本上总是超越其他语言?
–仅ASCII

@仅ASCII的果冻
Okx

@Okx *基于堆栈/默认
仅ASCII的


16

JavaScript(ES6),79个字节

使用递归函数g遍历网格并逐个字符构建输出。

n=>(g=x=>`/\\ X
`[~x?x-y?x+y-w&&2:x-n?1:3:4]+(~y?g(~x--?x:y--&&w):''))(y=w=n*2)

怎么样?

变量xy都2n迭代到-1,其中n是输入。

对于网格中的每个位置(x,y),我们选择以下字符之一:

  • 0: /
  • 1: \
  • 2:空间
  • 3: X
  • 4:换行

使用以下测试:

  • ~x:如果x == -1则为假:我们已经到达行尾。
  • x-y:如果x == y,则为假:我们位于反对角线上。
  • x+y-w:如果x + y == w,则为假:我们位于对角线上。
  • x-n:如果x == n,则为假:因为仅当x == y时才执行此测试,所以这意味着我们位于网格的确切中心。

以及以下决策树:

决策树

演示版


4
这是... JavaScript?老朋友,你怎么了?
roberrrt-s

13

MATL,16字节

'\/X 'iEQXytEP+)

在线尝试!

以输入2为例。此处堆叠显示为上下颠倒,即下部元件是最近推入的元件。

'\/X '  % Push this string
        %   STACK: '\/X '
iEQ     % Input a number, n. Multiply by 2, add 1: gives 2*n+1
        %   STACK: '\/X '
                   5
Xy      % Identity matrix of that size
        %   STACK: '\/X '
                   [1 0 0 0 0;
                    0 1 0 0 0;
                    0 0 1 0 0;
                    0 0 0 1 0;
                    0 0 0 0 1]
tEP     % Duplicate, multiply each entry by 2, flip vertically
        %   STACK: '\/X '
                   [1 0 0 0 0;
                    0 1 0 0 0;
                    0 0 1 0 0;
                    0 0 0 1 0;
                    0 0 0 0 1]
                   [0 0 0 0 2;
                    0 0 0 2 0;
                    0 0 2 0 0;
                    0 2 0 0 0;
                    2 0 0 0 0]
+       % Add the two matrices
        %   STACK: '\/X '
                   [1 0 0 0 2;
                    0 1 0 2 0;
                    0 0 3 0 0;
                    0 2 0 1 0;
                    2 0 0 0 1]
)       % Index into the string. Indexing is 1-based and modular, so 1 picks
        % the first character ('\'), ..., 0 picks the last (space)
        %   STACK: ['\   /';
                    ' \ / ';
                    '  X  ';
                    ' / \ ';
                    '/   \']
        % Implicit display

我想在Octave中做类似的事情,但是您击败了我,而在MATL中它比Octave还要短,所以很棒!
Michthan

@Michthan谢谢!Octave版本肯定也值得发布。我的无能为力是38个字节,您的是什么?
Luis Mendo

我一直在考虑整个周末,找不到比您在这里使用的方法更有效的方法。因此,所有学分都应该归功于八度音阶版本。
Michthan

6

C,108106字节

a;g(n){for(int b=2*n,i=1,c=47;a+=i;b?puts(""):(i=-i,c=92),b-=2*i)printf("%*c%*c",a,b?c+45*i:88,b,b?c:10);}

在线尝试!

(多亏了MD XF,打了−2打高尔夫球)

它以动态字段宽度打印两个字符(首先c = 47是,是斜杠,c + 45是,是反斜杠;然后交换它们)。

字段宽度从1和开始2n,在每次迭代中,第一个宽度增加1,第二个宽度减少2。

当第二个字段的宽度变为0时,它输出'X'一个换行符而不是常规字符,并反转增量方向(i)。将为所有其他行分别打印换行符(puts(""))。


106字节:a,b,i=1,c;g(n){for(b=2*n,c=47;a+=i;b?puts(""):(i=-i,c=92),b-=2*i)printf("%*c%*c",a,b?c+45*i:88,b,b?c:10);} 在线尝试!
MD XF

谢谢你的主意!我只使用了其中一部分来确保可以两次调用该代码。
anatolyg

5

shortC,111字节

s(x){Wx--)R" ")}j;f(x){O;j<x;j++)s(j),P92),s((x-j)*2-1),R"/\n");s(x);R"X\n");Wj--)s(j),P47),s((x-j)*2-1),R"\\\n

根据我的C答案。转换次数:

  • R -> printf(
  • P -> putchar(
  • W -> while(
  • O -> for(
  • 自动插入关闭 ");}

这也将ASCII码用于\/

在线尝试!



5

C,168个 155 150字节

-5感谢Computronium

#define p printf(
s(x){while(x--)p" ");}j;f(x){for(;j<x;j++)s(j),p"\\"),s((x-j)*2-1),p"/\n");s(x);p"X\n");while(j--)s(j),p"/"),s((x-j)*2-1),p"\\\n");}

当然可以打高尔夫球;我在做 在线尝试!

取消高尔夫:

int space(int x)
{
    while (x--)
        putchar(' ');
}

int f(int x)
{
    for (int j = 0; j < x; j++) {
        space(j);
        printf("\\");
        space((x-j)*2-1);
        printf("/\n");
    }

    space(x);
    puts("X");

    while (j--) {
        space(j);
        putchar('/');
        space((x-j)*2-1);
        printf("\\\n");
    }
}

2
你可以通过定义P设为“的printf(”代替“printf的”输5个字符。
Computronium

3

V,21字节

éXÀñ>HÄÒ r\Á/YGpr/$r\

在线尝试!

十六进制转储:

00000000: e958 c0f1 3e48 c4d2 2072 5cc1 2f59 4770  .X..>H.. r\./YGp
00000010: 722f 2472 5c                             r/$r\

说明:

éX                      " Insert an 'X'
  Àñ                    " Arg1 times:
    >H                  "   Add a space to every line.
                        "   Conveniently, this also puts us on the first line
      Ä                 "   Duplicate this line
       Ò                "   And replace the whole line with spaces
         r\             "   Replace the first char with '\'
           Á/           "   Append a '/' char
             Y          "   Yank this line
              G         "   Move to the last line
               p        "   And paste the line we yanked
                r/      "   Replace the first character with a '/'
                  $     "   Move to the end of the line
                   r\   "   And replace the last character with a '\'

本质上,我们有一个X插入,将斜线扩展了n次

但这不是那么简单,因为我们还必须在第一次添加斜杠。如果斜线已经存在,我们可以将斜线扩展为:

>HÄX2pGÙX2p

这将为我们节省6个字节。


3

C#,157 122 120个字节

_=d=>"".PadLeft(d)
a=>{var s=_(a)+"X\n";for(int i=0;++i<=a;)s=$@"{_(a-i)}\{_(i*2-1)}/
{s+_(a-i)}/{_(i*2-1)}\
";return s;}

非高尔夫版本:

 Func<int, string> _ = (d) =>"".PadLeft(d);
        Func<int, string> func = a => {

            var s = _(a) + "X\n";

            for (int i = 0; ++i <= a;) {

                s = $@"{_(a - i)}\{_(i * 2 - 1)}/
{s + _(a - i)}/{_(i * 2 - 1)}\
";

            }
            return s;
        };

1
您可以将其他匿名函数移出第一个匿名函数,然后将其包含为_=d=>new string(' ',d);(请注意,不需要大括号d)。您可以删除for循环周围的花括号。请使用逐字字符串,这样您就不必转义所有反斜杠。如果设置,i=0则可以++i<a+1删除i++
TheLethalCoder

同样,对于逐字字符串,您不需要包括\n实际的换行符就可以了,尽管我不确定是否可以删除for循环中的花括号,您必须尝试一下。
TheLethalCoder

1
在应用了TheLethalCoder的第一个建议后,您也可以替换++i<a+1++i<=a EDIT。您还可以通过将Funcfrom 更改new string(' ',d)"".PadLeft(d)
auhmaan

感谢您的建议,我可以声明@TheLethalCoder这样的2个函数,如果可以的话,这会不会使很多C#高尔夫球变得更短?
LiefdeWen

1
@StefanDelport在某个地方有关于它的元讨论,但就目前而言,我相信只要显示函数名称就可以。在这种情况下_
TheLethalCoder

3

Mathematica,71个字节

(部分受Jenny_mathy的104字节解决方案的启发)

""<>#&/@(#"\\"+Reverse@#"/"&@IdentityMatrix[2#+1]/.{0->" ",a_+_->"X"})&

返回字符串列表。

说明:IdentityMatrix[2#+1]制作一个大小合适的矩阵,对角线为1,其他地方为0。接下来,我们用它乘"\\"(转义反斜线),这使得它与沿对角线反斜线和0别处矩阵,因为当然1次反斜杠反斜杠是0次反斜线为0内容加入到"/"它的反面倍,使X形状。我们几乎完成了,除了到处还有0,中间是"\\" + "/"。我们通过替换" "0"X"来固定这两件事a_+_,这与两件事的任何总和相匹配(_+_应该这样,除非Mathematica出于自身利益太聪明,并且将其解释为2倍_)。最后,""<>#&/@将其转换为字符串列表。


3

Java(OpenJDK 8),135字节

i->{int k=0,j,l=2*i+1;String[]s=new String[l];for(;k<l;k++)for(s[k]="",j=0;j<l;j++)s[k]+=j==k?j==i?"X":"\\":j==l-1-k?"/":" ";return s;}

Lambda表达式,它取整数并返回一个字符串数组

在线尝试!

取消高尔夫:

i->{
    int k=0,j,l=2*i+1;                // Some variables to be used
    String[]s=new String[l];            // Return array (size 2*i+1)
    for(;k<l;k++)                       // For each array entry
        for(s[k]="",j=0;j<l;j++)        // Set each character to 
            s[k]+=j==k?j==i?"X":"\\"    // \ or X if it's the jth character of the jth row
                 :j==l-1-k?"/"          // / if it's the opposite char
                 :" ";                  // else blank
    return s;
}

3

T-SQL,201字节

DECLARE @ INT SELECT @=a FROM t DECLARE @i INT=@
WHILE @>0BEGIN PRINT SPACE(@i-@)+'\'+SPACE(2*@-1)+'/'SET @-=1 END
PRINT SPACE(@i)+'X'WHILE @<@i BEGIN SET @+=1 PRINT SPACE(@i-@)+'/'+SPACE(2*@-1)+'\'END

格式:

DECLARE @ INT 
SELECT @=a FROM t 
DECLARE @i INT=@
WHILE @>0
    BEGIN
        PRINT SPACE(@i-@)+'\'+SPACE(2*@-1)+'/'
        SET @-=1 
    END
PRINT SPACE(@i)+'X'
WHILE @<@i 
    BEGIN 
        SET @+=1 
        PRINT SPACE(@i-@)+'/'+SPACE(2*@-1)+'\'
    END

根据我们的指南,输入是通过命名表t中的a列输入的。


3

红宝石,66字节

递归函数。

f=->x{?X[x]||"\\#{s=' '*(2*x-1)}/
#{f[x-1].gsub /^/,' '}
/#{s}\\"}

在线尝试!

说明

f=->x{                  # Start of recursive function named `f`
      ?X[x]||           # Return 'X' if x==0, otherwise the following:
"\\#{s=' '*(2x-1)}/     #  Top edge of the cross. Save no. of spaces needed
#{f[x-1]                #  Get result of f[x-1]
        .gsub /^/,' '}  #  Regex sub to left-pad every line w/ a space
/#{s}\\"                #  Bottom edge of cross (insert saved no. of spaces)

3

果冻24 17字节

Ḥ‘=þ`µḤ+Uị“/\x ”Y

在线尝试!

怎么运行的

Ḥ‘=þ`µḤ+Uị“/\x ”Y   main link, input a
Ḥ‘                  input doubled and incremented
   þ                Make a table: Apply  
  =                 "equals"/ to      
    `               each element in range(2a+1) cartesian multiplied with itself.
                      eg. For input 1: [1=1,1=2,1=3],[2=1,2=2,2=3],[3=1,3=2,3=3]      
     µ              on this array:
       +            add: 
      Ḥ             double of it to
        U           its reverse (changes south-east to north-west)
         ị“/\x ”    index into the string "/\x " to get the right characters
                Y   join by newlines for the final output.

@LeakyNun表示-6个字节,-1个字节则进行了其他改进



2

批处理,201字节

@echo off
set s= /
for /l %%i in (2,1,%1)do call set s=  %%s%%
set s=\%s%
for /l %%i in (-%1,1,%1)do call:c
exit/b
:c
echo %s%
set s=%s:\ = \%
set s=%s:X =/\%
set s=%s:\/=X %
set s=%s: /=/ %

首先建立顶行,然后在打印每行之后,向右移动\一个空格,/向左移动一次空格,确保它们X在中间。



2

视网膜,74字节

.+
$* X
+`^ ( *).( *)
$1\  $2/¶$&
+`¶ ( *).( *).?$
$&¶$1/  $2\
m` (\W)$
$1

在线尝试!说明:

.+
$* X

放置X

+`^ ( *).( *)
$1\  $2/¶$&

从处开始X,向上工作,\每次将对角线放在左侧。还要比上次/多放置两个空格/

+`¶ ( *).( *).?$
$&¶$1/  $2\

X向下开始,/每次将对角线放在左侧。还要比上次\多放置两个空格/

m` (\W)$
$1

两个对角线之间的空格数必须为奇数,因此将X删除每行的最后空格(原始行除外)。


2

Mathematica,131个字节

(F[x_,y_]:=Table[x<>StringJoin@Table[" ",i]<>y,{i,1,#*2,2}];Column[Join[Reverse@F["\\","/"],{"X"},F["/","\\"]],Alignment->Center])&


Mathematica,104个字节

这是使用网格的另一种方法

(S=DiagonalMatrix[Table["\\",r=2#+1]];Table[S[[r+1-i,0+i]]="/",{i,r}];S[[#+1,#+1]]="X";Grid@S/. 0->" ")&

2

APL(Dyalog),25个字节

要求⎕IO←0在许多系统上是默认设置。

' \/X'[(⊢+2×⌽)∘.=⍨⍳1+2×⎕]

在线尝试!

' \/'[] 索引字符串

 得到输入

 乘以二

1+ 加一

 比许多整数

∘.=⍨ 等价表(即单位矩阵; NW-SE对角线)

(……在其上) 应用以下默认功能

   论点

  + 加

   两次

   水平镜像的参数(即NE-SW对角线)


2

重击,138字节

for i in `seq $1;seq $[$1-1] -1 1`
{ $[a++]
printf "%*c%*s\n" `echo ' '$i $[a>$1?1:2] $[($1-i)*2]' '$[a<$1?1:2]`
}|sed 's/22/X/'|tr 12 /\\

在线尝试!

真的很长,bash会加热'\和/'

少打高尔夫球

 for i in {1..10} {9..1};{
   $[a++];                      #argument as padding, prints 1 for \ and 2 for /
   printf "%*c%*s\n" `echo ' '$i $[a>$1?1:2] $[($1-i)*2]' '$[a<$1?1:2]`;
  }|sed 's/22/X/g' | tr 12 /\\



1

Perl 5,110 +1 = 111字节

使用-n标志。

$x=$_;$,="\n";push@x,$"x($x-$_)."\\".$"x(2*--$_+1)."/"while$_>0;say@x,$"x$x."x";for(reverse@x){y!\\/!/\\!;say}

1

QBIC,90个字节

~b=0|?@X`\[0,:-1|X=space$(a)┘Z=Z+X+@\`+space$((b-a)*2-1)+@/`+X+@┘`]Z=Z+space$(b)+A+_fZ

这种怪兽是如何工作的,留给读者练习。

样本输出:

Command line: 3
\     /
 \   / 
  \ /  
   X
  / \  
 /   \ 
/     \

1

可视Basic.Net454个 450字节

Option Strict Off
module m
sub main(a As String())
dim v=Convert.toInt32(a(0))
for i as Integer=v to 1 step -1
for j as Object=1 to v-i
w(" ")
next
w("\")
for j as Object=1 to i*2-1
w(" ")
next
console.writeline("/")
next
console.writeline(new String(" ",v)&"X")
for i as Object=1 to v
for j as Object=1 to v-i
w(" ")
next
w("/")
for j as Object=1 to i*2-1
w(" ")
next
console.writeline("\")
next
end sub
sub w(s)
console.write(s)
end Sub
end module

不确定是否为func编写函数是否writeline会节省一些字节,这要归功于Stephen S指出as ...删除也将其更改integerobject 最后一个编辑,从而将第一个更改为


您是个勇敢的人:)我相信您可以删除所有的as Types,因为如果拥有Option Strict Off,VB.NET的行为就像是一种松散类型的语言。
斯蒂芬

当前在Linux上的单声道正在困扰
polyglotrealIknow

单声道不关心选项严格,或者至少就是我的想法
polyglotrealIknow

哦,好像是functions != for loops感谢您参加高尔夫
polyglotrealIknow

Option Strict默认情况下不关闭吗?至少在Visual Studio中
斯蒂芬

1

05AB1E,22字节

F'\IN-úR.∞})Âí'Xs)˜.c»

在线尝试!

说明

F                        # for N in [0...input-1] do
 '\                      # push a backslash
   IN-ú                  # prepend input-N spaces
       R                 # reverse
        .∞               # mirror
          }              # end loop
           )             # wrap stack in a list
            Â            # bifurcate
             í           # reverse each item
              'Xs        # push an "X" between the 2 lists on the stack
                 )˜      # wrap in flattened list
                   .c    # pad lines to equal length
                     »   # join on newlines

替代22字节解决方案

F'\N·>ú'/ì})Âí'X¸«ì.c»

1

Pyke,14个字节

\XQV.X \   /\/

在这里尝试!

\X             - "X"
  QV           - repeat input times:
    .X \   /\/ -  surround(^, all=" ", 
                              tl="\", 
                              left=" ",  
                              right=" ",  
                              lower=" ",  
                              tr="/",  
                              br="\",  
                              bl="/")

1

tcl,134

proc P {x s b} {time {puts [format %[incr ::i $x]s%[expr ($::n-$::i)*2+2]s $s $b]} $::n}
P 1 \\ /
puts [format %[incr i]s X]
P -1 / \\

演示

n在第一行。

也许我可以使用递归方法来打高尔夫球


1

R75 72字节

y=diag(b<-2*scan()+1);write(c(" ",'\\','/','X')[y+2*y[,b:1]+1],'',b,,'')

受此答案启发,生成隐式矩阵并将其写入stdout;从标准输入读取大小。它必须建立一个空格字符矩阵,并使用sep=''b / c,否则会出现间距问题。

diag(b)                     # generates a main diagonal of 1, rest 0
2*diag(b)[,b:1]             # the other diagonal is 2
                            # [,b:1] reverses columns
                            # [b:1,] reverses the rows; they're equivalent
diag(b)+2*diag(b)[,b:1]     # sums, so we get 1 for main diagonal
                            # 2 for other diagonal, 3 for center
diag(b)+2*diag(b)[,b:1]+1   # add 1 since R is 1-indexed
                            # the result is indices for the vector
c(' ','\\','/','X')

在线尝试!

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.