Output diagramma visivo dell'immagine


22

Scrivi un programma che inserisca le dimensioni di un dipinto, la larghezza della stuoia e la larghezza della cornice per un ritratto incorniciato. Il programma dovrebbe generare un diagramma usando il simbolo Xper la pittura, +per la stuoia e #per l'inquadratura. I simboli devono essere separati da spazio. Lo spazio bianco finale è corretto, purché l'output corrisponda visivamente ai criteri. Gli ingressi possono essere 0.

INGRESSO: 3 2 1 2 (Larghezza, Altezza, Larghezza opaca, Larghezza cornice)

PRODUZIONE:

I primi 3 e 2 sono la larghezza e l'altezza della pittura.  1 è la larghezza opaca attorno ad esso.  2 è la larghezza della cornice attorno a tutto.

In forma di testo:

# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + X X X + # #
# # + X X X + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

Il codice vincente completa le condizioni nei byte meno possibili.


2
Bella sfida! Per sfide future potresti voler usare The Sandbox
MilkyWay90 il

2
ti dispiace se l'ingresso è in un ordine diverso?
vityavv

1
Possiamo restituire un elenco di stringhe?
MilkyWay90

5
Qualcuno degli ingressi può essere zero?
Laikoni

1
Possiamo avere uno spazio alla fine di ogni riga?
Luis Mendo,

Risposte:


5

Python 2 , 98 byte

w,h,a,b=input()
a*='+'
b*='#'
for c in b+a+h*'X'+a+b:print' '.join(min(c,d)for d in b+a+w*'X'+a+b)

Provalo online!

Stampa una griglia separata dallo spazio, seguendo rigorosamente le specifiche. Sono divertito che *=viene utilizzato per convertire ae bda numeri a stringhe.

Python 3 può salvare alcuni byte evitando ' '.join, forse di più usando f-string ed espressioni di assegnazione. Grazie a Jo King per -2 byte.

Python 3 , 93 byte

def f(w,h,a,b):a*='+';b*='#';[print(*[min(c,d)for d in b+a+w*'X'+a+b])for c in b+a+h*'X'+a+b]

Provalo online!


Sono stato superato! Bel lavoro, sembra piuttosto golfato
MilkyWay90

Bel golf! Molto intelligente.
George Harris,

4

JavaScript (ES6),  118 113  107 byte

(w,h,M,F)=>(g=(c,n)=>'01210'.replace(/./g,i=>c(i).repeat([F,M,n][i])))(y=>g(x=>'#+X'[x<y?x:y]+' ',w)+`
`,h)

Provalo online!

Commentate

(w, h, M, F) => (       // given the 4 input variables
  g = (                 // g = helper function taking:
    c,                  //   c = callback function returning a string to repeat
    n                   //   n = number of times the painting part must be repeated
  ) =>                  //
    '01210'             // string describing the picture structure, with:
    .replace(           //   0 = frame, 1 = matte, 2 = painting
      /./g,             // for each character in the above string:
      i =>              //   i = identifier of the current area
        c(i)            //   invoke the callback function
        .repeat         //   and repeat the result ...
        ([F, M, n][i])  //   ... either F, M or n times
    )                   // end of replace()
)(                      // outer call to g:
  y =>                  //   callback function taking y:
    g(                  //     inner call to g:
      x =>              //       callback function taking x:
        '#+X'           //         figure out which character to use
        [x < y ? x : y] //         according to the current position
        + ' ',          //         append a space
      w                 //       repeat the painting part w times
    )                   //     end of inner call
    + '\n',             //     append a line feed
  h                     //   repeat the painting part h times
)                       // end of outer call

3

MATL , 24 byte

&l,ithYaQ]'#+X'w)TFX*cYv

L'input è: Altezza, Larghezza, Larghezza opaca, Larghezza cornice.

Provalo online!

Spiegazione

&l      % Take height and width implicitly. Push matrix of that size with all
        % entries equal to 1
,       % Do twice
  i     %   Take input
  th    %   Duplicate, concatenate: gives a 1×2 vector with the number repeated
  Ya    %   Pad matrix with those many zeros vertically and horizontally
  Q     %   Add 1 to each entry 
]       % End
'#+X'   % Push this string
w)      % Index into the string with the padded matrix
TF      % Push row vector [1 0]
X*      % Kronecker product. This inserts columns of zeros
c       % Convert to char again. Char 0 is will be displayed as space
Yv      % Remove trailing spaces in each line. Implicitly display


2

Carbone , 48 47 44 byte

≔×NXθ≔×NXηFE+#×Nι«≔⁺ι⁺θιθ≔⁺ι⁺ηιη»Eη⪫⭆θ⌊⟦ιλ⟧ 

Provalo online! Il collegamento è alla versione dettagliata del codice. Nota: spazio finale. Modifica: ora utilizza l'algoritmo di @ xnor. Spiegazione:

≔×NXθ≔×NXη

Inserisci la larghezza e l'altezza e convertili in stringhe di Xs.

FE+#×Nι

Passa sopra i caratteri +e #, convertendoli in stringhe di lunghezza fornite dai restanti due input. Quindi avvolgi queste due stringhe.

«≔⁺ι⁺θιθ≔⁺ι⁺ηιη»

Prefisso e suffisso il dipinto con le corde per la stuoia e l'inquadratura.

Eη⪫⭆θ⌊⟦ιλ⟧ 

Passa sopra le stringhe, prendendo il minimo dei caratteri orizzontali e verticali, quindi spaziando due volte le righe, stampando implicitamente ciascuna riga sulla propria riga.


2

05AB1E (legacy) / 05AB1E --no-lazy , 32 31 byte

и'Xׄ+#vyI©×UεX.ø}®FDнgy×.ø]€S»

Accetta l'input nell'ordine height, width, matte, frame. Se l'ordine di input specificato nella sfida è rigoroso (ancora in attesa di verifica dell'OP), è spossibile aggiungere un vantaggio (swap) per +1 byte.

Richiesto il --no-lazyflag del compilatore Elixir nella nuova versione di 05AB1E, poiché Elixir ha un comportamento strano a causa della valutazione pigra per le mappe / i loop nidificati ( qui il risultato senza questo flag ).

Provalo online nella versione legacy di 05AB1E.
Provalo online nella nuova versione di 05AB1E con --no-lazyflag aggiunto .

Spiegazione:

и              # Repeat the second (implicit) input the first (implicit) input amount of
               # times as list
 'X×          '# Repeat "X" that many times
„+#v           # Loop `y` over the characters ["+","#"]:
    y          #  Push character `y`
     I         #  Push the next input (matte in the first iteration; frame in the second)
      ©        #  And store it in the register (without popping)
       ×       #  Repeat character `y` that input amount of times
        U      #  Pop and store that string in variable `X`
    εX.ø}      #  Surround each string in the list with string `X`
    ®F         #  Inner loop the value from the register amount of times:
      Dнg      #   Get the new width by taking the length of the first string
         y×    #   Repeat character `y` that many times
             #   And surround the list with this leading and trailing string
   ]           # Close both the inner and outer loops
    S         # Convert each inner string to a list of characters
      »        # Join every list of characters by spaces, and then every string by newlines
               # (and output the result implicitly)


1

Tela , 24 byte

X;«[lx*e⤢}
X×*+⁸#⁸ *J ×O

Provalo qui!

Dovrebbe essere più corto di 5 byte, ma non perché Canvas è difettoso.


1

R , 119 byte

function(w,h,m,f)write(Reduce(function(x,y)rbind(y,cbind(y,x,y),y),rep(c("+","#"),c(m,f)),matrix("X",w,h)),1,w+2*f+2*m)

Provalo online!


1

Python 3.8 (pre-release) , 116 115 113 byte

lambda a,b,c,d:"\n".join((g:=['#'*(a+2*c+2*d)]*d+[(h:='#'*d)+'+'*(a+c*2)+h]*c)+[h+'+'*c+'X'*a+'+'*c+h]*b+g[::-1])

Provalo online!

Il primo tentativo di giocare a golf sarà presto migliorato. aè larghezza, bè altezza, cè larghezza opaca e dlarghezza del telaio.

-1 byte usando l' :=operatore per definire hcomee * d

-2 byte grazie a Jo King che mi ha suggerito di rimuovere i parametri e ef

SPIEGAZIONE:

lambda a,b,c,d:          Define a lambda which takes in arguments a, b, c, and d (The width of the painting, the height of the painting, the padding of the matte, and the padding of the frame width, respectively).
    "\n".join(                       Turn the list into a string, where each element is separated by newlines
        (g:=                         Define g as (while still evaling the lists)...
            ['#'*(a+2*c+2*d)]*d+       Form the top rows (the ones filled with hashtags)
            [(h:='#'*d)+'+'*(a+c*2)+h]*c Form the middle-top rows (uses := to golf this section)
        )+
        [h+'+'*c+'X'*a+'+'*c+h]*b+       Form the middle row
        g[::-1]                      Uses g to golf the code (forms the entire middle-bottom-to-bottom)
    )

Rimuovere il ecompito ti fa risparmiare due byte, il fcompito non ti fa risparmiare nulla
Jo King

@JoKing Oh wow, ho dimenticato di rimuovere i compiti ee fdopo aver scoperto la gscorciatoia
MilkyWay90

0

Javascript, 158 byte

(w,h,m,f)=>(q="repeat",(z=("#"[q](w+2*(m+f)))+`
`)[q](f))+(x=((e="#"[q](f))+(r="+"[q](m))+(t="+"[q](w))+r+e+`
`)[q](m))+(e+r+"X"[q](w)+r+e+`
`)[q](h)+x+z)

