大きなスラッシュXを描く


21

負でない整数を指定すると、Xその大きさのが出力されます。Xはinputの出力であり0、各方向に入力に等しいスラッシュを追加してX、より大きな入力用に拡張します。

テストケース

0

X

1

\ /
 X
/ \

2

\   /
 \ /
  X
 / \
/   \

...

10

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

ルール

出力を印刷するか、関数から文字列または文字列のリストを返すことができます。末尾の改行と、出現に影響しない余分な内部空白が許可されます。

これはなので、バイト単位の最短回答が勝ちです!



6
...炭の1バイトソリューションを待ちます。
リーキー修道女

木炭は、簡単に扱うことができる場合、私は驚かれると思います@LeakyNun X途中で(私はそれを追加した理由の一部)が、人は知っている:D
スティーブン


回答:


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`

短いダン。
ディルナン

:|||||||| ゴルファイニーのために+1
ASCIIのみ

また、スタックベースの言語は基本的に他の言語を常に凌alwaysしているのだろうか?
ASCIIのみ


@Okx * stack-based / tacit
ASCIIのみ

22

木炭、6バイト

PX⁺¹NX

あなたのナンセンスは私を止めていない;)

オンラインでお試しください!


2
TIOのルックス...あなたはそれに本当に大きな数値を入れると面白い
スティーブン・

@StephenSラッピングが原因でのみ。
Okx

ラップされた `\` sのすべてが左揃えになるのは直感的です(スペースがラップされないため)
Stephen

Canvasに少し近づけるために5文字(ポストデートチャレンジ)
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-nx == nの場合は偽:このテストは次の場合にのみ実行されるため x == yの、グリッドの正確な中心に位置していることを意味します。

そして次の決定木:

decision tree

デモ


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ありがとう!オクターブ版も間違いなく投稿する価値があります。私の試みは38バイトです、あなたのものは何ですか?
ルイスメンドー

私は週末ずっとそれについて考えていました、そして、あなたがここで使用しているものより効率的な方法を見つけることができませんでした。したがって、すべてのクレジットはオクターブ版のためにあなたに行くべきです。
ミクサン

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ゴルフ)

2文字(最初c = 47は、スラッシュであり、c + 45動的フィールド幅を持つ、バックスラッシュ)が、次にスワップされます。

フィールド幅はで開始1し、2n、各反復で、第1の幅は1だけインクリメントされ、2つ目は2だけデクリメントされます。

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

アイデアをありがとう!コードを2回呼び出すことができるようにするために、その一部のみを使用しました。
アナトリグ



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\

オンラインでお試しください!

Hexdump:

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こともできます変更することにより、4バイト以上のセーブFuncから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を含む正しいサイズの行列を作成します。次に、我々は乗算、それによって"\\"バックスラッシュがあるバックスラッシュもちろん1回のため、他の場所で対角線に沿ってバックスラッシュと0の行列になり(エスケープバックスラッシュ)、および0です。バックスラッシュ0回私たちは、これを追加する"/"作るために倍の逆をXシェイプ。ほぼすべて完了しました。ただし、どこにも0が残っており、真ん中は"\\" + "/"です。" "for 0"X"forを置き換えることでこれらの2つのことを修正しますa_+_。これは、2つのことの和に一致します(_+_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;}

整数を取り、文字列の配列を返すラムダ式

オンラインでお試しください!

ゴルフをしていない:

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

入力欄を経由してある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.

-6 @LeakyNunおかげバイト追加の改善に-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: /=/ %

一番上の行を作成することから始め、各行を印刷した後、\右に1スペース、/左に1スペースを移動し、それらXが真ん中にあることを確認します。



2

網膜、74バイト

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

オンラインでお試しください!説明:

.+
$* X

を置きますX

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

から開始し、X上向きに作業し、\毎回左に斜めに配置します。また、前回よりも/2つ多くスペースを置きます/

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

から始めて、X下に向かって、/毎回左に斜めに配置します。また、前回よりも\2つ多くスペースを置きます/

m` (\W)$
$1

2つの対角線間のスペースの数は奇数である必要があるため、各行の最後のスペース(元の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(ダイアログ)、25バイト

⎕IO←0多くのシステムでデフォルトである必要があります。

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

オンラインでお試しください!

' \/'[] で文字列にインデックスを付けます

 入力を得る

 2を掛ける

1+ ひとつ追加

 多くの整数より

∘.=⍨ 等式表(すなわち、恒等行列; NW-SE対角線)

() 次の暗黙関数を適用します

   引数

  + プラス

   二度

   水平にミラーリングされた引数(つまり、NE-SW対角線)


2

Bash、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 bytes

Uses -n flag.

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

1

QBIC, 90 bytes

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

How this monstrosity works, is left as an excercise for the reader...

Sample output:

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

1

Visual Basic.Net, 454 450 Bytes

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

not sure whether making a func for writeline will save some bytes thanks to Stephen S for pointing at as ... removal also changed integer into object last edit changed the first one back


You're a brave one :) I believe you can remove all of the as Types, because if you have Option Strict Off, VB.NET acts like a loosely typed language.
Stephen

Currently on Linux mono is anoying
polyglotrealIknow

mono doesn't cares about Option Strict, or at least thats what I think
polyglotrealIknow

Oh it seemed functions != for loops thanks for the golf
polyglotrealIknow

Isn't Option Strict off by default? It is in Visual Studio at least
Stephen

1

05AB1E, 22 bytes

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

Try it online!

Explanation

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

Alternative 22 byte solution

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

1

Pyke, 14 bytes

\XQV.X \   /\/

Try it here!

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

demo

Set n on the first line.

May be I can golf it more using a recursive approach


1

R, 75 72 bytes

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

Inspired by this answer, generates an implicit matrix and writes it to stdout; reads the size from stdin. It has to build a matrix of space characters and uses sep='' b/c otherwise it has spacing issues.

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

Try it online!

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.