19
\$\begingroup\$

Make me a s'more! I tell you the width, the amount of graham cracker, the amount of chocolate, and the amount of marshmallow. An example:

Input:

Width: 10 Graham: 3 Chocolate: 2 Marshmallow: 1.

Output:

GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG

Is it that easy? Um... yes.

Note that the input should be a list of arguments to a function or a program, not a string. You might choose the first being Width, then Graham, but any order is fine.

Full test cases if you are interested.

Stack snippet (for testing, etc.)

This is to test the 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>

Notes:

  • You may include a trailing newline on the end of the last line. You may also use a \ instead of a newline.
  • This is .
  • Any questions? Comment below:
\$\endgroup\$
  • 21
    \$\begingroup\$ I edited out your Let Me Google That For You link. It really wasn't funny. \$\endgroup\$ – Level River St Apr 17 '17 at 13:47
  • 1
    \$\begingroup\$ @FelipeNardiBatista yes. \$\endgroup\$ – programmer5000 Apr 17 '17 at 14:30
  • 1
    \$\begingroup\$ Some answers are assuming flexible input order and format (as usual in PPCG), but the challenge seems to require a specific order and rule out strings (not sure what that means). Can you clarify? \$\endgroup\$ – Luis Mendo Apr 17 '17 at 14:34
  • 2
    \$\begingroup\$ Thanks for clarifying. You should then reword the sentence the input should be a list of arguments to a function or a program, not a string, with the first being Width, then Graham, etc. Personally I would say something like "Input format is flexible as usual" \$\endgroup\$ – Luis Mendo Apr 17 '17 at 14:36
  • 4
    \$\begingroup\$ @programmer5000 but why? If they downvoted, it's 90% likely it's because they think it's a boring and trivial challenge. Furthermore, it's quite rude to tell people to explain or retract. They have the right to downvote without comment. \$\endgroup\$ – Rɪᴋᴇʀ Apr 17 '17 at 16:12

40 Answers 40

2
\$\begingroup\$

Jelly, 11 bytes

ṁ4“GCMG”x×Y

Try it online!

How it works

ṁ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.
\$\endgroup\$
13
\$\begingroup\$

Python 2, 73 48 bytes

lambda w,g,c,m:zip(*['G'*g+'C'*c+'M'*m+'G'*g]*w)

Try it online!

Creates a transposed version of the answer, than transposes it to the correct format with zip(*l)

\$\endgroup\$
8
\$\begingroup\$

05AB1E, 21 19 19 bytes

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

Try it online!

-2 thanks to my oversight and 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.

(See Emigna's answer, it's better: https://codegolf.stackexchange.com/a/116787/59376)

\$\endgroup\$
  • 1
    \$\begingroup\$ You seem to have accidentally left a © in there. \$\endgroup\$ – Emigna Apr 17 '17 at 14:31
  • 1
    \$\begingroup\$ You could also replace ¬¸ with D as the extra elements are lost when you zip. \$\endgroup\$ – Emigna Apr 17 '17 at 14:33
  • \$\begingroup\$ @Emigna I both like and hate that functionality. \$\endgroup\$ – Magic Octopus Urn Apr 17 '17 at 14:56
  • \$\begingroup\$ Yes, it's often very annoying but now and then (like now) it becomes useful :) \$\endgroup\$ – Emigna Apr 17 '17 at 14:57
8
\$\begingroup\$

JavaScript (ES6), 71 bytes

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

Woohoo, beat 3 other JavaScript answers!

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

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

\$\endgroup\$
  • \$\begingroup\$ Nice, very nice - gets my vote. \$\endgroup\$ – Shaggy Apr 17 '17 at 22:00
7
\$\begingroup\$

MATL, 17 bytes

'GCMG'iK:)Y"!liX"

Input format is: first input [G, C, M], second input W.

Try it online!

Explanation with example

Consider inputs [3 2 1] and 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
\$\endgroup\$
7
\$\begingroup\$

C#, 204 bytes


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

Ungolfed readable

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

Full code

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

Releases

  • v1.0 - 204 bytes - Initial solution.

Notes

\$\endgroup\$
  • \$\begingroup\$ Appreciated! :D \$\endgroup\$ – auhmaan Apr 17 '17 at 15:04
7
\$\begingroup\$

05AB1E, 17 16 bytes

1 bytes saved thanks to carusocomputing.

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

Try it online!

Input order is W, [G,C,M]

Explanation

10, [3,2,1] used as example.

