ASCIIラダーを作成する


28

2つの整数nおよびmの入力が与えられた場合、長さnおよびサイズmの ASCIIラダーを出力します 。

これは、長さ3およびサイズ3のASCIIラダーです。

o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

これは、長さ5、サイズ1のASCIIラダーです。

o-o
| |
+-+
| |
+-+
| |
+-+
| |
+-+
| |
o-o

これは、長さ2およびサイズ5のASCIIラダーです。

o-----o
|     |
|     |
|     |
|     |
|     |
+-----+
|     |
|     |
|     |
|     |
|     |
o-----o

具体的に:

  • 長さ(n)は、はしごを構成する正方形の数を表します。

  • サイズ(m)は、各正方形の内部の幅と高さ(つまり、「境界線」をカウントしない)を表します。

  • 各正方形は、スペースで満たされた内部領域で構成され-、上下を|sで、左右を+sで、四隅すべてでsで囲まれて います。

  • 正方形間の境界線は一緒にマージされるため、1行に2つの行 +--...--+が1つにマージされます。

  • はしご全体の角がキャラクターに置き換わりoます。

  • オプションで、末尾の改行を出力できます。

はしごの長さ(n)は常に≥2で、サイズ(m)は常に≥1です。

入力は、空白/コンマ区切りの文字列、配列/リスト/など、または2つの関数/コマンドライン/などとして取得できます。引数。引数は、最も便利な/最もゴルフ好きな順番でとることができます。

これはであるため、バイト単位の最短コードが優先されます。

ヒント:上記の例は、テストケースとしても使用できます。


最初に長さを取り、次にサイズを取る必要がありますか?
RK。

@RK。より便利な順序でそれらを取ることができます。
ドアノブ

1
存在でき大手改行は?
コナーオブライエン

1
@CᴏɴᴏʀO'Bʀɪᴇɴうーん...私はその上でノーで行くつもりです。
ドアノブ

1
わかりました:Pそれは一撃の価値がありました。
コナーオブライエン

回答:


4

Pyth、34バイト

.NjjNm*QTvz*2YjC:M++J"+|o"m"- -"QJ

テストスイート

STDINで区切られた改行を引数に取ります。

ヘルパー関数を使用します。:これは、3文字から各タイプの垂直文字列を作成し、必要に応じて複製し、改行で転置および結合します。


11

ルビー、71

->m,n{h=0;(?o+?+*(n-1)+?o).chars{|c|puts [?|+' '*m+?|]*h,c+?-*m+c;h=m}}

テストプログラムに参加していない

f=->m,n{
  h=0                             #The number of | above the 1st rung is 0
  (?o+?+*(n-1)+?o).chars{|c|      #Make a string of all the rung ends o++...++o and iterate through it
    puts [?|+' '*m+?|]*h,         #draw h vertical segments |  ...  |
      c+?-*m+c                    #and a rung with the correct ends
    h=m                           #The number of | above all rungs except the 1st is m
  }
}


f[gets.to_i,gets.to_i]

ゴルフバージョンにはマイナーな問題があるようです:;後で必要、後h=0にスペースが必要putsです。ただし、前に余分なスペースがあるため、スコアは1文字のみで増加しますputs
マナトワーク

@manatworkおっと、ありがとう、修正。私はそれがどのように起こったのか分かりません、私はゴルフをしたに違いありません、そしてその後それを走らせないでください。
レベルリバーセント

9

CJam、43 42バイト

私はスコアにastされていません。しかし、私はデニスではありませんよね?

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$

入力は、スペースで区切られた2つのアイテムです。最初の長さ

2 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

