Disegna un rettangolo ASCII


20

Dati due numeri interi come input in un array, disegna un rettangolo, usando il primo numero intero come larghezza e il secondo come altezza.

Oppure, se la tua lingua lo supporta, i due numeri interi possono essere dati come input separati.

Supponiamo che la larghezza e l'altezza non siano mai inferiori a 3 e verranno sempre fornite.

Esempi di output:

[3, 3]

|-|
| |
|-|

[5, 8]

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

[10, 3]

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

Questo è code-golf, quindi vince la risposta con il minor numero di byte.

Risposte:


6

Jolf, 6 byte

,ajJ'|

Provalo qui! Il mio box integrato finalmente è tornato utile! : D

,ajJ'|
,a       draw a box
  j      with width (input 1)
   J     and height (input 2)
    '    with options
     |    - corner
          - the rest are defaults

10

Gelatina , 14 byte

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

Provalo online! o verifica tutti i casi di test .

Come funziona

,þ%,ỊḄị“-|| ”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.

Questo è un uso meraviglioso di :)
Lynn,

9

Matlab, 69 65 56 byte

Grazie @WeeingIfFirst e @LuisMendo per alcuni byte =)

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

Questo è davvero semplice in Matlab: prima crea una matrice della dimensione desiderata, quindi indicizza la prima e l'ultima riga per inserire il -, e fai lo stesso con la prima e l'ultima colonna da inserire| .

Ad esempio, f(4,3)ritorna

|--|
|  |
|--|

@WeeingIfFirst Oh, certo, grazie mille!
Flawr,

6 byte più brevi:z([1,b],1:a)=45;z(1:b,[1,a])=124;z=[z,'']
Stewie Griffin,

Ancora più breve:z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])=124
Luis Mendo,

@LuisMendo Grazie! Abbiamo ancora bisogno della stringa robusta, altrimenti l'array viene convertito in uno numerico.
Flawr,

@flawr z(b,a)=' 'inizializza come carattere. Dopodiché puoi riempire con i numeri e questi vengono automaticamente espressi in caratteri. zmantiene il suo tipo originale
Luis Mendo,

8

JavaScript (ES6), 63 byte

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>


Passare una funzione modello come argomento predefinito? Intelligente!
Florrie,

8

Haskell, 62 55 byte

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

Esempio di utilizzo:

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

La funzione helper faccetta un elenco di due elementi [a,b]e un numero ne restituisce un elenco di uno aseguito da n-2 bs seguito da uno a. Possiamo usare ftre volte: per costruire la linea superiore / inferiore:, f "|-" iuna linea centrale: f "| " ie da quei due l'intero rettangolo: f [<top>,<middle>] j(nota: jnon appare come parametro ing i causa di un'applicazione parziale).

Modifica: @dianne ha salvato alcuni byte combinando due Charargomenti in uno Stringdi lunghezza 2. Grazie mille!


Mi piace l' #idea!
Flawr,

2
Penso che puoi salvare qualche byte definendo (a:b)#n=a:([3..n]>>b)++[a]e scrivendo["|-"#i,"| "#i]#j
dianne,

@dianne: molto intelligente. Molte grazie!
nimi,

8

Python 2, 61 58 byte

-3 byte grazie a @flornquake (rimuove le parentesi non necessarie; usa hcome contatore)

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

I casi di test sono su ideone


('- '[1<i<h])non ha bisogno delle parentesi.
terremoto del

Salvare un altro byte utilizzando h come contatore:exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h
flornquake,

@flornquake Avevo intenzione di verificare la necessità di quelle parentesi, ma ho dimenticato. Usare hcome contatore è intelligente! Grazie.
Jonathan Allan,

8

PHP, 74 byte

for(;$i<$n=$argv[2];)echo str_pad("|",$argv[1]-1,"- "[$i++&&$n-$i])."|\n";

1
Puoi comunque vincere un byte con un'interruzione di linea fisica.
Tito,

1
-2 byte con !$i|$n==++$iinvece di!$i|$n-1==$i++
Tito

1
un altro byte con$i++&&$n-$i?" ":"-"
Tito,

1
$i++&&$n-$i?" ":"-"-> "- "[$i++&&$n-$i](-2)
Tito

7

Vimscript, 93 83 75 74 73 66 64 63 byte

Codice

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

Esempio

:call A(3,3)