"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
\$\endgroup\$
  • 1
    \$\begingroup\$ "GCMG"S×vy²Nè.D» wonder-twin powers, activate! Form of, 05AB1E code! Also, arguments get swapped, but it's still 16. \$\endgroup\$ – Magic Octopus Urn Apr 17 '17 at 14:59
  • \$\begingroup\$ @carusocomputing: It has the benefit of not leaving unprinted crap on the stack, but it seems similarly irreducible to me. \$\endgroup\$ – Emigna Apr 17 '17 at 15:04
  • 1
    \$\begingroup\$ It's still 1 byte less and will beat your tie with MATL ;). \$\endgroup\$ – Magic Octopus Urn Apr 17 '17 at 15:37
  • \$\begingroup\$ @carusocomputing: Oooh, when did that happen? I was sure it was 17 when I saw it. Nice! ;) \$\endgroup\$ – Emigna Apr 17 '17 at 15:41
  • \$\begingroup\$ I often post stupid stuff and make edits to it 1 minute after I realize I'm being an idiot. \$\endgroup\$ – Magic Octopus Urn Apr 17 '17 at 17:14
6
\$\begingroup\$

Ruby, 47 bytes

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

thanks to ventero

Ruby, 51 bytes

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

Call like this:

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

f[10,3,2,1]
\$\endgroup\$
  • \$\begingroup\$ ->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r} is a bit shorter \$\endgroup\$ – Ventero Apr 17 '17 at 19:12
5
\$\begingroup\$

PowerShell, 49 bytes

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

Try it online!

Takes input as four command-line arguments, width graham chocolate marshmallow, stores the first into $a and the rest into $b (implicitly as an array). Loops from over the range 0,1,2,0. Each loop, we index into string GCM, re-cast that char as a string, and multiply it out by $a (the width), and then using the comma-operator ,, turns that into an array by multiplying the appropriate index of $b (i.e., how many layers). Those resultant string arrays are all left on the pipeline and output is implicit, with a newline between elements.

\$\endgroup\$
5
\$\begingroup\$

C, 108 105 bytes

Thanks to @Quentin for saving 3 bytes!

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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ #define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c); saves three bytes :) \$\endgroup\$ – Quentin Apr 18 '17 at 20:31
  • \$\begingroup\$ @Quentin Thanks! I wonder why I missed that in the first place :) \$\endgroup\$ – Steadybox Apr 18 '17 at 21:11
4
\$\begingroup\$

Batch, 146 bytes

@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

Relies on the obscure behaviour of echo in that it can often ignore the symbol between echo and the text to be echoed to collapse the four loops into a nested loop.

\$\endgroup\$
4
\$\begingroup\$

V, 22 bytes

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

Try it online!

Hexdump:

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

Input order is

Graham, Marshmallow, Chocolate, Width

Explanation:

é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
\$\endgroup\$
  • \$\begingroup\$ Could you add an explanation? \$\endgroup\$ – programmer5000 Apr 17 '17 at 14:45
  • \$\begingroup\$ @programmer5000 Sure! See my edit \$\endgroup\$ – DJMcMayhem Apr 17 '17 at 15:20
4
\$\begingroup\$

Excel, 104 bytes

Oh, boy! A formula that requires line breaks.

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

A1 has Width
A2 has Graham
A3 has Chocolate
A4 has Mallow


If pre-formatting is allowed, then you can format the cell for Vertical Text and shorten the formula to 65 bytes:

=REPT(REPT("G",A2)&REPT("C",A3)&REPT("M",A4)&REPT("G",A2)&"
",A1)
\$\endgroup\$
4
\$\begingroup\$

Jelly, 13 bytes

“GCM”ẋ"ṁ4Fẋ€Y

A dyadic program. Inputs are: [Graham's, Chocolates, Marshmallows], Width.

Try it online!

How?

“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
\$\endgroup\$
3
\$\begingroup\$

PHP, 85 Bytes

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

or

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

Online Versions

PHP, 96 Bytes

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

Online Version

Expanded

[$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
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 14 bytes

Code:

…GCM‚øü׬)˜S×»

Uses the CP-1252 encoding. Try it online!

Explanation:

…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
\$\endgroup\$
3
\$\begingroup\$

Python 2, 6757 bytes

(Edit: now that matrices are allowed, no need to newline-join it.)

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

C# (150 bytes)

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));
}
\$\endgroup\$
3
\$\begingroup\$

Java, 138 bytes

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

Try it online!

Explanation:

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;
}
\$\endgroup\$
3
\$\begingroup\$

Swift, 138 137 134 130 bytes

Saved 7 bytes thanks to @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)}

Two functions that return the expected value: f is a helper function and r is the actual lamdba-like function that generates the output. Usage: print(r(10,3,2,1))

Check it out!