Probabilmente può essere ridotto un po '

f=

(w,h,m,f)=>(q="repeat",(z=("# "[q](w+2*(m+f))+`
`)[q](f))+(x=((e="# "[q](f))+(r="+ "[q](m))+(t="+ "[q](w))+r+e+`
`)[q](m))+(e+r+"X "[q](w)+r+e+`
`)[q](h)+x+z)

console.log(f(3,2,1,2))


0

Perl 6 , 98 byte

{map(&min,[X] map (($_='#'x$^d~'+'x$^c)~'X'x*~.flip).comb,$^a,$^b).rotor($b+2*($c+$d)).join("\n")}

Provalo online!

Questa è una porta della risposta Python di xnor .

Perl 6 , 115 byte

->\a,\b,\c,\d{$_=['#'xx$!*2+a]xx($!=c+d)*2+b;.[d..^*-d;d..^a+$!+c]='+'xx*;.[$!..^*-$!;$!..^a+$!]='X'xx*;.join("
")}

Provalo online!

Blocco di codice anonimo approssimativamente golfato utilizzando l'assegnazione dell'elenco multidimensionale di Perl 6. Ad esempio, @a[1;2] = 'X';assegnerà 'X'all'elemento con indice 2 dall'elenco con indice 1 e @a[1,2,3;3,4,5]='X'xx 9;sostituirà tutti gli elementi con indici 3,4,5degli elenchi con indici 1,2,3con 'X'.

Spiegazione:

In primo luogo, abbiamo inizializzare la lista come a+2*(c+d)dal b+2*(c+d)rettangolo di #s.

$_=['#'xx$!*2+a]xx($!=c+d)*2+a;
State:
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #

Quindi assegniamo il rettangolo interno di +s

.[d..^*-d;d..^a+$!+c]='+'xx*;
State:
# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + + + + + # #
# # + + + + + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

Infine, il rettangolo più interno di Xs.

.[$!..^*-$!;$!..^a+$!]='X'xx*;
# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + X X X + # #
# # + X X X + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

0

Gelatina , 35 31 28 24 byte

Dịx@“#+X+#”
⁽-Fç«þ⁽-ȥç$G

Provalo online!

Prende l'input nel frame dell'ordine, opaco, larghezza, altezza; separato da virgola. Stampa l'immagine in formato ASCII con cornice e mascherino. Se l'ordine di input è rigoroso, dovrei aggiungere più byte (come per il mio post originale).

Coppia di golf basati sulla risposta di @ EriktheOutgolfer; Avevo capito che i personaggi erano in ordine ASCII ma non avevo pensato al modo migliore per sfruttarlo, e me ne ero dimenticato G. La sua è comunque una risposta migliore!


Non ho mai programmato in Jelly, ma sicuramente 43134,43234 possono essere compressi? EDIT: ho bisogno di imparare a leggere, dici che possono davvero essere codificati in 4 byte ciascuno. Ma cosa c'entra l'ordine di input se questi numeri possono essere codificati o no? : S
Kevin Cruijssen,

@KevinCruijssen il numero intero massimo che può essere codificato utilizzando la sintassi a due byte è 32250; poiché entrambi superano il fatto che non riesco a salvare i byte. Per ora suppongo che posso scambiare le cose e ripristinare se non è permesso!
Nick Kennedy,

Ah ok, capisco. 43134avranno bisogno di 3 caratteri di codifica, che includendo un carattere iniziale / finale per indicare che è codificato avrà anche 5 byte. E forse Jelly ha un duplicato di qualche tipo, dal momento che il secondo numero è 100 più grande del primo? Non sei sicuro se le azioni spingono 43134, duplicano, spingono 100, più, la coppia è possibile e più corta in Jelly?
Kevin Cruijssen,

@KevinCruijssen Inizialmente ho provato a usare +0.100 che non ne salva. Penso che potrei usare una catena nilad per usare il fatto che in un nilad ³ è 100, ma se mi è permesso di riordinare gli input gli 250 di base sono migliori
Nick Kennedy

0

Perl 5, 115 byte

$_=(X x$F[0].$/)x$F[1];sub F{s,^|\z,/.*/;$_[0]x"@+".$/,ge,s/^|(?=
)/$_[0]/gm while$_[1]--}F('+',$F[2]);F('#',$F[3])

TIO


0

PowerShell , 132 byte

param($w,$h,$m,$f)filter l{"$(,'#'*$f+,$_[0]*$m+,$_[1]*$w+,$_[0]*$m+,'#'*$f)"}($a=@('##'|l)*$f)
($b=@('++'|l)*$m)
@('+X'|l)*$h
$b
$a

Provalo online!

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.