ASCII長方形を描く


20

2つの整数を配列の入力として指定し、最初の整数を幅として、2番目の整数を高さとして使用して、長方形を描きます。

または、言語でサポートされている場合、2つの整数を別々の入力として指定できます。

幅と高さが3未満になることはないと仮定し、常に指定されます。

出力例:

[3、3]

|-|
| |
|-|

[5、8]

|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

[10、3]

|--------|
|        |
|--------|

これはコードゴルフであるため、バイト数が最も少ない答えが優先されます。

回答:



10

ゼリー、14 バイト

,þ%,ỊḄị“-|| ”Y

オンラインでお試しください!またはすべてのテストケースを検証する

使い方

,þ%,ỊḄị“-|| ”Y  Main link. Left argument: w. Right argument: h

,þ              Pair table; yield a 2D array of all pairs [i, j] such that
                1 ≤ i ≤ w and 1 ≤ j ≤ h.
   ,            Pair; yield [w, h].
  %             Take the remainder of the element-wise division of each [i, j]
                by [w, h]. This replaces the highest coordinates with zeroes.
    Ị           Insignificant; map 0 and 1 to 1, all other coordinates to 0.
     Ḅ          Unbinary; convert each pair from base 2 to integer.
                  [0, 0] -> 0 (area)
                  [0, 1] -> 1 (top or bottom edge)
                  [1, 0] -> 2 (left or right edge)
                  [1, 1] -> 3 (vertex)
       “-|| ”   Yield that string. Indices are 1-based and modular in Jelly, so the
                indices of the characters in this string are 1, 2, 3, and 0.
      ị         At-index; replace the integers by the correspoding characters.
             Y  Join, separating by linefeeds.

これは:)の素晴らしい使用です。-
リン

9

Matlab、69 65 56バイト

@WeeingIfFirstと@LuisMendoに感謝します=)

function z=f(a,b);z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])='|'

これはMatlabでは本当に簡単です。最初に目的のサイズの行列を作成し、最初と最後の行にインデックスを付けてを挿入-し、最初と最後の列に同じように挿入し|ます。

例のためのf(4,3)リターン

|--|
|  |
|--|

@WeeingIfFirstああ、もちろん、どうもありがとう!
-flawr

6バイト短縮:z([1,b],1:a)=45;z(1:b,[1,a])=124;z=[z,'']
Stewie Griffin

さらに短く:z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])=124
ルイスメンドー

@LuisMendoありがとう!まだ厳しい文字列が必要です。そうでない場合、配列は数値配列に変換されます。
フレイ

@flawr z(b,a)=' 'はcharとして初期化されます。その後、数字を入力すると、それらは自動的にcharにキャストされます。z元のタイプを維持
ルイスメンドー

8

JavaScript(ES6)、63バイト

f=
(w,h,g=c=>`|${c[0].repeat(w-2)}|
`)=>g`-`+g` `.repeat(h-2)+g`-`
;
<div oninput=o.textContent=f(w.value,h.value)><input id=w type=number min=3 value=3><input id=h type=number min=3 value=3><pre id=o>


テンプレート関数をデフォルト引数として渡しますか?賢い!
フローリー

8

Haskell、62 55バイト

f[a,b]n=a:(b<$[3..n])++[a]
g i=unlines.f[f"|-"i,f"| "i]

使用例:

*Main> putStr $ g 10 3
|--------|
|        |
|--------|

ヘルパー関数fは、2つの要素のリスト[a,b]と数値nを受け取り、1つan-2 bs 、1の順に続くリストを返しますafthrice:を使用して、上/下の行:f "|-" i、中間の行:f "| " iを作成し、これら2つから長方形全体を作成できますf [<top>,<middle>] j(注:部分的なアプリケーションのためj、パラメーターとして表示されませんg i)。

編集:@dianneは、2つのChar引数をString長さ2の引数に結合することにより、いくつかのバイトを節約しました。ありがとうございました!


私はその#アイデアが好きです!
-flawr

2
定義(a:b)#n=a:([3..n]>>b)++[a]して書くことで数バイト節約できると思います["|-"#i,"| "#i]#j
ダイアン

@dianne:とても賢い。どうもありがとう!
nimi

8

パイソン2、61 58バイト

@flornquakeのおかげで-3バイト(不要な括弧を削除h、カウンターとして使用)

def f(w,h):exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h

テストケースはイデオンにあります


('- '[1<i<h])括弧は必要ありません。
flornquake

hをカウンターとして使用して、別のバイトを保存しますexec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h
。– flornquake

@flornquakeこれらの括弧の必要性をチェックするつもりでしたが、忘れていました。hカウンターとして使用するのは賢明です!ありがとう。
ジョナサンアラン