説明

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$
q~                                         e# read input
  :Z;                                      e# Record the size in Z and discard
     '-'o{[\Z*1$N]}:X~                     e# Create the initial line (and final). also creates a shorcut to do this later
           \                               e# Capture two arguments
            Z*                             e# The separator is repeated size times
              1$                           e# Repeat the first argument
                N                          e# Add newline
                                           e# X is a function to create line in a ladder
                      ['-_'+X\'|XZ*]       e# Design the repeating part
                                    @*     e# Repeat the pattern n times
                                      1>   e# Discard the initial
                                        1$ e# Since the final line is same than the initial, we just write it.
                                           e# Implicit printing

1
私はあなたが質問としてそれを言ったことを気に入っています。「私はデニスじゃないよね...」
地下

7

JavaScript(ES6)、89

...繰り返し、繰り返し、繰り返し...

(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

テスト

F=(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

// Less golfed
U=(n,m)=>
{
  var R=x=>x.repeat(m),
      a=R(' '),
      b=R(`|${a}|\n`);
      c=R('-'),
      d=`o${c}o\n`;
  m=n-1;
  return d+R(b+`+${c}+\n`)+b+d
}

function test() {
  var i=I.value.match(/\d+/g)
  if (i) O.textContent=F(+i[0],+i[1])
  console.log(i,I.value)
}  
 
test()
N,M: <input id=I value="3,5" oninput=test()>
<pre id=O></pre>


document.getElementById('elem').置き換えられるとは知りませんでしたelem.!これについては+1ですが、これに関するドキュメントをいくつか指摘していただけますか?
F.ハウリ

2
@ F.Hauriはほぼすべてのブラウザで動作しますが、避けるべきです(楽しみのためにコーディングする場合を除く)。情報とリンクstackoverflow.com/questions/3434278/…-edc65
1

6

C#、1412バイト

...私の最初のCodeGolfの試み、勝つ可能性は低いが、うまくいくのでここに行く:

using System;

namespace Ascii_Ladders
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            int m = 0;

            Console.Write("Please enter Height: ");
            n = int.Parse(Console.ReadLine());
            Console.Write("Please Enter Width: ");
            m = int.Parse(Console.ReadLine());

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("o");

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < m; i++)
                {
                    Console.Write("|");
                    for (int j = 0; j < m; j++)
                    {
                        Console.Write(" ");
                    }
                    Console.WriteLine("|");
                }
                if (k != n - 1)
                {
                    Console.Write("+");
                    for (int i = 0; i < m; i++)
                    {
                        Console.Write("-");
                    }
                    Console.WriteLine("+");
                }
            }

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                 Console.Write("-");
            }
            Console.WriteLine("o");

            Console.ReadKey();
        }
    }
}

9
プログラミングパズルとコードゴルフへようこそ!コードに多くの空白があり、コードを短くするために削除できます。コードをもっとゴルフしたい場合は、C#でのゴルフのヒントを参照してください
ダウンゴート

