Fammi un s'more!


19

Fammi un s'more ! Ti dico la larghezza, la quantità di cracker Graham, la quantità di cioccolato e la quantità di marshmallow. Un esempio:

Ingresso:

Larghezza: 10 Graham: 3 Cioccolato: 2 Marshmallow: 1.

Produzione:

GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG

È così facile? Ehm ... si.

Si noti che l'input dovrebbe essere un elenco di argomenti per una funzione o un programma, non una stringa. Puoi scegliere prima Larghezza, poi Graham, ma qualsiasi ordine va bene.

Casi di test completi se sei interessato.

Stack snippet (per test, ecc.)

Questo per testare l'output.

var smore = function(width, graham, chocolate, marshmallow){
	return ("G".repeat(width) + "\n").repeat(graham) + 
	("C".repeat(width) + "\n").repeat(chocolate) + 
	("M".repeat(width) + "\n").repeat(marshmallow) + 
	("G".repeat(width) + "\n").repeat(graham);
};
Snippetify(smore);
<script src="https://programmer5000.com/snippetify.min.js"></script>
Width: <input type = "number">
Graham: <input type = "number">
Chocolate: <input type = "number">
Marshmallow: <input type = "number">
<button>Try it out!</button>
<pre data-output></pre>

Appunti:

  • È possibile includere una nuova riga finale alla fine dell'ultima riga. Puoi anche usare una \anziché una nuova riga.
  • Questo è .
  • Qualsiasi domanda? Commento sotto:

21
Ho modificato il tuo link Let Me Google That For You. Non è stato davvero divertente.
Level River St

1
@FelipeNardiBatista sì.
programmatore

1
Alcune risposte assumono un ordine e un formato di input flessibili (come al solito in PPCG), ma la sfida sembra richiedere un ordine specifico ed escludere le stringhe (non sono sicuro di cosa significhi). Puoi chiarire?
Luis Mendo,

2
Grazie per il chiarimento. Dovresti quindi riformulare la frase, l'input dovrebbe essere un elenco di argomenti per una funzione o un programma, non una stringa, con il primo come larghezza, poi Graham, ecc . Personalmente direi qualcosa del tipo "Il formato di input è flessibile come al solito"
Luis Mendo,

4
@ programmer5000 ma perché? Se hanno effettuato il downgrade, è probabile che il 90% sia perché pensano che sia una sfida noiosa e banale. Inoltre, è abbastanza scortese dire alle persone di spiegare o ritrarre. Hanno il diritto di votare senza commenti.
Rɪᴋᴇʀ

Risposte:


2

Gelatina , 11 byte

ṁ4“GCMG”x×Y

Provalo online!

Come funziona

ṁ4“GCMG”x×Y  Main link. Left argument: g, c, m. Right argument: w

ṁ4           Mold 4; repeat g, c, m until length 4 is reached. Yields [g, c, m, g].
  “GCMG”x    Repeat 'G' g times, then 'C' c times, then 'M' m times, and finally
             'G' g times. This yields a string.
         ×   Multiply each character w times. This is essentially a bug, but
             Jelly's × behaves like Python's * (and vectorizes), so it can be
             abused for character repetition.
          Y  Join, separating by linefeeds.


8

05AB1E , 21 19 19 byte

"GCMG"S×|D«‚øvy`.D»

Provalo online!

-2 grazie alla mia supervisione ed Emigna.

"GCMG"S×            # Push GCMG, separate, duplicate n times.
        |D«         # Push rest of inputs, doubled.
           ‚ø       # Wrap GCMG array and input array, then zip them into pairs.
             vy`.D» # For each pair, print n of G/C/M/G.

(Vedi la risposta di Emigna, è meglio: /codegolf//a/116787/59376 )


1
Sembra che tu abbia lasciato accidentalmente un ©lì dentro.
Emigna,

1
Puoi anche sostituirlo ¬¸con Dpoiché gli elementi extra vengono persi quando si zip.
Emigna,

@Emigna Mi piace e odio quella funzionalità.
Magic Octopus Urn,

Sì, spesso è molto fastidioso ma ogni tanto (come ora) diventa utile :)
Emigna,

8

JavaScript (ES6), 71 byte

(W,G,C,M)=>[...'GCMG'].map(X=>`${X.repeat(W)}
`.repeat(eval(X))).join``

Woohoo, batti 3 altre risposte JavaScript!


Bello, molto bello - ottiene il mio voto.
Shaggy,

7