7

Vimscript、93 83 75 74 73 66 64 63バイト

コード

fu A(...)
exe "norm ".a:1."i|\ehv0lr-YpPgvr dd".a:2."p2dd"
endf

:call A(3,3)

説明

fun A(...)    " a function with unspecified params (a:1 and a:2)
exe           " exe(cute) command - to use the parameters we must concatenate :(
norm          " run in (norm) al mode
#i|           " insert # vertical bars
\e            " return (`\<Esc>`) to normal mode
hv0l          " move left, enter visual mode, go to the beginning of the line,  move right (selects inner `|`s)
r-            " (r)eplace the visual selection by `-`s
YpP           " (Y) ank the resulting line, and paste them twice
gv            " re-select the previous visual selection
r<Space>      " replace by spaces
dd            " Cut the line
#p            " Paste # times (all inner rows) 
2dd           " Remove extra lines

使用しnorm!ていないため、vimカスタムマッピングに干渉する可能性があることに注意してください!


5

MATL、19バイト

'|-| '2:"iqWQB]E!+)

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

説明

アプローチはこの他の答えで使用されるそれと同様です。コードは次の形式の数値配列を作成します

3 2 2 2 3
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
3 2 2 2 3

そして、その値は文字列への(1ベースのモジュラー)インデックスとして使用されます '|-| '、目的の結果が生成。

'|-| '                % Push this string
      2:"     ]       % Do this twice
         i            % Take input
          q           % Subtract 1
           W          % 2 raised to that
            Q         % Add 1
             B        % Convert to binary
               E      % Multiply by 2
                !     % Transpose
                 +    % Add with broadcast
                  )   % Index (modular, 1-based) into the string

5

05AB1E23 22 20バイト

入力は高さ、次に幅として取得されます。

F„ -N_N¹<Q~è²Í×'|.ø,

説明

F                          # height number of times do
    N_                     # current row == first row
          ~                # OR
      N¹<Q                 # current row == last row
 „ -       è               # use this to index into " -"
            ²Í×            # repeat this char width-2 times
               '|          # push a pipe
                 .ø        # surround the repeated string with the pipe
                   ,       # print with newline

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

Adnanのおかげで2バイト節約


if-elseステートメントの代わりにサブストリングを使用すると、2バイト節約できますF„ -N_N¹<Q~è²Í×'|.ø,
アドナン

5

C、73バイト

i;f(w,h){for(i=++w*h;i--;)putchar(i%w?~-i%w%~-~-w?i/w%~-h?32:45:124:10);}

4

Python 2、56バイト

w,h=input()
for c in'-%*c'%(h-1,45):print'|'+c*(w-2)+'|'

flornquakeは1バイトを節約しました。


1
文字列フォーマットの素晴らしい使用!%c変換を使用してバイトを保存できます'-%*c'%(h-1,45)
。– flornquake

ああ、私%*cはものでさえないと思いました!ありがとうございました。:)
リン

'-%%%dc'%~-h%45同じ長さでも機能します。
-xnor

4

Common Lisp、104バイト

ゴルフ:

(defun a(w h)(flet((f(c)(format t"|~v@{~A~:*~}|~%"(- w 2)c)))(f"-")(loop repeat(- h 2)do(f" "))(f"-")))

ゴルフをしていない:

(defun a (w h)
  (flet ((f (c) (format t "|~v@{~A~:*~}|~%" (- w 2) c)))
    (f "-")
    (loop repeat (- h 2) do
     (f " "))
    (f "-")))

3

タートルード、40バイト

通訳はありません少しもはや盗聴