ここで@Doᴡɴɢᴏᴀᴛに同意します。私は潜在的にそれをわずか533バイトまでゴルフすることができました。しかし、それは良いかもしれません。(警告:C#でプログラムしません。)
user48538

私はそれを314に下げましたusing System;class P{static int m;static void Main(){int n = int.Parse(Console.ReadLine());m = int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
-RedLaser

3
いくつかのスペースを逃したため、310でusing System;class P{static int m;static void Main(){int n=int.Parse(Console.ReadLine());m=int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
RedLaser

2
使用するアプローチを変更せずに270まで:using C=System.Console;class P{static void Main(){int i,k,n=int.Parse(C.ReadLine()),m=int.Parse(C.ReadLine());System.Action<char,char> M=(x,y)=>C.WriteLine(x+new string(y,m)+x);M('o','-');for(k=0;k<n;k++){for(i=0;i<m;i++){M('|',' ');}if(k<n-1){M('+','-');}}M('o','-');}}。ただし、ここでは、方法を少し変更するだけで、より多くの可能性があります。
ジョーイ

6

ジュリア、87バイト

f(n,m)=(g(x)=(b=x[1:1])x[2:2]^m*b*"\n";(t=g("o-"))join([g("| ")^m for i=1:n],g("+-"))t)

これは、2つの整数を受け入れ、文字列を返す関数です。

ゴルフをしていない:

function f(n::Int, m::Int)
    # Create a function g that takes a string of two characters and
    # constructs a line consisting of the first character, m of the
    # second, and the first again, followed by a newline.
    g(x) = (b = x[1:1]) * x[2:2]^m * b * "\n"

    # Assign t to be the top and bottom lines. Construct an array
    # of length n where each element is a string containing the
    # length-m segment of the interior. Join the array with the
    # ladder rung line. Concatenate all of this and return.
    return (t = g("o-")) * join([g("| ")^m for i = 1:n], g("+-")) * t
end

5

pb -147バイト

^t[B]>>[B]vw[T!0]{b[43]<[X]b[43]>w[B=0]{b[45]>}v[X-1]w[B=0]{b[124]^}v[X]t[T-1]}t[111]b[T]<w[X!0]{b[45]<}b[T]w[Y!0]{w[B!0]{^}b[124]^}b[T]^>>[B]vb[T]

これは、権利上、pbが本当に得意とする種類の課題です。文字でシンプルな絵を描くことは、まさにpbの設計目的です。悲しいかな、それは私が推測する単なる言葉の言語です。

最初に入力長を取得し、次にサイズを取得します。たとえば、バイト値の形式で入力を受け取ります。python -c 'print(chr(5) + chr(7))' | ./pbi.py ladder.pb

見て、楽しいアニメーション!

コメント付き:

^t[B]            # Save length to T
>>[B]v           # Go to X=size+1, Y=0

w[T!0]{          # While T is not 0:
    b[43]            # Write a '+'
    <[X]b[43]        # Write a '+' on the left side as well
    >w[B=0]{b[45]>}  # Travel back to the right '+', writing '-' on the way
    v[X-1]           # Go down by X-1 (== size)
    w[B=0]{b[124]^}  # Travel back up to the '+', writing '|' on the way
    v[X]             # Go down by X (== size + 1, location of next '+')
    t[T-1]           # Decerement T
}

t[111]           # Save 'o' to T (it's used 4 times so putting it
                 # in a variable saves bytes)

b[T]             # Write an 'o' (bottom right)

<w[X!0]{         # While not on X=0:
    b[45]<           # Travel left, writing '-' on the way
}

b[T]             # Write an 'o' (bottom left)

w[Y!0]{          # While not on Y=0:
    w[B!0]{^}        # Skip nonempty spaces
    b[124]           # Write a '|'
    ^                # Travel up
}

b[T]             # Write an 'o' (top left, replaces existing '+')

^>>[B]v          # Go back to where the size is saved and go to X=size+1, Y=0

b[T]             # Write an 'o' (top right, replaces existing '+')

5

純粋バッシュ、132の130 128 127バイト

はい${p% *}、lastを置き換えるためにもう1バイト削除できますが、私はこれを好みます:

p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"

サンプル:

ladders() {
    p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
    a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"
}

ladders 3 4
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

ladders 2 1
o--o
|  |
|  |
o--o

4

Haskell、100 97バイト

l#s=unlines$t:m++[t]where _:m=[1..l]>>["+"!"-"]++("|"!" "<$u);t="o"!"-";o!i=o++(u>>i)++o;u=[1..s]

使用例:

*Main> putStr $ 4 # 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

使い方:

l#s=unlines$t:m++[t]         -- concat top line, middle part and end line
                             -- with newlines between every line
  where                      -- where
  _:m=                       -- the middle part is all but the first line of
     [1..l]>>                -- l times
         ["+"!"-"]           --    a plus-dashes-plus line
         ++("|"!" "<$u)      --    followed by s times a bar-spaces-bar line

  t="o"!"-"                  -- very first and last line
  o!i=o++(u>>i)++o           -- helper to build a line
  u=[1..s]

編集:@Christian Irwanは3バイトを見つけました。ありがとう!


-1スコアのパターンマッチングm=init$[1..l]>>("|"!" "<$u)++["+"!"-"]=>(_:m)=[1..l]>>["+"!"-"]++("|"!" "<$u)
Akangka

驚くほど_:m=[1..l]>>["+"!"-"]++("|"!" "<$u)うまく
いく-Akangka

@ChristianIrwan:よく見かけます!ありがとう!
-nimi

3

brainfuck-334バイト

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-]<----[>---<----]--[>[+>>]<<[<<]>++++++]>[+.>>]-[<+>---]<+++++++>>--[<+>++++++]->---[<------->+]++++++++++[<++<]+++++[>[++++++>>]<<[<<]>-]>[-]>.-<<----[>>+++<<----]--[>+<--]>---<<<<++++++++++.,[>[>+>+<<-]>[<+>-]>[<<<<[>>>>>>[.>>]<<[<<]>>-]>>>>>[.>>]<<[<<]>-]<<<<+>-]>>>>[-]----[>---<----]>+.[>]<<<<<[.<<]

これはもっと短くなると思っていました。

「文字列」まで、このセットのルックスのようなもの| (...) |と1ルックスのようなその+----(...)----+ためのいくつかの特別なケースで、必要に応じて各1を印刷し、o上部と下部に秒。

8ビットセルを使用し、セル0から左に移動できるインタープリターが必要です(負のセルまたはループになります)。私の経験では、これらは最も一般的なデフォルト設定です。

コメント付き:

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-] Get m from input; make a copy
                      Turn it into m cells containing 1 with empty cells between

<----[>---<----]      Put 67 at the beginning (again with an empty cell between)

--[>[+>>]<<[<<]>++++++]  Add 43 to every nonempty cell

>[+.>>]               Add 1 to each cell and print it

-[<+>---]<+++++++    Put 92 after the last 45 (no empty cell!)

>>--[<+>++++++]      Put 43 immediately after the 92

->---[<------->+]    Put 234 after 43

++++++++++           And 10 after that

[<++<]             Add two to the 234; 92; the empty spaces; and left of the 111

+++++[>[++++++>>]<<[<<]>-] Add 30 to each 2; the 94; and the 236

>[-]>.-<<----[>>+++<<----] Erase leftmost 32; Print 111; subtract 68 from it

--[>+<--]>---        Put 124 where the 32 was

<<<<++++++++++.,     Print a newline; override the cell with n from input

[                    n times:

  >[>+>+<<-]>[<+>-]    Make a copy of m

  >[                   m times:

    <<<<                 Look for a flag at a specific cell

    [                    If it's there:

      >>>>>>[.>>]          Go to the 43; print it and every second cell after

      <<[<<]>>-            Clear the flag

    ]

    >>>>>[.>>]           Go to the 124; print it and every second cell after

    <<[<<]>              Go back to the copy of m

  -]

  <<<<+>               Plant the flag

-]

>>>>

[-]----[>---<----]>+ Erase the 124; add 68 to 43

.[>]                 Print it; then head to the end

<<<<<[.<<] Go to the last 45; print it; then print every second cell to the left



2

Perl、98バイト

($n,$m)=@ARGV;print$h="o"."-"x$m."o\n",((("|".(" "x$m)."|\n")x$m.$h)x$n)=~s{o(-+)o(?=\n.)}{+$1+}gr

1
優れた最初の答え。しかし+、コードに兆候はありません。中間ラングの+両端に兆候があると考えましたか?
レベルリバーセント

非常にうまくコメントされたコメントをありがとう。スペースもかなりかかりました。まだ省略する以外にも...私はそれを短縮することができる方法を考えて($n,$m)=@ARGV;いないことを確認場合は、その者の精神やない-と、それらがすでに設定されていると仮定。調べる必要があります。
ZILjr

質問で特に指定されていない限り、ルールはmeta.codegolf.stackexchange.com/a/2422/15599です。変数が設定されていると仮定することはできませんが、それが役立つ場合は、プログラムの代わりに関数を書くことができます。私はPerlをしませんが、それはあなたを救うかもしれないと思います@ARGV。また、誰かに返信するときは、アラートを受け取るために@usernameを含めることを忘れないでください。これはあなたの投稿なので、行う必要はありません。
レベルリバーセント


1

Tcl、187バイト

lassign $argv n w
set c 0
while { $c < [expr {($w * $n) + ($n + 2)}]} {if {[expr {$c % ($n + 1)}] == 0} {puts "o[string repeat "-" $w ]o"} else {puts "|[string repeat " " $w ]|"}
incr c}

このコードは、コマンドラインで入力された引数とともにファイルに入れられます。ボックスの数と幅をこの順序で指定します。


1

PHP、81バイト

PHPコマンドを直接呼び出すときに渡される2つの引数が必要です。1つ目はサイズで、2つ目はステップ数です。

$R=str_repeat;echo$P="o{$R('-',$W=$argv[1])}o
",$R("|{$R(' ',$W)}|
$P",$argv[2]);

いくつかの改善が必要な場合があります。


0

Python 2、94バイト

def F(n,m):a,b,c,d='o|+-';r=[a+d*m+a]+([b+' '*m+b]*m+[c+d*m+c])*n;r[-1]=r[0];print'\n'.join(r)

「Ungolfed」:

def F(n,m):
 # 'o---o'
 r = ['o'+'-'*m+'o']
 # ('|   |'*m+'+---+') n times
 r += (['|'+' '*m+'|']*m+['+'+'-'*m+'+'])*n
 # replace last +---+ with o---o
 r[-1] = r[0]
 print '\n'.join(r)


0

ピップ -l、35バイト

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o

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

説明

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o
                                     a is length, b is size, s is space (implicit)
   sXb                               String containing b spaces
      RLa                            List containing a copies of that string
         JW'-                        Join on "-" and wrap the result in "-" as well
  Y                                  Necessary for operator precedence reasons
 ^                                   Split into a list of characters
(            )Xb                     String-repeat each character in the list b times
                                     This list represents the central columns of the ladder

                    '|Xb             String containing b pipe characters
                        RLa          List containing a copies of that string
                           J'+       Join on "+"
                   (          )WR'o  Wrap in "o"
                  ^                  Split into a list of characters
                                     This list represents the outer columns of the ladder

                WR                   Wrap the left list in the right list, vectorizing

他のバージョン

私はPythを捕まえようとしてさまざまなアプローチを試しました...

[Y'-XbWR'o;@>(sXbWR'|RLbPE'-XbWR'+RL:a)y]  41
Y^(t**b.1*:t**bX--a.1)" --"@yXbWR"|o+"@y   40
Y'|XbRLaJ'+YyWR'o;Z:sXbRLaJW'-RLbPEyAEy    39
t**:b(" |-o-+"<>2)@_@^t.1M$*Y[ttXa-1].1    39
J*Z:sXbRLaJW'-RLbWR:^('|XbRLaJ'+)WR'o      37
Y^$*Y[t**:btXa-1].1" --"@yXbWR"|o+"@y      37

t**bラダーの垂直パターンを生成するために数学を使用するものが特に好きです。

        b           Size; e.g. 3
    t               Preset variable for 10
     **:            Set t to t**b (e.g. 1000)
           a        Length; e.g. 3
            -1      2
         tX         String-repeat (the new value of) t 2 times: 10001000
   [          ]     Put t and the above into a list: [1000; 10001000]
               .1   Append 1 to both of them: [10001; 100010001]
$*(              )  Fold on multiplication: 1000200020001

1000200020001使用して、はしごを構成するパターンo|||+|||+|||oとを生成でき- - - -ます。残念ながら、このアプローチをjoin / wrapアプローチよりも短くすることはできませんでした。

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