MATL , 17 byte

'GCMG'iK:)Y"!liX"

Il formato di input è: primo input [G, C, M], secondo input W.

Provalo online!

Spiegazione con esempio

Considerare input [3 2 1] e 10.

'GCMG' % Push this string
       % STACK: 'GCMG'
i      % Take first input: array of three numbers
       % STACK: 'GCMG', [3 2 1]
K:     % Push [1 2 3 4]
       % STACK: 'GCMG', [3 2 1], [1 2 3 4]
)      % Index (modular, 1-based). This repeats the first entry of the input array
       % STACK: 'GCMG', [3 2 1 3]
Y"     % Run-length decoding
       % STACK: 'GGGCCMGGG'
!      % Transpose. Gives a column vector of chars
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G']
l      % Push 1
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1
i      % Take second input: number
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1, 10
X"     % Repeat the specified numbers of times along first and second dimensions
       % STACK: ['GGGGGGGGGG';'GGGGGGGGGG';'GGGGGGGGGG';'CCCCCCCCCC';...;'GGGGGGGGGG']
       % Implicitly display

7

C # , 204 byte


golfed

(w,g,c,m)=>{string G="\n".PadLeft(++w,'G'),C="\n".PadLeft(w,'C'),M="\n".PadLeft(w,'M'),o="".PadLeft(g,'G');o+="".PadLeft(m,'M')+"".PadLeft(c,'C')+o;return o.Replace("G",G).Replace("C",C).Replace("M",M);};

Ungolfed

( w, g, c, m ) => {
   string
      G = "\n".PadLeft( ++w, 'G' ),
      C = "\n".PadLeft( w, 'C' ),
      M = "\n".PadLeft( w, 'M' ),
      o = "".PadLeft( g, 'G' );

   o +=
      "".PadLeft( m, 'M' ) +
      "".PadLeft( c, 'C' ) +
      o;

   return o
      .Replace( "G", G )
      .Replace( "C", C )
      .Replace( "M", M );
};

Leggibile non golfato

// Function with 4 parameters
//   w : Width
//   g : Graham
//   c : Chocolate
//   m : Marshmallow
( w, g, c, m ) => {

   // Initialization of vars with the contents
   //    of each line, with a new line at the end
   string
      G = "\n".PadLeft( ++w, 'G' ),
      C = "\n".PadLeft( w, 'C' ),
      M = "\n".PadLeft( w, 'M' ),

      // Trick to reduce the byte count
      //   Initialize the output with n 'G's
      o = "".PadLeft( g, 'G' );

   // Add again n 'M's and n 'C's
   //   Append the 'G's at the end.
   o +=
      "".PadLeft( m, 'M' ) +
      "".PadLeft( c, 'C' ) +
      o;

   // Replce every instance of 'G'/'C'/'M'
   //    with the full line
   return o
      .Replace( "G", G )
      .Replace( "C", C )
      .Replace( "M", M );
};

Codice completo

using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<Int32, Int32, Int32, Int32, String> f = ( w, g, c, m ) => {
            string
               G = "\n".PadLeft( ++w, 'G' ),
               C = "\n".PadLeft( w, 'C' ),
               M = "\n".PadLeft( w, 'M' ),
               o = "".PadLeft( g, 'G' );

            o +=
               "".PadLeft( m, 'M' ) +
               "".PadLeft( c, 'C' ) +
               o;

            return o
               .Replace( "G", G )
               .Replace( "C", C )
               .Replace( "M", M );
         };

         List<Tuple<Int32, Int32, Int32, Int32>>
            testCases = new List<Tuple<Int32, Int32, Int32, Int32>>() {
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 1 ),
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 2 ),
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 2, 1 ),
               //
               // ...
               //
               // The link above contains the code ready to run
               //    and with every test from the pastebin link
               //
               // Yes, it contains 342 tests ready to run.
               //
               // I can barely fit every test on a 1080p screen...
               //    ... and there's 6 tests per line... Jebus...
               //
            };

         foreach( var testCase in testCases ) {
            Console.WriteLine( $"Input:\nWidth: {testCase.Item1,3} Graham: {testCase.Item2,3} Chocolate: {testCase.Item3,3} Marshmellow: {testCase.Item4,3}\nOutput:\n{f( testCase.Item1, testCase.Item2, testCase.Item3, testCase.Item4 )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Uscite

  • v1.0 - 204 bytes- Soluzione iniziale.

Appunti


Apprezzato! : D
auhmaan,

7

05AB1E , 17 16 byte

1 byte salvato grazie al carusocomputing .

"GCMG"S×vy²Nè.D»

Provalo online!

L'ordine di input è W, [G,C,M]

Spiegazione

10, [3,2,1] usato come esempio.

"GCMG"S           # push the list ['G','C','M','G']
       ×          # repeat each W times
                  # STACK: ['GGGGGGGGGG', 'CCCCCCCCCC', 'MMMMMMMMMM', 'GGGGGGGGGG']
        v         # for each [string, index] y,N in the list
          ²Nè     # get the amount of layers at index N from the [G,C,M] list
         y   .D   # duplicate the string y that many times
               »  # join strings by newlines

1
"GCMG"S×vy²Nè.D»poteri gemello-meraviglia, attiva! Forma del codice 05AB1E! Inoltre, gli argomenti vengono scambiati, ma è ancora 16.
Magic Octopus Urn

@carusocomputing: ha il vantaggio di non lasciare cazzate non stampate in pila, ma mi sembra altrettanto irriducibile.
Emigna,

1
È ancora 1 byte in meno e batterà il tuo pareggio con MATL;).
Magic Octopus Urn,

@carusocomputing: Oooh, quando è successo? Ero sicuro che fossero 17 quando l'ho visto. Bello! ;)
Emigna,

Pubblico spesso cose stupide e le faccio modifiche 1 minuto dopo mi rendo conto di essere un idiota.
Magic Octopus Urn,

6

Rubino, 47 byte

->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r}