?;,u[*'|u]'|?@-[*:l'|l[|,l]d@ ],ur[|'-r]

説明

?                            - input integer into register
 ;                           - move down by the contents of register
  ,                          - write the char variable, default *
   u                         - move up
    [*   ]                   - while current cell is not *
      '|                     - write |
        u                    - move up
          '|                 - write | again
            ?                - input other integer into register
             @-              - set char variable to -
               [*             ] - while current char is not *
                 :l'|l          - move right by amount in register, move left, write |, move left again
                      [|,l]     - while current cell is not |, write char variable, move left
                           d@   - move down, set char variable to space (this means all but first iteration of loop writes space)
                               ,ur   -write char variable, move up, right
                                  [|   ] -while current char is not |
                                    '-r - write -, move right

3

Mathematica、67 64バイト

ラストリゾートとTuukkaXに、ゴルファーはこっそりして3バイト節約する必要があることを思い出させてくれてありがとう!

簡単な実装。文字列の配列を返します。

Table[Which[j<2||j==#,"|",i<2||i==#2,"-",0<1," "],{i,#2},{j,#}]&

1
0<1代わりに使用True
-u54112

1
私はそれが思うj==1に低減することができj<1、およびi==1i<1
Yytsi

3

Python 3、104 95バイト

(@ mbomb007からのフィードバック:-9バイト)

def d(x,y):return'\n'.join(('|'+('-'*(x-2)if n<1or n==~-y else' '*(x-2))+'|')for n in range(y))

(私の最初のコードゴルフ、フィードバックに感謝します)


ようこそ!いくつかのスペースを削除して、のrange(y)代わりに使用できます。負でないrange(0,y)場合nは、使用できますif n<1or n==~-y else
mbomb007

Pythonのヒントページを参照してください
mbomb007

@ mbomb007ありがとう!確かめます。
バイアリティ

2

バッチ、128バイト

@set s=
@for /l %%i in (3,1,%1)do @call set s=-%%s%%
@echo ^|%s%^|
@for /l %%i in (3,1,%2)do @echo ^|%s:-= %^|
@echo ^|%s%^|

コマンドラインパラメーターとして幅と高さを取ります。


2

Haxe、112 106バイト

function R(w,h){for(l in 0...h){var s="";for(i in 0...w)s+=i<1||i==w-1?'|':l<1||l==h-1?'-':' ';trace(s);}}

テストケース

R(5, 8)
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

R(10, 3)
|---------|
|         |
|---------|

2

Java 135バイト

public String rect(int x, int y){
String o="";
for(int i=-1;++i<y;){
o+="|";
for(int j=2;++j<x)
if(i<1||i==y-1)
o+="-";
else
o+=" ";
o+="|\n";
}
return o;
}

ゴルフ:

String r(int x,int y){String o="";for(int i=-1;++i<y;){o+="|";for(int j=2;++j<x;)if(i<1||i==y-1)o+="-";else o+=" ";o+="|\n";}return o;}

私は136を数えます:)また、最初のコンマの後のスペースを削除することで文字を保存することができます。
クリスチャンロンドー

1
まず、このコードはコンパイルされません。これがコンパイルされても、OPが現在必要としているように長方形を「描画」しません。-1。
Yytsi

@TuukkaX改行の問題を修正しましたが、コンパイルできない理由はわかりません。もちろん、そのコードをクラスに入れる必要がありますが、その後は動作するはずです。
ローマングラフ

1
「コンパイルしてはならない理由がわからない」。では、これは何o+=x "|\n"ですか?+そこに置くつもりですか?
-Yytsi

ありがとう。キャラクターをそこに配置したくありませんでした。
ローマングラフ

2

PowerShell v3 +、55バイト

param($a,$b)1..$b|%{"|$((' ','-')[$_-in1,$b]*($a-2))|"}

入力$aとを受け取ります$b。から1にループし$bます。繰り返しごとに、単一の文字列を作成します。真ん中は、2つの単一の長さの文字列の配列から選択され、$a-2パイプで囲まれている間、で文字列が乗算されます。結果の文字列はパイプラインに残り、暗黙的な出力Write-Outputはプログラムの完了時に発生し、デフォルトの改行セパレーターが使用されます。

あるいは、55バイトでも

param($a,$b)1..$b|%{"|$((''+' -'[$_-in1,$b])*($a-2))|"}

これは、代わりに文字列を使用して中央の配列選択をゴルフしようとしていたために生じました。ただし、[char]時間[int]は定義されていないため、かっこと文字列としてキャストする必要があるため、節約量を失うことになります。''+ます。

どちらのバージョンでも、-inオペレーターにはv3以降が必要です。

PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 10 3
|--------|
|        |
|--------|

PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 7 6
|-----|
|     |
|     |
|     |
|     |
|-----|

2

PHP、82バイト

list(,$w,$h)=$argv;for($p=$h--*$w;$p;)echo$p--%$w?$p%$w?$p/$w%$h?" ":"-":"|
":"|";

改行を含む静的文字列のインデックス付け

list(,$w,$h)=$argv;         // import arguments
for($p=$h--*++$w;$p;)       // loop $p through all positions counting backwards
    // decrease $h and increase $w to avoid parens in ternary conditions
    echo" -|\n"[
        $p--%$w             // not (last+1 column -> 3 -> "\n")
        ?   $p%$w%($w-2)    // not (first or last row -> 2 -> "|")
            ?+!($p/$w%$h)   // 0 -> space for not (first or last row -> 1 -> "-")
            :2
        :3
    ];

親愛なるダウンボーター:なぜ?
タイタス

1
レビューキューであなたの回答が低品質としてフラグ付けされていることをユーザーが見たためである可能性があります。コードの説明、または1行以上のものを投稿すると、自動的にフラグが立てられるのを回避できます。
mbomb007

@mbomb:誰もが非eso言語でonelinerの説明を投稿するのを見たことはありません。
タイタス

または、出力、または非ゴルフバージョン。コンテンツが短すぎない限り、問題ではありません。しかし、あなたはそれを見たことがないなら、おそらく長くはいません。一部のPythonワンライナーはかなり複雑になる可能性があります。@xnorのいくつかを見てください。
mbomb007

2

Ruby, 59 54 52 bytes

Oh, that's a lot simpler :)

->x,y{y.times{|i|puts"|#{(-~i%y<2??-:' ')*(x-2)}|"}}

Test run at ideone


1
You can save a couple bytes by using a literal newlines instead of \n.
Jordan

1
You can save bytes by not defining i and j. Replace i's definition with x-=2. Instead of j, just use (y-2).
m-chrzan

Yeah, thanks :)
daniero

2

Perl, 48 bytes

Includes +1 for -n

Give sizes as 2 lines on STDIN

perl -nE 'say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"'
3
8
^D

Just the code:

say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"

Nice one, as always. Note that you've got a backtick at the end of the line while you probably wanted to write a single quote ;-)
Dada

@Dada Fixed. Thanks.
Ton Hospel

2

Lua, 120 93 bytes

Saved quite a few bytes by removing stupid over complexities.

function(w,h)function g(s)return'|'..s:rep(w-2)..'|\n'end b=g'-'print(b..g' ':rep(h-2)..b)end

Ungolfed:

function(w,h)                           -- Define Anonymous Function
    function g(s)                       -- Define 'Row Creation' function. We use this twice, so it's less bytes to function it.
        return'|'..s:rep(w-2)..'|\n'    -- Sides, Surrounding the chosen filler character (' ' or '-'), followed by a newline
    end
    b=g'-'                              -- Assign the top and bottom rows to the g of '-', which gives '|---------|', or similar.
    print(b..g' ':rep(h-2)..b)          -- top, g of ' ', repeated height - 2 times, bottom. Print.
end

Try it on Repl.it


1

Python 2, 67 bytes

def f(a,b):c="|"+"-"*(a-2)+"|\n";print c+c.replace("-"," ")*(b-2)+c

Examples

f(3,3)

|-|
| |
|-|

f(5,8)

|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

f(10,3)

|--------|
|        |
|--------|

1

MATL, 21 17 bytes

Z"45ILJhY('|'5MZ(

This is a slightly different approach than the one of the MATL-God.

Z"                   Make a matrix of spaces of the given size
  45ILJhY(           Fill first and last row with '-' (code 45)
          '|'5MZ(    Fill first and last column with '|' (using the automatic clipboard entry 5M to get ILJh back)

Thanks @LuisMendo for all the help!

Try it Online!


1

PHP 4.1, 76 bytes

<?$R=str_repeat;echo$l="|{$R('-',$w=$W-2)}|
",$R("|{$R(' ',$w)}|
",$H-2),$l;

This assumes you have the default php.ini settings for this version, including short_open_tag and register_globals enabled.

This requires access through a web server (e.g.: Apache), passing the values over session/cookie/POST/GET variables.
The key W controls the width and the key H controls the height.
For example: http://localhost/file.php?W=3&H=5


@Titus You should read the link. Quoting: "As of PHP 4.2.0, this directive defaults to off".
Ismael Miguel

Ouch sorry I take everything back. You have the version in your title. I should read more carefully.
Titus

@Titus That's alright, don't worry. Sorry for being harsh on you.
Ismael Miguel

Nevermind; that´s the price I pay for being pedantic. :D
Titus

@Titus Don't worry about it. Just so you know, around half of my answers are written in PHP 4.1. It saves tons of bytes with input
Ismael Miguel

1

Python 3, 74 chars

p="|"
def r(w,h):m=w-2;b=p+"-"*m+p;return b+"\n"+(p+m*" "+p+"\n")*(h-2)+b

1

Swift(2.2) 190 bytes

let v = {(c:String,n:Int) -> String in var s = "";for _ in 1...n {s += c};return s;};_ = {var s = "|"+v("-",$0-2)+"|\n" + v("|"+v(" ",$0-2)+"|\n",$1-2) + "|"+v("-",$0-2)+"|";print(s);}(10,5)

I think Swift 3 could golf this a lot more but I don't feel like downloading Swift 3.


1

F#, 131 bytes

let d x y=
 let q = String.replicate (x-2)
 [for r in [1..y] do printfn "%s%s%s" "|" (if r=y||r=1 then(q "-")else(q " ")) "|"]
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.