Spiegazione

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

Nota che non sta usando, norm!quindi potrebbe interferire con le mappature personalizzate di VIM!


5

MATL , 19 byte

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

Provalo online!

Spiegazione

L'approccio è simile a quello utilizzato in questa altra risposta . Il codice crea una matrice numerica del modulo

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

e quindi i suoi valori vengono utilizzati come indici (a base 1, modulari) nella stringa '|-| 'per produrre il risultato desiderato.

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

05AB1E , 23 22 20 byte

Input preso come altezza, quindi larghezza.

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

Spiegazione

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

Provalo online!

Salvato 2 byte grazie ad Adnan


Utilizzando sottostringhe anziché l'istruzione if-else salva due byte: F„ -N_N¹<Q~è²Í×'|.ø,.
Adnan,

5

C, 73 byte

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 byte

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

flornquake ha salvato un byte.


1
Buon uso della formattazione delle stringhe! Puoi salvare un byte usando la %cconversione:'-%*c'%(h-1,45)
flornquake,

Oh, pensavo %*cnon fosse nemmeno una cosa! Grazie. :)
Lynn,

'-%%%dc'%~-h%45funziona anche per la stessa lunghezza.
xnor

4

Lisp comune, 104 byte

golfed:

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

Ungolfed:

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

3

Turtlèd , 40 byte

L'interprete non è leggermente più disturbato

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

Spiegazione

?                            - 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 byte

Grazie a lastresort e TuukkaX per avermi ricordato che i golfisti dovrebbero essere subdoli e risparmiare 3 byte!

Implementazione semplice. Restituisce una matrice di stringhe.

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

1
Utilizzare 0<1al posto diTrue
u54112

1
Penso che j==1possa essere ridotto a j<1, e i==1a i<1.
Yytsi,

3

Python 3, 104 95 byte

(feedback da @ mbomb007: -9 byte)

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

(il mio primo codice golf, apprezzo feedback)


Benvenuto! Puoi rimuovere alcuni degli spazi, usare al range(y)posto di range(0,y), e se nnon è mai negativo puoi usareif n<1or n==~-y else
mbomb007

Vedi la pagina dei suggerimenti di Python
mbomb007,

@ mbomb007 grazie! Io lo verificherò.
Biarity,

2

Lotto, 128 byte

@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%^|

Accetta larghezza e altezza come parametri della riga di comando.


2

Haxe, 112 106 byte

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

Casi test

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

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

2

Java 135 byte

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

golfed:

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

Conto 136 :) Puoi anche salvare un carattere rimuovendo lo spazio dopo la prima virgola.
Christian Rondeau,

1
Prima di tutto, questo codice non viene compilato. Anche se questo si compilasse, non "disegnare" un rettangolo come l'OP attualmente desidera. -1.
Yytsi,

@TuukkaX I fixed that newline problem, but I don't see any reason why it should not compile. Of course you have to put that code in a class, but then it should work.
Roman Gräf

1
"I don't see any reason why it should not compile". What's this then: o+=x "|\n"? Did you mean to put an + there?
Yytsi

Thanks. I didn't wanted to place any characters there.
Roman Gräf

2

PowerShell v3+, 55 bytes

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

Takes input $a and $b. Loops from 1 to $b. Each iteration, we construct a single string. The middle is selected from an array of two single-length strings, then string-multiplied by $a-2, while it's surrounded by pipes. The resulting strings are left on the pipeline, and output via implicit Write-Output happens on program completion, with default newline separator.

Alternatively, also at 55 bytes

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

This one came about because I was trying to golf the array selection in the middle by using a string instead. However, since [char] times [int] isn't defined, we lose out on the savings by needing to cast as a string with parens and ''+.

Both versions require v3 or newer for the -in operator.

Examples

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 bytes

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

indexing a static string including the newline

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

Dear downvoter: why?
Titus

1
It could be because a user saw that your answer was flagged as low quality in the review queue. If you post an explanation of your code, or anything more than a one-liner, you can avoid it being automatically flagged.
mbomb007

@mbomb: I have never seen anyone post a description for a oneliner in a non-eso language.
Titus

Or output, or a non-golfed version. It doesn't matter as long as the content is not too short. But you probably haven't been around long if you haven't seen that. Some Python one-liners can be pretty complicated. Look at some of @xnor's.
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 " ")) "|"]
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.