grazie a ventero

Rubino, 51 byte

->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}

Chiama in questo modo:

f=->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}

f[10,3,2,1]

->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r}è un po 'più corto
Ventero,

5

PowerShell , 49 byte

$a,$b=$args;0..2+0|%{,("$('GCM'[$_])"*$a)*$b[$_]}

Provalo online!

Accetta input come quattro argomenti della riga di comando width graham chocolate marshmallow, memorizza il primo in $ae il resto in $b(implicitamente come un array). Loop da oltre la gamma 0,1,2,0. Ogni ciclo, lo indicizziamo in stringa GCM, lo ripetiamo charcome una stringa e lo moltiplichiamo per $a(la larghezza), e quindi usando l'operatore virgola ,, lo trasforma in un array moltiplicando l'indice appropriato di $b(cioè, quante strati). Questi array di stringhe risultanti vengono tutti lasciati sulla pipeline e l'output è implicito, con una nuova riga tra gli elementi.


5

C, 108 105 byte

Grazie a @Quentin per aver salvato 3 byte!

#define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c);
i,j;f(w,g,c,m){i=g;F(i,71)F(c,67)F(m,77)F(g,71)}

Provalo online!


1
#define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c);salva tre byte :)
Quentin,

@Quentin Grazie! Mi chiedo perché in primo luogo mi sia perso :)
Steadybox,

4

Lotto, 146 byte

@set s=
@for /l %%i in (1,1,%1)do @call set s=G%%s%%
@for %%w in (%2.%s% %3.%s:G=C% %4.%s:G=M% %2.%s%)do @for /l %%i in (1,1,%%~nw)do @echo%%~xw

Si basa sul comportamento oscuro del fatto echoche spesso può ignorare il simbolo tra echoe il testo da echeggiare per far collassare i quattro anelli in un ciclo nidificato.


4

V , 22 byte

éGÄÀäjMoC
MÀÄkÀÄHdêÀP

Provalo online!

hexdump:

00000000: e947 c4c0 e46a 4d6f 430a 4d1b c0c4 6bc0  .G...jMoC.M...k.
00000010: c448 64ea c050                           .Hd..P

L'ordine di input è

Graham, Marshmallow, Chocolate, Width

Spiegazione:

éG                  " Insert 'G'
  Ä                 " Duplicate this line
   Àäj              " *arg1* times, duplicate this line and the line below it
      M             " Move to the middle line
       o            " Open up a newline, and enter insert mode
        C<cr>M<esc> " Insert 'C\nM'
ÀÄ                  " Make *arg2* copies of this line (Marshmallow)
  k                 " Move up one line
   ÀÄ               " Make *arg3* copies of this line (Chocolate)
     H              " Move to the first line
      dê            " Delete this column
        ÀP          " And paste it horizontally *arg4* times

Potresti aggiungere una spiegazione?
programmatore

@ programmer5000 Certo! Guarda la mia modifica
DJMcMayhem

4

Excel, 104 byte

