Crea dinamicamente scatole


22

La sfida:

Disegna un rettangolo di caselle ASCII: []

Le regole:

Accetta input per larghezza e altezza

Puoi presumere che entrambi questi siano numeri

Deve produrre una stringa con caratteri di nuova riga, \ n

Esempi:

2, 2:

[][]
[][]

2, 3:

[][]
[][]
[][]

Vince il minor numero di byte.


2
Bel primo post! Benvenuti in PPCG!
MD XF,

1
Posso presumere che i numeri siano positivi? Possono esserci nuove righe finali?
dzaima,

@dzaima Interi positivi, niente elementi finali o
iniziali

possiamo stampare su console o dobbiamo restituire la stringa?
Giuseppe,

5
cosa succede se non possiamo letteralmente non stampare nuove righe finali? tende ad essere una buona pratica consentire una nuova riga finale
Destructible Lemon

Risposte:


6

SOGL , 5 byte

Ƨ[]*∙

Semplice:

Ƨ[]    push "[]"
   *   multiply horizontally (repeating width times)
    ∙  get an array with input (height) items of that
       implicitly output the array joined with newlines

4

Mathematica, 26 byte

Grid@Table["[]",{#2},{#}]&

Un Gridoggetto Mathematica conta come "una stringa con caratteri di nuova riga"?
David Zhang,

4

MATL , 7 byte

v&DiiX"

Provalo online!

Spiegazione

v    % Concatenate the (non-existing) stack contents: gives []
&D   % String representation: gives '[]'
ii   % Take two inputs
X"   % Repeat those numbers of times vertically and horizontally. Implicit display

4

Pyth - 7 5 byte

-2 byte con un trucco intelligente grazie a insert_name_here

VE*`Y

Provalo qui

Spiegazione:

VE*`Y
V      # Loop
 E     # <input> number of times
   `Y  # String representation of empty list (used to be "[]", but insert_name_here pointed out this shorter alternative)
  *    # repeat string implicit input number of times
       # implicit print

3
È possibile salvare 2 byte utilizzando `Y(rappresentazione stringa dell'elenco vuoto) anziché "[]".
insert_name_here

@insert_name_here Ingenious !! Ho aggiornato la risposta. Grazie per la segnalazione!
Maria,

1
È venuto con questo codice esatto in modo indipendente. Ben fatto.
Isaacg,

4

C, 47 46 byte

f(w,h){for(h*=w;h--;)printf(h%w?"[]":"[]\n");}

o

f(w,h){for(h*=w;h--;)printf("[]%c",h%w?0:10);}

Il mio primo tentativo di golf con codice, mi sono perso qualcosa di ovvio?


Ce n'è per 45, ma all'inizio ha una nuova riga:f(w,h){h*=w;while(h--)printf("\n[]"+!(h%w));}
Conor O'Brien,

Funziona solo quando la larghezza è 2.
dbandstra

Così lo fa, il mio errore
Conor O'Brien

Ottimo primo golf! Benvenuti nel sito!
MD XF,

1
L'uso di un forloop non ridurrebbe ulteriormente il codice?
Spikatrix,

3

05AB1E , 6 byte

F„[]×,

Provalo online!

Spiegazione

L'ingresso accetta come height, width

F         # height times do
 „[]      # push "[]"
    ×     # repeat width times
     ,    # print with newline

3

; # + , 197 byte

>;;;;;;~++++++++:>~;;;;:>~*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-::<-::::>-::(;)::>-::*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-:<~<;;;;;-+>-:<-:-(-:::~<-:::(~<#<-;;-#~;)-:<#-::<;>-:-)

Provalo online! Richiede uno zero byte dopo ogni numero di input.

Non so come funzioni. Quello che posso dirti è che questa parte del codice:

 *(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-::<-::::>-::(;)::>-::*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)

sta analizzando i numeri di input.


3

Brainfuck, 145 byte

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

Provalo online!

Il mio primo golf in assoluto! Sìì!

L'input è in ascii + 48, quindi per fare 50, 50 devi inserire b, b (le lettere ascii per 98)

Spiegazione

+++++++++[>++++++++++<-]>+ Get the opening square bracket into first position
[>+>+<<-] Get it into the second and third position
>>++ Get the third position to be the closing bracket
>
,>+++++++++[<----->-]<--- Get first number into fourth cell
>>>
,>+++++++++[<----->-]<--- Get second number into seventh cell
>++++++++++ get newline into 8th position
<

[ Start our height loop
<<<[>+>+<<-] Get the width into the fifth and sixth positions
>[ Start our width loop at the fifth position
<<<.>. Print the second and third positions
>>-] Decrement the fifth position
>
[<<+>>-] copy the sixth position into the fourth position
>>. print newline
<-]

Impressionante. Benvenuti nel sito! :)
DJMcMayhem

Perché l'ingresso ASCII + 48? Puoi salvare molti byte semplicemente usando l'ingresso ASCII + 0 (possibilmente collegandoti alla versione ASCII + 48 per usabilità)
CalculatorFeline

Volevo solo soddisfare i criteri per l'input, @calculatorFeline
vityavv,

...Oh giusto. : |
Calcolatrice

2

J , 12 byte

'[]'$~],+:@[

Provalo online!

Spiegazione

'[]'$~],+:@[   input: y, x
        +:@[   double y
      ],       pair with x
               this gives (x, 2y)
    $~         shape the left argument into the right argument's shape
'[]'           2-length character string

Questo ci dà una xdalla 2ystringa di ripetere []caratteri.




2

Gelatina , 7 byte

ẋ⁾[]ẋ$Y

Un collegamento diadico che restituisce un elenco di caratteri (o un programma completo che stampa il risultato).

Provalo online!

Come?

ẋ⁾[]ẋ$Y - Main link: number w, number h          e.g. 2, 3
ẋ       - repeat w h times                            [2,2,2]
     $  - last two links as a monad:
 ⁾[]    -   literal ['[',']'],                        "[]"
    ẋ   -   repeat list (vectorises)                  ["[][]","[][]","[][]"]
      Y - join with newlines                          "[][]\n[][]\n[][]"
        - if a full program, implicit print




2

Ohm , 9 byte

M"[]"َJ,    

Provalo online!

Spiegazione

M"[]"َJ,
M         //Executes code input1 times
 "[]"     //Pushes []
     َ   //Duplicates [] input2 times
       J  //Joins the stack
        , //Prints with a trailing newline

2

PowerShell, 25 byte

param($w,$h),("[]"*$w)*$h

-3 grazie a Mathias!


Puoi accorciarlo a 25 in questo modo:param($w,$h),("[]"*$w)*$h
Mathias R. Jessen il

2

Japt , 13 12 + 1 = 14 13 byte

+1 per la -Rbandiera.

"[]"pN× òU*2

Provalo online

  • 1 byte salvato grazie a obarakon.


@ETHproductions: il cartone animato che stavo cercando ma era troppo ubriaco per trovare!
Shaggy

Haha, spero che vi stiate divertendo una notte. a proposito, U*Vpuò essere abbreviato in
Oliver,

1
@obarakon: ecco 2 opportunità con cui lavorare Nieri sera. Mai bere e giocare a golf, bambini!
Shaggy,

2

APL (Dyalog) , 11 byte

'[]'⍴⍨⊢,2×⊣

Provalo online!

'[]' la stringa

⍴⍨ ripetuto ciclicamente per riempire la forma

 argomento giusto (righe)

, e

 due volte

l'argomento sinistro (colonne)


2

Carbone , 8 7 byte

EN×[]Iη

Provalo online! Il collegamento è alla versione dettagliata del codice. Accetta input per altezza, larghezza. I primitivi per il disegno di Charcoal non sono adatti a questo, quindi questo prende semplicemente la via d'uscita e ripete la []stringa in modo appropriato. Spiegazione:

 N      First input as a number
E       Map over implcit range
      η Second input
     I  Cast to number
   []   Literal string
  ×     Repeat
        Implicitly print on separate lines

Bene, ha questo disegno di primitive ma ancora 8 byte : P
ASCII il

@ Solo ASCII Spiacente, non mi ero reso conto che Oblong lavorava su stringhe arbitrarie. ! Neat
Neil,

@ Solo ASCII Oh, e qual è il nome dettagliato della variabile stringa vuota predefinita?
Neil,


@ ASCII-only Allora cosa sto facendo di sbagliato qui: provalo online!
Neil,

1

R , 70 byte

p=paste
function(w,h)p(rep(p(rep('[]',w),collapse=''),h),collapse='
')

Provalo online!

Restituisce una funzione anonima che costruisce e restituisce la stringa.

45 byte, non conforme

function(w,h)write(matrix('[]',w,h),'',w,,'')

Una funzione anonima che stampa la stringa nel formato desiderato.

Prova questo online


1

Japt , 7 byte

6 byte di codice, +1 per la -Rbandiera.

VÆç"[]

Non funziona nell'ultima versione a causa di un bug con ç, ma funziona in commitf619c52 . Provalo online!

Spiegazione

VÆ   ç"[]
VoX{Uç"[]"}  // Ungolfed
             // Implicit: U, V = input integers
VoX{      }  // Create the range [0...V) and replace each item X with
    Uç"[]"   //   U copies of the string "[]".
-R           // Join the result with newlines.
             // Implicit: output result of last expression


1

QBIC , 14 byte

[:|?[:|?@[]`';

Spiegazione:

[:|     FOR a = 1 to (read input from cmd line)
?       PRINT a newlne
[:|     FOR c = 1 to (read input from cmd line)
?@[]`   PRINT A$ (containing the box)
';         and inject a semicolon in the compiled QBasic code to suppress newlines

Questo prende i suoi argomenti nell'ordine di #rows, #cols. L'output inizia con una nuova riga.




1

C #, 78 byte

(w,h)=>"".PadLeft(h).Replace(" ","".PadLeft(w).Replace(" ","[]")+'\n').Trim();

Esegui in C # Pad

This is shorter than with for-loops and I'm not aware of any function in C# which can repeat with less code.



1

JavaScript (ES6), 43 36 bytes

From the comments, a trailing newline is now permitted.

w=>h=>("[]".repeat(w)+`
`).repeat(h)

Try it

f=
w=>h=>("[]".repeat(w)+`
`).repeat(h)
oninput=_=>o.innerText=f(+i.value)(+j.value);o.innerText=f(i.value=2)(j.value=2)
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
<label for=i>w: </label><input id=i type=number><label for=j>h: </label><input id=j type=number><pre id=o>



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.