\$\endgroup\$
  • \$\begingroup\$ You can save several characters by just referencing the string initializer directly (var f=String.init(repeating:count:);). And it doesn't save you any characters but it doesn't cost any so they should both really be let. \$\endgroup\$ – Kevin Apr 18 '17 at 5:34
  • \$\begingroup\$ And 3 more by dropping the explicit arguments 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)}) \$\endgroup\$ – Kevin Apr 18 '17 at 5:40
  • \$\begingroup\$ @Kevin Thanks, I had no idea that you can initialise a value to something like this: f=String.init(repeating:count:)... \$\endgroup\$ – Mr. Xcoder Apr 18 '17 at 6:39
  • \$\begingroup\$ @Kevin when it comes to your second suggestion, it seems like it exceeds the number of bytes in UTF-8, checked the byte count on TIO, don't know why \$\endgroup\$ – Mr. Xcoder Apr 18 '17 at 6:46
2
\$\begingroup\$

Convex, 20 bytes

"GCM"f*]z{~N+*}%(_@@

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 91 bytes

Includes trailing newline.

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

\$\endgroup\$
2
\$\begingroup\$

JS (ES6), 87 bytes

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

x acts as a standalone lambda function. The result has a trailing newline.

Try in a snippet:

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

function doTheThing() {
  document.getElementById("target").innerText = x(
    document.getElementById("width").value,
    document.getElementById("graham").value,
    document.getElementById("chocolate").value,
    document.getElementById("marshmallow").value,
  )
}
Width: <input id='width' value='10'>
Graham: <input id='graham' value='3'>
Chocolate: <input id='chocolate' value='2'>
Marshmallow: <input id='marshmallow' value='1'>
<pre id='target'></pre>
<button onclick='doTheThing()'>Do the thing</button>

\$\endgroup\$
2
\$\begingroup\$

C, 90 bytes (based on Steadybox's answer)

Renamed the variables and exploited the stringification preprocessor operator to cut down on the macro parameters. I hope posting this idea as its own answer is fine :)

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

TIO link

\$\endgroup\$
  • \$\begingroup\$ Would upvote, but hit vote limit :( \$\endgroup\$ – programmer5000 Apr 18 '17 at 21:41
2
\$\begingroup\$

F# (148 99 bytes)

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

Usage:

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

I'm still new to F#, so if I did anything weird or stupid, please let me know.

\$\endgroup\$
  • \$\begingroup\$ A link to F# would be nice. \$\endgroup\$ – programmer5000 Apr 18 '17 at 14:36
2
\$\begingroup\$

JavaScript ES6, 69 68 66 bytes

Thanks @Arnauld for golfing off one byte

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

Try it online!

Explanation

Receives input in curried format (Width)([Graham,Chocolate,Marshmallow])

Using .replace(/./g,...) replaces each character in the string GCMG with the return value from the function (c,i)=>`${c.repeat(a)} `.repeat(b[i%3])

`${c.repeat(a)} ` creates each line of the graham cracker with a newline appended .repeat(b[i%3]) repeats this line the required number of times

\$\endgroup\$
  • \$\begingroup\$ Using replace() would save a byte: a=>"GCMG".replace(/./g,(c,i)=>`${c.repeat(a[0])}\n`.repeat(a[1+i%3])) \$\endgroup\$ – Arnauld Apr 18 '17 at 12:12
1
\$\begingroup\$

JS (ES6), 111 bytes

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)
\$\endgroup\$
1
\$\begingroup\$

Mathematica 102 Bytes (100 Characters)

Heard the s'mores built-in isn't coming out til V12.

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

Pretty straightforward using the idea of building up a column first. Long function names waste 35 bytes. The one box-looking symbol is actually a transpose character and will paste into Mathematica just fine.

Usage: %@{Graham, Chocolate, Marshmallows, Width} e.g. %@{3, 2, 1, 11}

\$\endgroup\$
1
\$\begingroup\$

Java 7, 226 bytes

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

OR (also 226 bytes):

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

Explanation:

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)

Test code:

Try it here.

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

Output:

GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
\$\endgroup\$
  • 1
    \$\begingroup\$ Not bad...for java! \$\endgroup\$ – programmer5000 Apr 18 '17 at 14:27
  • 1
    \$\begingroup\$ @programmer5000 Hehe, thanks! I like golfing in Java 7 (and sometimes 8), although I don't think it will ever even compete with other answers.. The only time 'somewhat competed' with a Java answer was with this 8 byte answer and this 19 byte answer, actually outgolfing Python for the first time. ;p Although those golfing languages with their 1 or 2 byte submissions still leave Java in the dust of course. \$\endgroup\$ – Kevin Cruijssen Apr 18 '17 at 14:32
1
\$\begingroup\$

Haskell, 91 bytes

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

Should be pretty self-explanatory. Since it was noted in a comment that character matrices are allowed, here's a 58 byte version that returns a list of strings (one for each layer):

(#)=replicate
f w g c m=map(w#)$g#'G'++c#'C'++m#'M'++g#'G'
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.