Oh ragazzo! Una formula che richiede interruzioni di riga.

=REPT(REPT("G",A1)&"
",A2)&REPT(REPT("C",A1)&"
",A3)&REPT(REPT("M",A1)&"
",A4)&REPT(REPT("G",A1)&"
",A2)

A1ha Larghezza
A2ha Graham
A3ha Cioccolato
A4ha Malva


Se è consentita la pre-formattazione, è possibile formattare la cella per il testo verticale e abbreviare la formula a 65 byte:

=REPT(REPT("G",A2)&REPT("C",A3)&REPT("M",A4)&REPT("G",A2)&"
",A1)

4

Gelatina , 13 byte

“GCM”ẋ"ṁ4Fẋ€Y

Un programma diadico. Gli input sono: [Graham's, Chocolates, Marshmallows], Width.

Provalo online!

Come?

“GCM”ẋ"ṁ4Fẋ€Y - Main link: [g,c,m], w    e.g. [1,2,1], 2
“GCM”         - literal ['G', 'C', 'M']
      "       - zip that and [g,c,m] with the dyadic operation:
     ẋ        -     repeat list               [['G'],['C','C'],['M']]
       ṁ4     - mould like [1,2,3,4]          [['G'],['C','C'],['M'],['G']]
         F    - flatten                       ['G','C','C','M','G']
          ẋ€  - repeat €ach w times           [['G','G'],['C','C'],['C','C'],['M','M'],['G','G']]
            Y - join with line feeds          ['G','G','\n','C','C','\n','C','C','\n','M','M','\n','G','G']
              - implicit print                GG
                                              CC
                                              CC
                                              MM
                                              GG

3

PHP, 85 byte

for($m=$argv;$i++<4;)for($c=$m[_2342[$i]]*$m[1];$c;)echo$c--%$m[1]?"":"\n",_GCMG[$i];

o

for($m=$argv;$i++<4;)for($c=$m[_2342[$i]];$c--;)echo"\n".str_pad("",$m[1],_GCMG[$i]);

Versioni online

PHP, 96 byte

<?[$n,$w,$G,$C,$M]=$argv;for(;$i<4;$i++)for($t=${"$n[$i]"};$t--;)echo"\n".str_pad("",$w,$n[$i]);

Versione online

allargato

[$n,$w,$G,$C,$M]=$argv; # $argv[0] must contain a file beginning with "GCMG"
for(;$i<4;$i++) # Take the first 4 values of the filename
for($t=${"$n[$i]"};$t--;) # How many rows should be printed
echo"\n".str_pad("",$w,$n[$i]); # print $w times the actual letter

3

05AB1E , 14 byte

Codice:

…GCM‚øü׬)˜S×»

Utilizza la codifica CP-1252 . Provalo online!

Spiegazione:

…GCM              # Push the string "GCM"
    ‚             # Wrap with the input
     ø            # Transpose the array
      ü×          # Compute the string product of each element (['A', 3] --> 'AAA')
        ¬)˜       # Get the last element and append to the list
           S      # Split the list
            ×     # Vectorized string multiplication with the second input
             »    # Join by newlines and implicitly print

3

Python 2 ,6757 byte

(Modifica: ora che sono consentite le matrici, non è necessario unire newline.)

def s(w,g,c,m):g=['G'*w]*g;print g+['C'*w]*c+['M'*w]*m+g

3

C # (150 byte)

void S(int w,int g,int c,int m){P(w,g,'G');P(w,c,'C');P(w,m,'M');P(w,g,'G');}void P(int w,int i,char c){while(i-->0)Console.Write("\n".PadLeft(w,c));}

Ungolfed:

void SMores(int w, int g, int c, int m)
{
    Print(w,g,'G');
    Print(w,c,'C');
    Print(w,m,'M');
    Print(w,g,'G');
}
void Print(int w, int i, char c)
{
    while(i-->0)
        Console.Write("\n".PadLeft(w,c));
}

3

Java, 138 byte

String s(int w,int g,int c,int m){String b="";int i=-g-c,j;for(;i++<g+m;){for(j=0;j++<w;)b+=i<=-c|i>m?'G':i<=0?'C':'M';b+="\n";}return b;}

Provalo online!

Spiegazione:

String s(int w, int g, int c, int m) {
    String b = "";
    int i = -g - c, j;              // i is the layer
    for (; i++ < g + m;) {          // Repeat (G+C+M+G) times, starting from -g-c to m+g 
                                    //Layer 0 is the last chocolate layer

        for (j = 0; j++ < w;) {     // Repeat W times
            b += 
                i <= -c | i > m ? 'G': //If before the chocolate or after the marshmellow, output a G
                i <= 0 ? 'C' :      // Else if equal or before last chocolate layer output C
                'M';                //Otherwise output an M
        }
        b += "\n";
    }
    return b;
}


3

Rapido, 138 137 134 130 byte

Salvato 7 byte grazie a @Kevin

let f=String.init(repeating:count:)
let r={w,g,c,m in f(f("G",w)+"\n",g)+f(f("C",w)+"\n",c)+f(f("M",w)+"\n",m)+f(f("G",w)+"\n",g)}

Due funzioni che restituiscono il valore atteso: fè una funzione di supporto ed rè l'attuale funzione simile a lamdba che genera l'output. Uso: print(r(10,3,2,1))

Controlla!


Puoi salvare diversi caratteri semplicemente facendo riferimento direttamente all'inizializzatore di stringhe ( var f=String.init(repeating:count:);). E non ti salva alcun personaggio ma non costa nulla, quindi dovrebbero essere entrambi let.
Kevin,

E altri 3 rilasciando gli argomenti espliciti in r( let r={f(f("G",$0)+"\n",$1)+f(f("C",$0)+"\n",$2)+f(f("M",$0)+"\n",$3)+f(f("G",$0)+"\n",$1)})
Kevin,

@Kevin Grazie, non avevo idea che tu potessi inizializzare un valore su qualcosa del genere: f=String.init(repeating:count:)...
Mr. Xcoder,

@Kevin quando si tratta del tuo secondo suggerimento, sembra che superi il numero di byte in UTF-8, controllato il conteggio dei byte su TIO, non so perché
Mr. Xcoder


2

JavaScript (ES6), 91 byte

Include newline finale.

f=

(w,g,c,m)=>(b=(`G`[r=`repeat`](w)+`
`)[r](g))+(`C`[r](w)+`
`)[r](c)+(`M`[r](w)+`
`)[r](m)+b

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


2

JS (ES6), 87 byte

x=(w,g,c,m)=>(f=>f`Gg`+f`Cc`+f`Mm`+f`Gg`)(([[x,y]])=>(x.repeat(w)+`
`).repeat(eval(y)))

xagisce come una funzione lambda autonoma. Il risultato ha una nuova riga finale.

Prova in uno snippet:


2

C, 90 byte (basato sulla risposta di Steadybox )

Rinominato le variabili e sfruttato l'operatore preprocessore di stringificazione per ridurre i parametri macro. Spero di pubblicare questa idea perché la sua risposta va bene :)

#define F(x)for(i=x;i--;puts(""))for(j=w;j--;)printf(#x);
i,j;f(w,G,C,M){F(G)F(C)F(M)F(G)}

Collegamento TIO


Voterebbe, ma colpirà il limite di voto :(
programmer5000,

2

F # ( 148 99 byte)

let s w q="GCMG"|>Seq.iteri(fun i c->for j in 1..(q|>Seq.item(i%3))do printf"%A"("".PadLeft(w,c)))

Uso:

s 10 [2;3;4]

Ungolfed:

let smores width quantities =
    "GCMG"
    |>Seq.iteri(fun i char ->
        for j in 1..(quantities|>Seq.nth(i%3))
            do printf "%A" ("".PadLeft(width,char))) 

Sono ancora nuovo in F #, quindi se ho fatto qualcosa di strano o stupido, per favore fatemelo sapere.


Un collegamento a F # sarebbe carino.
programmatore

2

JavaScript ES6, 69 68 66 byte

Grazie @Arnauld per giocare a golf a un byte

a=>b=>"GCMG".replace(/./g,(c,i)=>`${c.repeat(a)}
`.repeat(b[i%3]))

Provalo online!

Spiegazione

Riceve input in formato curry (Width)([Graham,Chocolate,Marshmallow])

L'utilizzo .replace(/./g,...)sostituisce ogni carattere nella stringa GCMGcon il valore restituito dalla funzione(c,i)=>`${c.repeat(a)} `.repeat(b[i%3])

`${c.repeat(a)} `crea ogni riga del cracker graham con una nuova riga aggiunta .repeat(b[i%3])ripete questa riga il numero richiesto di volte


L'utilizzo replace()salverebbe un byte:a=>"GCMG".replace(/./g,(c,i)=>`${c.repeat(a[0])}\n`.repeat(a[1+i%3]))
Arnauld

1

JS (ES6), 111 byte

n=`
`,G="G",C="C",M="M",r=(s,t)=>s.repeat(t),(w,g,c,m)=>r(r(G,w)+n,g)+r(r(C,w)+n,c)+r(r(M,w)+n,m)+r(r(G,w)+n,g)

1

Mathematica 102 byte (100 caratteri)

Ho sentito che gli s'mores integrati non usciranno fino alla V12.

s=StringRepeat;StringReplace[s@@@({Characters@"GCMG",#/.#[[4]]->#[[1]]})<>"",x_:>x~s~#[[4]]<>"\n"]&

Abbastanza semplice usando l'idea di costruire prima una colonna. I nomi di funzioni lunghe perdono 35 byte. L'unico simbolo a forma di scatola è in realtà un personaggio trasposto e andrà bene in Mathematica.

Utilizzo: %@{Graham, Chocolate, Marshmallows, Width} ad es %@{3, 2, 1, 11}


1

Java 7, 226 byte

String c(int w,int g,int c,int m){return x(w,'G',g)+x(w,'C',c)+x(w,'M',m)+x(w,'G',g);}String x(int w,char c,int x){String r="";for(;x-->0;r+=x(w,c));return r;}String x(int w,char c){String r="";for(;w-->0;r+=c);return r+"\n";}

OPPURE (anche 226 byte ):

String c(int w,int g,int c,int m){return x(w,71,g)+x(w,67,c)+x(w,77,m)+x(w,71,g);}String x(int...a){String r="";for(;a[2]-->0;r+=x(a[0],(char)a[1]));return r;}String x(int w,char c){String r="";for(;w-->0;r+=c);return r+"\n";}

Spiegazione:

String c(int w,int g,int c,int m){  // Main method with four integer parameters and String return-type
  return x(w,'G',g)                 //  Return all Graham-rows
        +x(w,'C',c)                 //   plus all Chocolate-rows
        +x(w,'M',m)                 //   Plus all Marshmallon-rows
        +x(w,'G',g);                //   Plus all Graham-rows again
}                                   // End of main method

String x(int w,char c,int x){       // Separate method (1) with two integers & character parameters and String return-type
  String r="";                      //  Result-String
  for(;x-->0;                       //  For the given amount of rows of a certain type
             r+=x(w,c)              //   Append the result-String with a row of the given character
  );                                //  End of for-loop (implicit / no body)
  return r;                         //  Return the result-String
}                                   // End of separate method (1)

String x(int w,char c){             // Separate method (2) with integer and character parameters and String return-type
  String r="";                      //  Result-String
  for(;w-->0;                       //  For the amount given as width
             r+=c                   //   Append the character to the row
  );                                //  End of for-loop (implicit / no body)
  return r+"\n";                    //  Return the result-String including a new-line
}                                   // End of separate method (2)

Codice di prova:

Provalo qui.

class M{
  String c(int w,int g,int c,int m){return x(w,'G',g)+x(w,'C',c)+x(w,'M',m)+x(w,'G',g);}String x(int w,char c,int x){String r="";for(;x-->0;r+=x(w,c));return r;}String x(int w,char c){String r="";for(;w-->0;r+=c);return r+"\n";}

  public static void main(String[] a){
    System.out.print(new M().c(10,3,2,1));
  }
}

Produzione:

GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG

1
Non male ... per java!
programmatore

1
@ programmer5000 Hehe, grazie! Mi piace giocare a golf in Java 7 (e talvolta 8), anche se non credo che potrà mai competere con altre risposte. L'unica volta in cui un po 'è stata in competizione con una risposta Java è stata con questa risposta a 8 byte e questa risposta a 19 byte , superando in realtà Python per la prima volta. ; p Anche se quelle lingue da golf con i loro invii da 1 o 2 byte lasciano Java nella polvere, ovviamente.
Kevin Cruijssen,

1

Haskell , 91 byte

import Data.List
(#)=replicate
f w g c m=intercalate"\n"$map(w#)$g#'G'++c#'C'++m#'M'++g#'G'

Dovrebbe essere abbastanza autoesplicativo. Poiché è stato notato in un commento che le matrici di caratteri sono consentite, ecco una versione di 58 byte che restituisce un elenco di stringhe (una per ogni livello):

(#)=replicate
f w g c m=map(w#)$g#'G'++c#'C'++m#'M'++g#'G'
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.