title: Where are Champernowne's zeroes?

text:
# Question
Title: Where are Champernowne's zeroes?
Consider the infinite string of all nonnegative decimal integers concatenated together in order (akin to Champernowne's constant):

```
0123456789101112131415161718192021222324252627282930...979899100101102103...

```

Write a program or function that takes in a nonnegative integer that indexes (0-based) into this infinite string. Output a truthy value if the digit indexed is 0, otherwise output a falsy value if the digit is 1-9.

The shortest code in bytes wins.

The first 25 truthy-producing inputs are:

```
0
11
31
51
71
91
111
131
151
171
191
192
194
197
200
203
206
209
212
215
218
222
252
282
312

```

Kudos if your program is memory effecient, but this is not a requirement.

# Answer
> 12 votes
## Haskell, 25 bytes

```
(<'1').((show=<<[0..])!!)

```

Usage example: `(<'1').((show=<<[0..])!!) 312` -\> `True`

# Answer
> 7 votes
# 05AB1E, 5 bytes

Code:

```
ÝJ¹è_

```

Explanation:

```
Ý      # Get the list [0 .. input].
 J     # Join the list.
  ¹    # Get the first input again.
   è   # Get the character on that index.
    _  # Logical negate (0 -> 1, everything else -> 0).

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 7 votes
# Mathematica, ~~42~~ 40 bytes

```
(0@@Join@@IntegerDigits@Range@#)[[#]]<1&

```

Anonymous function. Takes a number as input and returns either `True` or `False` as output. A longer, yet more efficient(?) solution:

```
RealDigits[ChampernowneNumber[],10,1,-#][[1,1]]<1&

```

# Answer
> 5 votes
## CJam, 9 bytes

```
{_),s=~!}

```

This is an unnamed block (function) which takes in an integer and returns 0 or 1 accordingly.

Explanation:

```
{       }        Defines a block
 _               Copy input n
  ),             Increment n and take range
    s            Convert to string - for a list of numbers this concatenates
                 the digits
     =           Index, getting nth digit
      ~          Evaluate the digit character into a number
       !         Logical negation

```

Online interpreter. Note that `~` evaluates a block. Alternative, you can run this test suite which uses `,` to filter the first 1000 numbers for truthy values.

# Answer
> 5 votes
# Jelly, 6 bytes

```
RDF⁸ị¬

```

Try it online! or verify all test cases.

### How it works

```
RDF⁸ị¬  Main link. Argument: n

R       Range; yield [1, ..., n].
 D      Decimal; convert all integers in that range to base 10 arrays.
  F     Flatten the result.
   ⁸ị   Extract the digit at index n (1-based).
        This returns 0 if the array is empty (n = 0).
     ¬  Logical NOT; return 1 if the digit is 0, 0 if not.

```

# Answer
> 4 votes
# MATL, 11 bytes

```
Qt:qVXzw)U~

```

**Try it Online!**

**Explanation**:

```
    % Implicitly grab input as an integer (N)
Qt  % Add 1 and duplicate
:q  % Create an array from [0 ... N]
V   % Convert each entry to a string (places spaces between each number)
Xz  % Remove all whitespace
w)  % Get the N+1 element of the string (since MATL uses 1-based indexing natively)
U~  % Convert the result back to a number and negate which yields TRUE if it was '0' and
    % FALSE otherwise

```

# Answer
> 4 votes
# Brachylog, ~~10~~ 8 bytes

**2 bytes thanks to Fatalize.**

```
y@ec:?m0

```

Try it online!

```
y@ec:?m0

y         range from 0 to Input, inclusive,
 @e       the digits of every number in that range,
   c      concatenated
    :?m   the Input-th digit
       0  is zero.

```

# Answer
> 4 votes
# Perl 6, ~~26~~ 25 bytes

```
{!+map(|*.comb,0..*)[$_]}

```

A lambda that takes a number as input and returns a `True` or `False`.

Memory-efficient.

**How it works**

1. `0..*` – Construct the range from 0 to infinity.
2. `map(|*.comb, )` – Lazily iterate the range, replacing each number with the characters of its string representation, and returning a new lazy sequence. The `|` keeps the new sequence flattened.
3. `[$_]` – Take the element at the index defined by the (implicitly declared) lambda parameter `$_`.
4. `+` – Coerce it to a number. *(This step is needed because coercing a string directly to a boolean always gives True unless the string is empty.)*
5. `!` – Coerce it to a boolean and negate it.

(try it online)

*EDIT: -1 byte thanks to b2gills.*

# Answer
> 4 votes
# Python 3.5, 40 bytes

```
lambda n:('%d'*-~n%(*range(n),n))[n]<'1'

```

Test it on repl.it.

### How it works

For input **n**, `'%d'*-~n` repeats the format string **n + 1** times.

`(*range(n),n)` unpacks the range **\[0, ..., n - 1\]** and yields the tuple **(0, ..., n)**.

`...%...` replaces each occurrence of **%d** with the corresponding integer in the range, yielding the string **01234567891011...n**.

`(...)[n]<'1'` selects the character at index **n** and tests if it is less than the character **1**.

# Answer
> 3 votes
# Python 3, 44 bytes

```
lambda n:''.join(map(str,range(n+1)))[n]<'1'

```

An anonymous function that takes input via argument and returns `True` or `False` as appropriate.

**How it works**

```
lambda n      Anonymous function with input n
range(n+1)    Yield the range [0, n]...
map(str,...)  ...convert all elements to string...
''.join(..)   ...concatenate...
...[n]        ...yield nth character...
:...<'1'      ...return True if int(character)==0 else return False

```

Try it on Ideone

# Answer
> 3 votes
# Pyth, ~~8~~ 7 bytes

*Thanks to @LeakyNun for -1 byte*

```
!s@jkUh

```

This is my first attempt at golfing in Pyth.

A full program that prints `True` or `False` as appropriate.

Try it online

First 25 truthy inputs

**How it works**

```
!s@jkUh    Program. Input: Q
      hQ   Head. Yield Q+1
     U     Unary range. Yield [0, Q]
   jk      Join. Join on empty string
  @     Q  Index. Yield string[Q]
 s         Integer. Convert to integer
!          Logical negation. 0 -> True, all other digits -> False
           Print. Print result implicitly

```

# Answer
> 3 votes
# S.I.L.O.S, 141 bytes

```
readIO
i+1
lblL
c=C
p=1
lblc
p*10
c/10
if c c
p/10
lbln
m=C
m/p
m%10
p/10
i-1
if i C
GOTO H
lblC
if p n
C+1
GOTO L
lblH
m/m
m-1
m|
printInt m

```

Try it online!

Uses only 5 integers, maximum memory efficiency \o/

### Explanation

We generate as many digits as the input in the Champernowne's constant.

In the main loop, we do the following:

* Find the length of the current number by floor\_dividing it by 10 repeatedly until it reaches 0, and then count the number of divisions used.
* Instead of storing the number of divisions, we store 10 to that number power instead.
* Iterate through each digit as such: the `100`s digit of `1234` is obtained by `(1234/10)%10` where `/` is floor division.
* For each digit generated, take 1 from the input, while checking if the input reached zero.
* If the input reaches zero, check if the current digit is 0 and then halts.

# Answer
> 3 votes
## JavaScript (ES6), 45 bytes + Kudos

```
f=(n,s='0')=>s[n]?!+s[n]:f(n-s.length,-~s+'')

```

My best non-Kudos version was 34 bytes:

```
n=>!+(g=s=>s[n]||g(s+i++))('',i=0)

```

# Answer
> 1 votes
# JavaScript (ES6), 47 bytes

`n=>[...Array(n+1)].reduce((a,_,i)=>a+i,'')[n]<1`

# Answer
> 1 votes
## Javascript (ES6), ~~42~~ 33 bytes

```
n=>!+(r=i=>i>n?'':i+r(i+1))(0)[n]

```

Example:

```
let f =
n=>!+(r=i=>i>n?'':i+r(i+1))(0)[n]

// test all integers in [0, 312]
for(var n = 0, list = []; n <= 312; n++) {
  f(n) && list.push(n);
}
console.log(list.join(','));
```

# Answer
> 1 votes
# Groovy, 56 bytes

```
def f(n){def s=''<<'';(0..n).each{s<<it};!(s[n] as int)}

```

Nothing fancy, but I'm trying out some new things.

```
def f(n) {
  def s = ''<<''           // declare a StringBuffer
  (0..n).each { s << it }
  !(s[n] as int)           // Groovy considers a non-null char truthy, so we have to cast
}

```

# Answer
> 1 votes
# Perl, 24 bytes

Includes +1 for `-p`

Run with input on STDIN:

```
zero.pl <<< 31

```

print 1 for zero, nothing otherwise

`zero.pl`

```
$_=!(map/./g,0..$_)[$_]

```

# Answer
> 1 votes
# zsh, 31 bytes

```
exit ${${(j..):-{0..$1}}[$1+1]}

```

`exit 0` is true in zsh

# Answer
> 1 votes
# Ruby, ~~35~~ 23 bytes

This is an anonymous function that concatenates `[0..n]`, takes the `n`th index and checks if that char is `"0"` (less than `"1"`). Golfing suggestions welcome.

```
->n{([*0..n]*'')[n]<?1}

```

**Ungolfing**

```
->n{...}   # Create an anonymous function with parameter n.
[*0..n]    # Create an array of the range [0..n].
[...]*''   # Join the array using the empty string.
(...)[n]   # Take the char at the n-th index of the string.
<?1        # Check if the char is < "1" (that is, "0").

```

# Answer
> 1 votes
# PHP, 36 bytes

```
<?=!join(range(0,$a=$argv[1]))[$a];

```

Print `1` if Champernowne argument-th decimal is `0`, else print '' (empty string).

# Answer
> 1 votes
# R, 61 57 bytes

Thanks to @plannapus for 4 bytes.

```
n=scan();strsplit(paste(0:n,collapse=""),"")[[1]][n+1]==0

```

Creates a vector of numbers 0:n (for 0 indexing), creates a string of them, pulls the nth value from string (adjusting for 0 indexing). Converts to numeric and tests if it is 0.

# Answer
> 1 votes
# Bash, ~~31~~ 28 bytes

```
seq -s "" 0 $1|egrep ^.{$1}0

```

Output is non-empty (truthy) or empty (falsy). Test it on Ideone.

# Answer
> 1 votes
# Julia, ~~21~~ 20 bytes

```
!n=join(0:n)[n+1]<49

```

*Thanks to @LuisMendo for golfing off 1 byte!*

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 14 bytes

```
{~×⍎⍵⊃∊⍕¨⍳1+⍵}

```

Try it online!

## Explanation

```
{~×⍎⍵⊃∊⍕¨⍳1+⍵}     ⍝
{            }     ⍝ A dfn, in this case with a single argument (⍵)
         ⍳1+⍵      ⍝ Computes the range of 0..arg
       ⍕¨          ⍝ For each (¨), convert to a string (⍕)
      ∊            ⍝ Enlist all strings into a single string
    ⍵⊃             ⍝ Pick (⊃) the element at the index of the given arg (⍵)
   ⍎               ⍝ 'Execute' to treat it as a numeric
  ×                ⍝ Turn >1 into 1
 ~                 ⍝ Negate

```

# Answer
> 1 votes
# Vyxal, 38 bitsv2, 4.75 bytes

```
ʀṅi0=

```

Try it Online!

# Answer
> 0 votes
# GolfScript, 12 bytes

```
~.),""*\=48=

```

Explanation:

```
~             Evaluate the input.
 .            Duplicate it
  )           Increment the duplicate.
   ,          Create an array from 0 to it.
    ""*       Join it with an empty string.
       \=     Get the n-th index of this string, where n is the input
         48=  Is it equal to 0?

```

Try it online or verify all test cases!

# Answer
> 0 votes
# Javascript (ES5): 61 60 bytes

```
function(b){for(s="";s.length<b;)s+=s.length;return 0==s[b]}

```

Ungolfed:

```
function a(b){
  for(var s="";s.length<b;)
    s+=s.length;
  }
  return (s[b]==0);
}

```

Old:

```
function(n){s="";while(s.length<n)s+=s.length;return s[n]==0}

```

Ungolfed old:

```
function a(n){
  var str="";
  while(str.length<n)str+=str.length; //Create String as long as needed
  return str[n]==0 //Check for 0 and return
}

```

# Answer
> 0 votes
**C, 154 bytes**

```
s(n,v,k,z){for(k=1;(z=n%10,n/=10)&&!v||k<v;++k); return v?z:k;}
f(n,i,j,c){for(i=0,j=0;;++i){c=s(i,0,0,0);j+=c;if(j>n){c=s(i,j-n,c,0);break;}}return !c;}

```

the function that calculate the value is f(n,0,0,0) where n is the input index. it can calculate from index changing "return !c" in "return c" the value of the array in that index... i don't understand how but it seems to work ok....

```
main()
{int   i,r;
 char  a[]="0123456789101112131415161718192021222324252627282930313233343536";

 for(i=0; i<1000; ++i)
    if(r=f(i,0,0,0))
        printf("%u|",i);
}
/*
 154
 0|11|31|51|71|91|111|131|151|171|191|192|194|197|200|203|206|209|212|215|218|222
|252|282|312|342|372|402|432|462|491|492|494|497|500|503|506|509|512|515|518|522|552
|582|612|642|672|702|732|762|791|792|794|797|800|803|806|809|812|815|818|822|852
|882|912|942|972|
*/

```

# Answer
> 0 votes
# CoffeeScript, 56 bytes

```
a=(b)->
 s=""
 while s.length<b #loop for building string with required length
  s+=s.length     #add number
 "0"==s[b]        #return, if the number at the position equals zero

```

# Answer
> 0 votes
# C#, 71 bytes

And I thought it was short at first, but then I had to add `n+=11` to prevent it from throwing a `System.IndexOutOfRangeException` when numbers below 11 were input

```
return String.Join("",Enumerable.Range(0,n+=11).ToArray())[n]=='0'?1:0;

```

# Answer
> 0 votes
## Pyke, 7 bytes

```
m`sQ@b!

```

Try it here!

# Answer
> 0 votes
# Actually, ~~9~~ 8 bytes

This answer concatenates the range `[0..n]`, takes the `n`th index and checks if that char is `"0"`. Golfing suggestions welcome. Try it online!

```
;urεjE≈Y

```

**Ungolfing**

```
;          Duplicate n
 ur        Increment the duplicate and create range [0..n].
   εj      Join the range with an empty string. Stack: <string> n
     E     Take the char at the n-th index.
      ≈    int(a)
       Y   Logical NOT. If the digit is 0, then return 1, else return 0.

```

# Answer
> 0 votes
## PowerShell v2+, 32 bytes

```
param($n)(-join(0..$n))[$n]-eq48

```

Does the same as other answers -- takes the range from `0` to input `$n`, `-join`s together into a string, takes the `[$n]` index, checks if it's `-eq`ual to `48` (i.e., ASCII for `0`).

Note this will only work up to input `49999`, as the PowerShell range operator `..` only supports ranges of 50,000 elements or fewer. For larger inputs, you'll need to use the following, based on my previous Champernowne answer, at **58 bytes**:

```
param($n)$j=$n;for($c='';$j-ge0;$j--){$c+=$i++}$c[$n]-eq48

```

# Answer
> 0 votes
# Octave, ~~41~~ 29 bytes

*Credit to Dennis, whose Julia answer made me realize I wasn't treating input `0` correctly.*

```
@(n)sprintf('%i',0:n)(n+1)<49

```

This is an anonymous function.

Try at Ideone.

### Explanation

For input `n`, this generates the Champernowne digits corresponding to the first `n+1` numbers starting at `0` (which is more than enough). `sprintf` is used for this so that no blank spaces appear. The result is true if the `n+1`-th digit (1-based) is zero, that is, if its ASCII code is less than `49`.

# Answer
> 0 votes
# R, 57 bytes

```
grepl("0$",substr(paste(0:(n=scan()),collapse=""),1,n+1))

```

Build a string corresponding to `0:n`, keeps the first `n+1` characters and check if the last character is a zero.

# Answer
> 0 votes
# Thunno 2 `!`, 4 bytes

```
ĖJiN

```

Try it online! or verify some more cases

#### Explanation

```
ĖJiN  # Implicit input
Ė     # Push [0..input]
 J    # Join into string
  i   # Index using input
   N  # Cast to integer
      # Logical NOT
      # Implicit output

```

---
Tags: code-golf, string, integer, decision-problem
---


title: Self-referencing tuple in python

text:
# Question
Title: Self-referencing tuple in python
Goal: create a self-referencing tuple satisfying `x == (x,)` in any version of Python. Standard libraries, matplotlib, numpy, pandas only.

Answers meeting this extra condition are prioritised (which may be impossible): this tuple should also be insertable into a dict or set.

If the extra condition is impossible, apart from the low-hanging optimization of the below code, I am still interested in a qualitatively different approach of similar length or better.

---

I had previously assumed this answer to be one of the shortest, but as @mousetail brought up, actually it crashes python when inserted into a dict or set.

```
import ctypes
tup = (0,)
ctypes.c_longlong.from_address(id(tup)+24).value = id(tup)

```

I notice this also happens with the other answer in that post, so I'm wondering if there's a way to resolve it (the ideal answer), or if that is inherent in python.

# Answer
> 11 votes
# Python 3, 48 bytes

```
from marshal import*
t=loads(b'\xa9\1r\0\0\0\0')

```

Try it online!

Not portable, depends on the interpreter. There's probably a similar (portable) `pickle` version, although it would need to be handcrafted since the `pickle.dumps` gives an error due to recursion depth.

Uses `marshal`, which is a standard library for serializing Python objects. The string is the string received by serializing the object produced by the code in the question.

---
Tags: python, programming-puzzle
---


title: Comparator function in Javascript

text:
# Question
Title: Comparator function in Javascript
Need to write a JS function compare(a,b) for numbers which return 1 when a \> b, 0 when a == b, -1 when a \< b. Also following properties should hold:

1. compare(NaN, NaN) = 0
2. NaN is bigger than any other number, so compare(NaN, any) = 1 and compare(any, NaN) = -1.
3. compare(-0.0, 0.0) = -1 and compare(0.0, -0.0) = 1. Other numbers are ordered by default.

Other way to define: function should behave as Double.compare method in Java.

# Answer
# JavaScript (Node.js), 61 bytes

*-5 bytes, thanks to l4m2*

```
compare=(a,b)=>(a>b)-(b>a)||(1/a>1/b)-(1/b>1/a)+(b==b)-(a==a)

```

Attempt This Online!

## Explanation

```
compare=(a,b)=>
  (a>b)-(b>a)||        // compare values, return if non-zero
  (1/a>1/b)-(1/b>1/a)  // compare inverse values to check for -0<0
   +(b==b)-(a==a)      // compare equalities to check for NaN

```
> 0 votes

---
Tags: javascript, java, comparison
---


title: Keep jumping till a cycle

text:
# Question
Title: Keep jumping till a cycle
# Objective

You're on a nonempty list of integers that wraps around. You start at the leftmost entry of the list, and keep jumping to the right to the amount of the integer entry you're at.

Eventually, you'll end up in a cycle. The objective is to output the length of this cycle.

# I/O format

Provided that the inputted list has \\$n\\$ entries, each entry \\$m\\$ is assumed to satisfy \\$0 \leq m \< n\\$. Otherwise flexible.

# Examples

```
Input, Output
[0], 1
[0, 1, 2], 1
[1, 0, 2], 1
[1, 1, 2], 2
[2, 2, 2, 2], 2
[2, 3, 2, 1], 2
[3, 3, 3, 2], 3
[1, 1, 1, 1], 4

```

# Worked Example

```
[1, 2, 3, 2]
 ^
[1, 2, 3, 2]
    ^
[1, 2, 3, 2]
          ^
[1, 2, 3, 2]
    ^
Cycle detected; halt. The output is: 2.

```

# Answer
# Jelly, 9 bytes

```
Ėṙ`ḢṪƊÐḶL

```

A monadic Link that accepts a list of integers and yields the cycle length.

**Try it online!**

### How?

Keep a record of the original indices along with their jump-values and repeatedly rotate this left by its first jump-value to find the cycle and output its length.

The implementation actually rotates by all indices and jump-values then picks out the one we want (rotated by first jump-value).

```
Ėṙ`ḢṪƊÐḶL - Link: list of integers, Jumps
Ė         - enumerate  -> [[1, jump1], [2, jump2], ...]
      ÐḶ  - start with that and collect up while distinct then yield loop, applying:
     Ɗ    -   last three links as a monad - f(Current):
  `       -     use as both arguments of:
 ṙ        -       rotate {Current} left by {Current} (vectorises)
   Ḣ      -     head -> rotations by the first index and first jump
    Ṫ     -     tail -> rotation by the first jump
        L - length

```
> 6 votes

# Answer
# , 65 bytes

```
\(a){while(!(T=(T+a[+T]-1)%%sum(a|1)+1)%in%F)F=c(T,F)
match(T,F)}

```

Attempt This Online!
> 5 votes

# Answer
# Python, 62 bytes

*-4 bytes, thanks to loopy walt*

```
lambda L,i=0:len({*[i:=(i+L[i])%len(L)for _ in 2*L][len(L):]})

```

Attempt This Online!

## Explanation

1. compute list of first `2*len(L)` jumps
2. find the number of unique indices in the last `len(l)` jumps

---

# Python, 93 bytes

```
lambda l,i=0,s=[0]:1+len([(s:=s+[i:=j])for _ in l if(j:=(i+l[i])%len(l))not in s])-s.index(j)

```

Attempt This Online!

## Explanation

1. go through the first `len(l)` jumps, stop if a duplicate is found
2. return the (1-based) index of the duplicate element in the list of indices counted from the end of the list
> 4 votes

# Answer
# JavaScript, 56 bytes

```
a=>(g=t=>t-(a[i=(i+a[i|0])%a.length]||=t++)||g(t))(i=.5)

```

```
f=

a=>(g=t=>t-(a[i=(i+a[i|0])%a.length]||=t++)||g(t))(i=.5)

t = `
[0], 1
[0, 1, 2], 1
[1, 0, 2], 1
[1, 1, 2], 2
[2, 2, 2, 2], 2
[2, 3, 2, 1], 2
[3, 3, 3, 2], 3
[1, 1, 1, 1], 4
`.trim().split('\n').map(l => JSON.parse(`[${l}]`));
t.forEach(([i, e]) => {
  console.log(f([...i]) == e, f([...i]))
});
```
> 3 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
+J,1ị@\ÐḶL

```

Try it online!

*-1 thanks to Bubbler*

```
+J            Add every jump number to its 1-index.
  ,1          Pair that with 1.
       ÐḶ     Loop while unique then extract the cycle:
      \       scan by
    ị@        modular 1-index right into left.
      \ÐḶ     (Dyadic ÐḶ doesn't reuse the right argument.)
         L    Take the length of the cycle.

```
> 3 votes

# Answer
# JavaScript (ES6), 54 bytes

```
f=(a,i=j=0)=>j-a[~i]||f(a,(i+a[i])%a.length,a[~i]=j++)

```

Try it online!

---

# JavaScript (ES12), 52 bytes

-2 bytes by using nullish coalescing assignment, as suggested by @tsh.

```
f=(a,i=j=0)=>j-(a[~i]??=j++)||f(a,(i+a[i])%a.length)

```

Attempt This Online!
> 3 votes

# Answer
# Python, 99 bytes

```
lambda x,y=0,z={}:next(i-z[y]for i in range(len(x)+1)if y in z or[z:=z|{y:i},y:=(y+x[y])%len(x)]*0)

```

Attempt This Online!
> 2 votes

# Answer
# 05AB1E, 16 bytes

```
0λIā<+sè}Igô1èÙg

```

Try it online!
> 2 votes

# Answer
# , ~~41 34 31 30~~ 29 bytes

```
##@~.@}.0]F:.(#@[|]+{~)2###,:

```

Attempt This Online!

*-3 thanks to a nice observation by ovs: If you run the simulation 2\*n times, as I was, you can ensure you get only the cyclic elements by removing the first `n`*

*I also shaved another byte off by applying a trick from another of ovs's suggestion*

This is a combination of two suggestions from ovs, using `F:.` for folding.

## , ~~41 34 31~~ 30 bytes, saved for a new J trick

```
##@~.@}.<@+:@#@[(#@[|]+{~^:)&0

```

Attempt This Online!

* `<@+:@#@[(#@[|]+{~^:)&0` Simulate the jumps 2\*n times. For J lang enthusiasts, we are using a partially applied conjunction as an adverb here: `(#@[|]+{~^:)` -- it modifies the verb `<@+:@#@[`, and is equivalent to the standard form `(#@[|]+{~)^:(<@+:@#@[)`. It is acting here as a syntactic trick that allows us to save to some parens.
* `##@~.@}.` Now remove the first n elements (ensuring we only have cyclic elements left), and take the count of the uniq
> 2 votes

# Answer
# Vyxal, 12 bytes

```
ẏYd‡hǓ~↲t$↲L

```

Try it Online!
> 2 votes

# Answer
# Scala, 95 bytes

Golfed version. Try it online!

```
l=>{var(r,a)=(Seq[Int](),0);while(!r.contains(a)){r:+=a;a=(a+l(a))%l.size};r.size-r.indexOf(a)}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(f(List(2,3,2,1)))
  }

  def f(l: List[Int]): Int = {
    var r = List[Int]()
    var a = 0
    while (!r.contains(a)) {
      r = r :+ a
      a = (a + l(a)) % l.size
    }
    r.size - r.indexOf(a)
  }
}

```
> 2 votes

# Answer
# Ruby, 62 bytes

```
->l{*r=a=0;1while r!=r|=[a=(a+l[a])%l.size];r.size-r.index(a)}

```

Try it online!
> 1 votes

# Answer
# Charcoal, 29 bytes

```
ＵＭθ⁺ικ⊞υ⁰Ｆ⁺θθ⊞υ§θ↨υ⁰Ｉ⊕⌕Φ⮌υκ⊟υ

```

Try it online! Link is to verbose version of code. Explanation: Port of @bsoelch's Python answer.

```
ＵＭθ⁺ικ

```

Add the index to each element to give its (cyclic) destination index.

```
⊞υ⁰

```

Start on the leftmost index.

```
Ｆ⁺θθ

```

Repeat enough times to guarantee a cycle.

```
⊞υ§θ↨υ⁰

```

Get the next index.

```
Ｉ⊕⌕Φ⮌υκ⊟υ

```

Find the length of the cycle.
> 1 votes

---
Tags: code-golf, number
---


# Question
Title: Find the number in the Champernowne constant
### Introduction

In base 10, the Champernowne constant is defined by concatenating representations of successive integers. In base 10: `0.1234567891011121314151617...` and so on.

You can see that the first appearence of `15` starts at the `20th` decimal:

```
  Position
  0000000001111111111222222222233333333334444444444555555555566666666
  1234567890123456789012345678901234567890123456789012345678901234567
                     ^
0.1234567891011121314151617181920212223242526272829303132333435363738...
                     ^^
                     15 = position 20

```

The first appearence of `45` starts at the `4th` decimal:

```
  Position
  0000000001111111111222222222233333333334444444444555555555566666666
  1234567890123456789012345678901234567890123456789012345678901234567
     ^
0.1234567891011121314151617181920212223242526272829303132333435363738...
     ^^
     45 = position 4

```

So, the task is easy. Given a non-negative integer, output the position of the integer in the Champernowne constant.

### Rules

* You may provide a function or a program
* This is , so the submission with the least amount of bytes wins!

### Test cases

```
Input: 20
Output: 30

Input: 333
Output: 56

Input: 0
Output: 11 (note that the 0 before the decimal point is ignored)

Input: 2930
Output: 48

```

# Answer
> 8 votes
# Pyth, 10

```
hxjkS+QT`Q

```

Concatenates first `input + 10` numbers then finds the 0 based index plus one.. The extra ten are only needed for 0.

Test Suite

# Answer
> 10 votes
# LabVIEW, 29 LabVIEW Primitives

This uses strings for now. It matches the input as a pattern and outputs the offset - (input lenght -1).

# Answer
> 6 votes
# Javascript, 57 bytes

```
a=prompt();for(y=b=" ";y<a+11;)b+=++y;alert(b.indexOf(a))

```

Saved 1 byte thanks to Conor O'Brien.

# Answer
> 4 votes
# Japt, 11 bytes

This was originally beating Pyth, but apparently it didn't work for input `0`.

```
1+1oU+B ¬bU

```

Try it online!

### How it works

```
1+1oU+B ¬ bU
1+1oU+B q bU  // Implicit: U = input integer
  1oU+B       // Generate the range [0, U+11).
        q bU  // Join and take the index of U.
1+            // Add one to get the correct result.
              // Implicit: output last expression

```

# Answer
> 4 votes
## Haskell, 62 bytes

```
a#b|and$zipWith(==)a b=1|1<2=1+a#tail b
(#(show=<<[1..])).show

```

Usage example: `(#(show=<<[1..])).show $ 2930`-\> `48`.

How it works: `a # b` finds the position of `a` within `b`: if `a` is prefix of `b` return `1`, else add `1`to a recursive call with `a # tail b`. The pointfree function `(#(show=<<[1..])).show` expects an (unnamed) argument `n` and calls `show n # show=<<[1..]`.

The function `subIndex` would also do the job of `#`, but the required `import Data.List.Utils` doesn't pay off.

# Answer
> 4 votes
# Ruby, 28

```
->n{[*0..n+10]*''=~/\B#{n}/}

```

Includes a 0 at the beginning so that matches are 1-indexed, but uses `\B` to require that the match not be at the beginning of the string.

# Answer
> 3 votes
# Lua, 54 Bytes

```
s=""for i=1,1e4 do s=s..i end print(s:find(io.read()))

```

Note: ~~Currently this program prints both the first occurrence of the first char of the string, and the point where it ends. If this is not allowed, it will cost a few more bytes.~~ I would like to petition for a bonus because my program prints out both the first position and last position of the input number.

# Answer
> 3 votes
# MATL (release 1.0.1), 22 bytes

```
iXK10+:"@Ys]N$hKYsXf1)

```

### Example

```
>> matl iXK10+:"@Ys]N$hKYsXf1)
> 333
56

```

### Explanation

```
i       % Input
XK      % Copy to clipboard K
10+     % Add 10. This is needed in case input is 0
:       % Vector of equally spaced values, starting from 1
"       % For each
  @Ys   %   For loop variable as a string
]       % End
N$h     % Horizontal concatenation of all stack contents
KYs     % Paste from clipboard K (input number) and convert to string
Xf      % Find one string within another
1)      % First value

```

# MATL (release 20.8.0), 16 bytes (language postdates challenge)

*Credit to @Giuseppe for this version of the program (slightly modified)*

```
10+:"@V]&hGVXf1)

```

Try it online!

### Explanation

```
10+     % Implicit Input. Add 10. This is needed in case input is 0
:       % Vector of equally spaced values, starting from 1
"       % For each
  @V    %   For loop variable as a string
]       % End
&h      % Horizontal concatenation of all stack contents
GV      % Paste from automatic clipboard G (input number) and convert to string
Xf      % Find one string within another
1)      % First value

```

# Answer
> 3 votes
# MATL, 22 bytes

```
it10+:Yst' '=~)wYsXf1)

```

Take the input (`i`), make the vector 1 to input+10 (`10+:`), converts the vector to a string (`Ys`), and remove the spaces, which is painful, (`t' '=~)`). Then, convert the input to a string (`Ys`), find where the input string is in the string of numbers (`Xf`) and take the first location (`1)`). The `t`'s and `w`'s are manipulating the stack (duplicate and swap, respectively).

# Answer
> 3 votes
# PowerShell, 39 44 bytes

\[Edit: my assumption doesn't hold, building an array from 1-0 doesn't find 0 at place 11. Instead, build from 1-x+10 to handle 0 as well, now 44 bytes\]

```
param($i)(1..($i+10)-join'').IndexOf("$i")+1

```

---

You will always find *x* when building a string of the Champernowne constant at the latest point when you add *x* onto the end, so an array from 1-x will always have the answer in it. The question becomes *"does it occur any sooner than that?"*. This code

```
param($i)(1..$i-join'').IndexOf("$i")+1

e.g.

PS C:\Temp> .\Champer.ps1 20
30

```

generates a range of numbers, casts it to a string, and searches for the parameter inside it. Because PowerShell is an object oriented shell, the parameter is actually an `[int]` type, so trying to save two characters with `.IndexOf($i)` would search the string for an integer and find nothing. That's why I use string interpolation `"$i"`.

# Answer
> 2 votes
## PowerShell, ~~54~~ 50 Bytes

```
for($c='';!($x=$c.IndexOf("$args")+1)){$c+=++$i}$x

```

Thanks to TessellatingHeckler for the idea of swapping the `while` loop for a `for` loop.

Executes via a `for` loop. As with other languages, the first statement in the loop can construct variables and assignments, so this starts with `$c` equal to just the empty string `''` so that we have zero-indexing of the string lining up with the decimal indexing of the challenge. We're then in a loop that checks whether `$c` has the input integer (`$args`) somewhere within it (i.e., since `.IndexOf()` returns `-1` if the string isn't found, we add one to that (`0`) and not it (`$TRUE`) to continue the loop). If it's not found, we add on our pre-incremented `$i` counter variable, then recheck the string. Once the string is found, `.IndexOf()` will return a positive value, the not of which will be `$FALSE`, breaking out of the loop. Finally, we output the index with `$x`.

# Answer
> 2 votes
# JavaScript (ES6), 40 bytes

```
x=>(f=n=>n?f(n-1)+n:" ")(x+11).search(x)

```

Uses the recursive function `f` to avoid loops. The search method works the same as `indexOf` except that it takes a RegExp as a parameter, which is irrelevant for this challenge.

Adding a `" "` for the `n=0` case (zero is falsy in JS) coerces the `+` to perform string concatenation instead of addition, and corrects for zero-based indexing.

# Answer
> 1 votes
# Python 3, 54.

```
print(''.join(map(str,range(1,9**7))).find(input())+1)

```

# Answer
> 1 votes
## CJam, 11 bytes

```
r_i),s\#Be|

```

Test it here.

I'm finding the position of `N` in the string `01234...N` to account for the 1-based indexing. Finally I fix `0` by applying logical OR with 11.

# Answer
> 1 votes
## Seriously, 13 bytes

```
;≈9u+R`$`MΣí

```

Takes input as an integer. Contains unprintables, so hexdump:

```
0c3bf739752b526024604de4a1

```

Try it online

Explanation:

```
;≈9u+R`$`MΣí
<form feed>   push str(input)
;≈9u+R        dupe, push [1,...,input+10]
      `$`MΣ   string concatenation of list
           í  get index of input

```

# Answer
> 1 votes
# , 13 chars / 22 bytes

```
1+⩥(1,ï+ḋ)⨝ÿï

```

`Try it here (Firefox only).`

# Answer
> 1 votes
## k4, 21 bytes

```
{*1+(,/$1+!10+x)ss$x}

```

Same algo as everyone else—concatenate `[1..10+x]` as strings, search for x as string, convert to one-based indexing, return first hit.

Checking the test cases:

```
  &/20 4 30 56 11 48={*1+(,/$1+!10+x)ss$x}'15 45 20 333 0 2930
1b

```

# Answer
> 1 votes
# Mathematica, 101 bytes

```
(If[#==0,11,m=Min@SequencePosition[s=Flatten[(K=IntegerDigits)/@Range[0,#]],K@#];Length@s[[;;m-1]]])&

```

# Answer
> 1 votes
# Haskell, ~~82~~ ~~73~~ 55 bytes

*Migrated from the duplicate*

```
x!b|or$zipWith(==)x b=0
x!(_:b)=1+x!b
(!(show=<<[1..]))

```

Try it online!

## Explanation

First we define `!`. `x!b` truncates `b` to the first appearance of `x`. It does this by checking if `b` starts with `x` (`or$zipWith(==)x b`) returning `x` if it does and moving one down the string otherwise. Then we define our main function. Our main function is a point-free function that takes the constant (`show=<<[1..]`) and truncates it to the first appearance of `x`. This takes `x` as a string.

# Answer
> 1 votes
# Jelly, 5 bytes

```
+⁵RVw

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), ~~50~~ ~~39~~ 38 bytes

```
x=s=``
f=n=>-~s.search(n)||f(n,s+=++x)

```

---

## Try it

```
x=s=``
f=n=>-~s.search(n)||f(n,s+=++x)
o.innerText=f(i.value=15);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o></pre>
```

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
nLJsk>

```

Try it online!

# Answer
> 1 votes
# Stax, 6 bytes

```
⌐╛∙#»▓

```

Run and debug it

# Answer
> 1 votes
# Perl 6, 26 bytes

```
{[~](0..$_).index($_)||11}

```

Try it online!

Finds the index of the element in the concatenated range from 0 to that element, or `11` if the number is a zero

# Answer
> 1 votes
# Husk, ~~6~~ 5 bytes

```
€ṁdNd

```

Try it online!

*-1 thanks to Razetime*

```
€        The 1-based index, in
  d      decimal digits
 ṁ       concat-mapped over
   N     all natural numbers,
    d    of the decimal digits of the input.

```

# Answer
> 1 votes
# Vyxal, 6 bytes

```
₁+ɾṅḟ›

```

Try it Online! `ɾṅḟ` would be enough if not for the zero edgecase.

```
₁+ɾṅḟ›
     › # 1 +
    ḟ  # Index of input in
   ṅ   # Concatenation of
  ɾ    # 0...
₁+     # 100+n

```

# Answer
> 0 votes
# Perl 5, ~~42~~ 31 + 1 (-p) = 32 bytes

```
(join'',0..$_+10)=~/$_/;$_="@-"

```

Try it online!

**Explanation**

```
(join'',0..$_+10)   # concatenate all of the numbers from 0 to 10 over the input
=~/$_/;             # skip the first 0, then find the input
$_="@-"             # @- holds the index of the start of the last match

```

# Answer
> 0 votes
# Perl 6/Rakudo 29 bytes

```
{$_~=$++until /(.+)$^a/;$0.chars}

```

Defines a function with one input ($^a). Call thus:

```
say {$_~=$++until /(.+)$^a/;$0.chars}(333)
> 56

```

Appending `$`, an anonymous variable, incrementing `$++` until the input `$^a` is found, and then counting the number of chars before it. Requiring at least 1 char before it `.+` in the regex usefully excludes the 0-\>0 case

# Answer
> 0 votes
# J, 30 Bytes

```
{.I.(":E.[:}.' '-.~":@i.@+&11)

```

Could probably be golfed down a bit more, specifically in concatenating the first n+10 integers.

### Explanation:

```
{.I.(":E.[:}.' '-.~":@i.@+&11)
                      i.@+&11   | Integers 0 to n+10
                   ":@          | Format list to string
             ' '-.~             | Strip spaces
           }.                   | Behead (remove leading 0)
         [:                     | Cap (previous verbs executed in order, not as a fork)
     ":E.                       | Find matches to the string n (returns a boolean vector)
  I.                            | Indexes of 1s
{.                              | Take only the first

```

Note that this is 0-indexed. Examples:

```
    {.I.(":E.[:}.' '-.~":@i.@+&11) 1
0
    {.I.(":E.[:}.' '-.~":@i.@+&11) 0
10
    {.I.(":E.[:}.' '-.~":@i.@+&11) 333
55

```

---
Tags: code-golf, math, number
---


# Question
Title: 579085261 is CRAZY, 725582 is GOLF, 10757494 is ...?
Your task is to translate a 103-smooth number into an English word, using the method described below.

## How?

1. Generate the list of prime factors (with repetition) of the input number.
2. Sort the list:
    * If **2** is not one of the prime factors, sort the list in ascending order.
    * If **2** is one of the prime factors, remove it from the list and sort the remaining factors in descending order.
3. Translate each factor into a letter, using the following table:

```
 3 = S   13 = L   29 = X   43 = O   61 = Z   79 = H  101 = K
 5 = P   17 = Q   31 = N   47 = R   67 = T   83 = V  103 = Y
 7 = M   19 = U   37 = C   53 = A   71 = E   89 = D
11 = F   23 = I   41 = W   59 = G   73 = J   97 = B

```

*<sub>**Note**: This table was built empirically to maximize the number of possible words. For the curious, here is a list of 2,187 words that can be encoded that way (may include rude language). It's definitely not guaranteed to be optimal, but it's good enough for this challenge.</sub>*

## Examples

**Example 1: 579085261** (ascending order)

1. The prime factors are **\[ 37, 47, 53, 61, 103 \]**.
2. **2** is not a prime factor, so we keep the list sorted in ascending order.
3. 37 = C, 47 = R, etc. The output is "CRAZY".

**Example 2: 725582** (descending order)

1. The prime factors are **\[ 2, 11, 13, 43, 59 \]**.
2. **2** is a prime factor, so we remove it and sort the list in descending order, which gives:
**\[ 59, 43, 13, 11 \]**.
3. 59 = G, 43 = O, etc. The output is "GOLF".

**Example 3: 10757494** (with a repeated factor)

1. The prime factors are **\[ 2, 11, 71, 71, 97 \]**.
2. **2** is a prime factor, so we remove it and sort the list in descending order, which gives:
**\[ 97, 71, 71, 11 \]**.
3. 97 = B, 71 = E, 11 = F. The output is "BEEF".

## Clarifications and rules

* The input number is guaranteed to be 103-smooth and divisible by 2 at most once.
* By definition, a smooth-number is a *positive integer*.
* Input and output can be handled in any reasonable format. The output can be in lowercase or uppercase. Trailing whitespace is acceptable. Leading whitespace is not.
* If your program/function can't support large inputs, please specify it in your answer.
* This is code golf, so the shortest answer in bytes wins.

## Test cases

```
34874          --> ARM
483254         --> BAR
353722         --> EAR
494302         --> EGG
39061          --> FAT
6479           --> FUN
60421          --> ICE
54166          --> JAM
48911474       --> BETA
2510942        --> BOOM
2303854        --> DOOM
844261         --> FIRE
1606801        --> MAZE
1110085        --> PAGE
5212974        --> BALLS
67892046       --> BEANS
885396199      --> CREEK
67401037       --> FUNKY
27762173       --> QUICK
1238440506     --> ARROWS
33045832681    --> CRAGGY
1362714005     --> PIRATE
137302698      --> TROLLS
358310128062   --> BEGGARS
40255151586    --> DETAILS
164633248153   --> FIXATED
621172442227   --> UNRATED
2467812606     --> VACUUMS
86385078330    --> GROWNUPS
26607531423091 --> UNWORTHY

```

# Answer
# Jelly, ~~29~~ 27 bytes

```
ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡

```

*Thanks to @JonathanAllan for golfing off 1 byte!*

Try it online!

### Background

```
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’

```

is a numeric literal. The characters between the quotes are replaced with their 1-based indices in the Jelly code page, and the resulting array is interpreted as a base-250 number. This yields the integer **c := 288824892868083015619552399**.

### How it works

```
ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡  Main link. Argument: n

ÆE                           Yield the exponents of n's prime factorization, with.
                             zeroes. This yields an array A.
  µ                          Begin a new monadic chain with argument A.
   ØA                        Set the return value to “ABC...XYZ”.
     “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?        Select the c-th permutation of the alphabet, yielding
                             s := “SPMFLQUIXNCWORAGZTEJHVDBKY”.
                      Ḋ      Dequeue; yield A without its first element, stripping
                             the exponent of 2.
                     x       Repeat the k-th letter of s r times, where r is the
                             exponent of the k-th odd prime number.
                          ¡  Combine the two links to the left into a quicklink:
                        Ḣ}     - Apply head to the right argument (A), yielding the
                                 exponent of 2. Since n is at most divisible by the
                                 first power of 2, this yields 1 for even numbers
                                 and 0 for odd ones. Call the link to the left that
                                 many times on the previous return value.
                       Ṛ       - Reverse the string to the left.

```
> 14 votes

# Answer
# Jelly, 36 bytes

```
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA1;;⁶
×107ÆE¢×UḢ¡t⁶

```

Try it online!

## Explanation

**Helper constant**  (produces `“SPMFLQUIXNCWORAGZTEJHVDBKY ”` with a 1 prepended)

```
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA1;;⁶
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’          288824892868083015619552399 (compressed representation)
              œ?ØA      th permutation of the alphabet
                  1;    prepend 1
                    ;⁶  append a space

```

**Main program**

```
×107ÆE¢×UḢ¡t⁶
×107           Multiply {the input} by 107
    ÆE         Convert to a list of frequencies for each factor
      ¢×       {Vectorized} multiply by the return value of 1£
        UḢ¡    Delete the first value, reverse the list that many times
           t⁶  Delete trailing/leading space

```

I have a feeling that my compression of the list easily beats the other Jelly answer, but that my algorithm for using it could be a lot more efficient. Maybe I'll try to combine them.

# Jelly, 31 bytes, inspired by @Leakynun's answer

```
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA⁷;
ÆfÆCị¢U⁸¡U

```

Try it online! (slightly modified to run a lot faster)

Is inconsistent in whether it prints a trailing newline (but PPCG normally allows answers either with or without a trailing newline, so I guess this works too?). Is *very* slow (O(*n*) where *n* is the input, and those numbers aren't exactly small…)

## Explanation

**Helper constant**  (produces `“¶SPMFLQUIXNCWORAGZTEJHVDBKY”`, where  is newline)

```
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA⁷;
“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’          288824892868083015619552399 (compressed representation)
              œ?ØA      th permutation of the alphabet
                  ⁷;    prepend newline

```

**Main program**

```
ÆfÆCị¢U⁸¡U
Æf          Produce list of prime factors (repeating repeated factors)
  ÆC        Map the nth prime to n
    ị¢      Index into the output of 1£
      U     Reverse
        ¡   a number of times
       ⁸    equal to the input
         U  Reverse again

```
> 11 votes

# Answer
# 05AB1E, ~~39~~ 38 bytes

```
ÒW<iR¨}26LØR•6Ê2"£´õþÕàçŸôëÂÛ*™•36BS:J

```

Uses the **CP-1252** encoding. Try it online!
> 9 votes

# Answer
# Ruby, ~~139~~ ~~138~~ ~~134~~ ~~125~~ ~~120~~ 115+7 = ~~146~~ ~~145~~ ~~141~~ ~~132~~ ~~127~~ 122 bytes

Uses the `-rprime` flag for +7 bytes.

-1 byte from @daniero. -4 bytes by remembering that I can just do a regular divisibility check instead of checking the prime division for the existence of `2`.

-9 bytes from @mbomb007's Python solution reminding me of a shorter way to retrieve the matching letter.

-5 bytes because trailing whitespace is now allowed.

-5 bytes from discovering `Enumerable#find_index`

```
->n{x=Prime.prime_division n;x.reverse!if n%2<1;x.map{|i,c|" SPMFLQUIXNCWORAGZTEJHVDBKY"[Prime.find_index i]*c}*''}

```

Try it online! (all test cases)

### Explanation

```
->n{                                   # Anonymous procedure with one argument n
    x=Prime.prime_division n;          # Get prime factorization of n, sorted
                                       # p0^e0 * p1^e1 ... -> [[p0,e0],[p1,e1],...]
    x.reverse!if n%2<1;                # Reverse if divisible by 2
    x.map{|i,c|                        # For each prime/exponent pair:
        " SPMFLQUIXNCWORAGZTEJHVDBKY"[ # Get corresponding character by obtaining:
            Prime.find_index i]        # Determine index of the current prime
                               *c      # Repeat the letter by the supplied exponent
                                 }*''} # Join all letter sequences together

```
> 9 votes

# Answer
# Python 2, ~~220~~ 217 bytes

```
n=input()
i=1
L=[]
exec'i+=1;c=0\nwhile n%i<1:c+=1;n/=i\nif c:L+=[i]*c\n'*n
T='SPMFLQUIXNCWORAGZTEJHVDBKY'
print''.join(T[[p for p in range(3,104)if all(p%k for k in range(2,p))].index(q)]for q in[L,L[:0:-1]][L[0]<3])

```

**Try it online** \- *only runs the smallest test case without running out of memory*

### Ungolfed:

This version doesn't use `exec`, so you can actually test all of the test cases without running out of memory.

```
n=input()
i=1
L=[]
while~-n:
 i+=1;c=0
 while n%i<1:c+=1;n/=i
 if c:L+=[i]*c
if L[0]<3:L=L[:0:-1]
T='SPMFLQUIXNCWORAGZTEJHVDBKY'
print''.join(T[[p for p in range(3,104)if all(p%k for k in range(2,p))].index(q)]for q in L)

```

**Try it online**
> 8 votes

# Answer
# Bash + GNU utilities + bsd-games package, 170

Seems pretty non-optimal, but it works:

```
p='printf %03d\n'
a=(`factor $1`)
x=$[a[1]<3]
$p `primes 3 104`|paste - <(fold -1<<<SPMFLQUIXNCWORAGZTEJHVDBKY)|join -o1.2 - <($p ${a[@]:x+1})|(((x))&&tac||cat)|tr -d \\n

```

Try it online.
> 8 votes

# Answer
# Japt, ~~51~~ 50 bytes

49 bytes of code, +1 for the `-P` flag.

```
%2?Uk :Uk Åw)£`yspmflquixncÙgz’jhvdbk`g#ho fj bX

```

Try it online!

This could be way shorter if only Japt had a couple more features...

### Explanation

``yspmflquixncÙgz’jhvdbk`` is just the same string everyone else is using compressed as much as Japt can compress it (3 bytes shorter than the original!). Japt's only built-in compression tool at the moment replaces common pairs of lowercase letter with a single-byte char.

So let's examine the actual code:

```
%2?Uk :Uk Å  w)
%2?Uk :Uk s1 w)
%2?             // If the input mod 2 is non-zero,
   Uk           //   take the prime factors of the input (U).
      :Uk       // Otherwise, take the prime factors of the input,
          s1 w  //   slice off the first one (2), and reverse.

```

Then `£` is used to replace each item `X` in the result like this:

```
"string"g#h o fj bX
"string"g104o fj bX

         104o         // Create the range [0...104).
              fj      // Filter to only items Z where Z.j() is truthy (Z is prime).
                      // This results in the list of prime numbers from 2 to 103.
                 bX   // Take the index of X in this list.
"string"g             // Get the char in the compressed string at that index.
                      // For `y`, the index is 26, but since the string is only 26 chars
                      // long, Japt wraps around and grabs the first char in the string.

```

The result is an array of characters at this point, so the `-P` flag joins it into a single string, and the result is implicitly sent to output.
> 6 votes

# Answer
# Jelly, 33 bytes

```
ÆfÆCUṖ$¹e@?1’ị“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?ØA¤

```

**Try it online!**
> 6 votes

# Answer
# Pyth, ~~54~~ 47 bytes

7 bytes thanks to isaacg

```
s__W%Q2@L."AZ❤O❤❤❤❤❤❤Q❤9❤❤×❤❤"xL_MP#r_3_103-PQ2

```

( represents an unprintable character)

Pyth doesn't have many prime built-ins...

Hexdump:

```
0000000: 73 5f 5f 57 25 51 32 40 4c 2e 22 41 5a 03 4f f3 s__W%Q2@L."AZ.O.
0000010: 14 af 15 ed f5 51 90 39 d5 18 d7 20 a8 22 78 4c .....Q.9... ."xL
0000020: 5f 4d 50 23 72 5f 33 5f 31 30 33 2d 50 51 32    _MP#r_3_103-PQ2

```

Try it online!
> 5 votes

# Answer
# Jelly, 40 bytes

```
Æfḟ2ÆCṚ⁸Ḃ¤¡Ṛị“YSPMFLQUIXNCWORAGZTEJHVDBK

```

Try it online!

Verify all testcases at once! (slightly modified)
> 5 votes

# Answer
# , 59 bytes

```
'SPMFLQUIXNCWORAGZTEJHVDBKY'{~(p:>:i.26)i.[:|.@}.^:(2={.)q:

```

Try it online!

Quite simple...

```
'SPMFLQUIXNCWORAGZTEJHVDBKY'{~(p:>:i.26)i.[:|.@}.^:(2={.)q:
                              (p:>:i.26)                      first 26 primes after 2
                                        i.                    for which the indices is
                                                         q:   prime factors
                                            |.@}.             remove first and reverse
                                                 ^:           if
                                                   (2={.)     the first entry is 2
                            {~                                reverse index
'..........................'                                  hardcoded string

```
> 5 votes

# Answer
# PHP, 173 Bytes

```
for($i=2;1<$n=&$argn;$n%$i?++$i:$r[]=$i.!$n/=$i)for($t=$i;$i>2&!$w[$i]&&$i%--$t;$t>2?:$w[$i]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]);$r[0]>2?:rsort($r);foreach($r as$s)echo$w[$s];

```

Online Version

Expanded

```
for($i=2;1<$n=&$argn; # loop till input is 1
$n%$i?++$i:$r[]=$i.!$n/=$i) #after loop add value to result if input is divisible and divide input
  for($t=$i;$i>2&!$w[$i]&&$i%--$t; # loop if number is gt 2 and not in letter array till number is divisible
  $t>2?:$w[$i]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]) # if is prime add to letter array
  ; # make nothing in the loop
$r[0]>2?:rsort($r); # reverse result array if 2 is in result array
foreach($r as$s) # loop result array
  echo$w[$s]; # Output

```

# PHP, 178 Bytes

```
for($z=2;$p<26;$t>1?:$w[$z]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++])for($t=++$z;$z%--$t;);for($i=2;1<$n=&$argn;)$n%$i?++$i:$r[]=$i.!$n/=$i;$r[0]>2?:rsort($r);foreach($r as$s)echo$w[$s];

```

Online Version

Expanded

```
for($z=2;$p<26;
$t>1?:$w[$z]=SPMFLQUIXNCWORAGZTEJHVDBKY[$p++]) # after loop if is prime add to letter array
  for($t=++$z;$z%--$t;);
for($i=2;1<$n=&$argn;)  # loop till input is 1
  $n%$i?++$i:$r[]=$i.!$n/=$i; #add value to result if input is divisible and divide input
$r[0]>2?:rsort($r); # reverse result array if 2 is in result array
foreach($r as$s) # loop result array
  echo$w[$s]; # Output

```
> 3 votes

# Answer
# Vyxal, 27 bytes

```
∆Ǐḣ«
‹ṀnΠ⌈≈Ǐ¶¨≤½꘍Qr←«f*∑$ßṘ

```

Try it Online! Port of Dennis' Jelly answer.

```
∆Ǐ             # Exponents of prime factors
  ḣ            # Remove the first item and leave it on the stack
   «...«f      # Compressed string "spmflquixncworagztejhvdbky", as a char list
         *∑    # Repeat each character by its corresponding exponent, and concatenate
           $ß  # If the popped item is nonzero (i.e. factor of 2)
             Ṙ # Then reverse the string

```
> 2 votes

# Answer
# Python, 1420 bytes

```
lambda x:(lambda a,b,e,k,l,m,q,p:len.__name__[:a].join(dict(zip((lambda n:(lambda n,f,g:f(n,e,[],f,g))(n,lambda n,i,r,f,g:g(n,i+b,r,f,g)if i<n else r,lambda n,i,r,f,g:f(n,i,[r,r+[i]][all(i%x!=a for x in[e]+r)],f,g)))(l*e*(k*l+b)),(lambda n,o,t:(lambda n,f,g:f(n, len.__name__[:a],f,g))(n,lambda n,s,f,g:g(n,s,f,g)if n>o else s,lambda n,s,f,g:f(n//t,s+chr(n%t),f,g)))((((((k<<e)-b)<<m)+m)<<((k<<q)+(k<<b)))+(((((k<<e)-b)<<e)+b)<<((k<<q)-(b<<b)))+((((((b<<k)+b))<<l)+b)<<((((k<<e)-b)<<l)+(b<<b)))+(((((k<<e)-b)<<l)-k)<<((m<<m)+p))-(((p<<m)-b)<<((m<<m)-(b<<b)))+(((m<<k)+b)<<((((m<<e)-b)<<k)-(b<<b)))+(((((k<<e)-b)<<l)-m)<<((((b<<l)+b)<<k)+k))-(((((b<<l)-b)<<l)-p)<<((b<<p)+(b<<b)))-(((p<<k)-b)<<((((b<<l)-b)<<k)+k))-(((k<<q)-b)<<((p<<l)))+(((m<<m)+m)<<((((k<<e)+b)<<k)-b))-(((k<<m)+b)<<((k<<m)-b))-(((m<<m)+k)<<((((k<<e)-b)<<k)-(b<<b)))+(((((k<<e)+b)<<e)+b)<<((m<<l)-(b<<e)))-(((((k<<e)+b)<<e)+b)<<((((b<<l)+b)<<e)-b))+((((((b<<k)+b))<<k)+b)<<((p<<k)))+(((((k<<e)-b)<<k)-k)<<((k<<l)))+(((m<<l)+b)<<((m<<k)))+(((m<<e)-b)<<((b<<m)+(b<<b)))+((((((b<<k)+b))<<e)-b)<<((k<<k)+b))+(((m<<k)-b)<<((b<<l)+b))-((((k<<e)-b))<<((k<<e)))+(((m<<e)+b)<<e)-b,b,b<<l*e)))[i]for i in(lambda x: [x.remove(e), x[::-b]][b] if e in x else x)((lambda x:(lambda x,g,h:g(x,b,[],g,h))(x,lambda x,n,r,g,h:h(x,n+b,r,g,h)if x>b else r,lambda x,n,r,g,h:h(x//n,n,r+[n],g,h)if x%n==a else g(x,n,r,g,h)))(x))))(*[x for x in range(True<<len(len.__name__))])

```

This could definitely by shorted some, but it's my attempt at solving it with no numbers or string literals. I realize this is a code-golf problem and this isn't *exactly* short but wanted to share anyway, not sure if this breaks any rules or not.

Was a lot of fun to make, I used the algorithm on this blog post to reduce the ASCII numerical representation of "SPMFLQUIXNCWORAGZTEJHVDBKY" in to the bit-shift expression I use. I also generally took a lot of inspiration from this blog, I wanted to try it out myself and this seemed like a good challenge to do it with.

Here is a slightly more readable version, with some more sensible variable names too
> 1 votes

---
Tags: code-golf, string, primes, cipher
---


title: Zigzagify a Matrix

text:
# Question
Title: Zigzagify a Matrix
As part of its compression algorithm, the JPEG standard unrolls a matrix into a vector along antidiagonals of alternating direction:

Your task is to take a matrix (not necessarily square) and return it in unrolled form. As an example:

```
[1 2 3 4
 5 6 7 8
 9 1 2 3]

```

should yield

```
[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]

```

## Rules

You may assume that the matrix elements are positive integers less than `10`.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

The input matrix may be given in any convenient, unambiguous, nested list or string format, or as a flat list along with both matrix dimensions. (Or, of course, as a matrix type if your language has those.)

The output vector may be in any convenient, unambiguous, flat list or string format.

Standard rules apply.

## Test Cases

```
[[1]]                                               => [1]
[[1 2] [3 1]]                                       => [1 2 3 1]
[[1 2 3 1]]                                         => [1 2 3 1]
[[1 2 3] [5 6 4] [9 7 8] [1 2 3]]                   => [1 2 5 9 6 3 4 7 1 2 8 3]
[[1 2 3 4] [5 6 7 8] [9 1 2 3]]                     => [1 2 5 9 6 3 4 7 1 2 8 3]
[[1 2 6 3 1 2] [5 9 4 7 8 3]]                       => [1 2 5 9 6 3 4 7 1 2 8 3]
[[1 2 5 9 6 3 4 7 1 2 8 3]]                         => [1 2 5 9 6 3 4 7 1 2 8 3]
[[1] [2] [5] [9] [6] [3] [4] [7] [1] [2] [8] [3]]   => [1 2 5 9 6 3 4 7 1 2 8 3]

```

## Related Challenges

# Answer
> 31 votes
# J, 31 30 14 12 11 bytes

```
[:;<@|.`</.

```

Ych. Too big.

Takes a matrix as input.

**Explanation**

J has an advantage here. There's a command called oblique (`/.`) which takes the oblique lines in turn and applies a verb to them. In this case I'm using a gerund to apply two verbs alternately: `<` (box) and `<@|.` (reverse and box). Then it's just a matter of unboxing everything using `;` (raze).

# Answer
> 13 votes
# Jelly, ~~24~~ ~~19~~ ~~15~~ ~~13~~ 11 bytes

```
pS€żị"¥pỤị⁵

```

Takes number of rows, number of columns and a flat list as separate command-line arguments.

Try it online!

### How it works

```
pS€żị"¥pỤị⁵  Main link. Argument: m (rows), n (columns), A (list, flat)

p            Compute the Cartesian product [1, ..., m] × [1, ..., n]. This yields
             the indices of the matrix M, i.e., [[1, 1], [1, 2], ..., [m, n]].
 S€          Compute the sums of all index pairs.
       p     Yield the Cartesian product.
      ¥      Dyadic chain. Arguments: Sums, Cartesian product.
    ị"       For each index pair in the Cartesian product, retrieve the coordinate
             at the index of its sum, i.e., map [i, j] to i if i + j is odd and to
             j if i + j is even.
   ż         Zip the sums with the retrieved indices.
       Ụ     Sort [1, ..., mn] by the corresponding item in the resulting list.
        ị⁵   Retrieve the corresponding items from A.

```

# Answer
> 11 votes
## Pyth, ~~24~~ ~~23~~ ~~21~~ ~~20~~ ~~19~~ ~~18~~ 17 bytes

```
ssm_W=!Td.T+LaYkQ

```

Alternate 17-byte version: `ssuL_G=!T.T+LaYkQ`

```
                Q  input
           +L      prepend to each subarray...
             aYk   (Y += ''). Y is initialized to [], so this prepends [''] to
                     the first subarray, ['', ''] to the second, etc.
                   ['' 1  2  3  4
                    '' '' 5  6  7  8
                    '' '' '' 9  1  2  3]
         .T        transpose, giving us
                   ['' '' ''
                    1  '' ''
                    2  5  ''
                    3  6  9
                    4  7  1
                    8  2
                    3]
  m_W=!Td          black magic
 s                 join subarrays together
s                  join *everything* on empty string (which means ''s used for
                     padding disappear)

```

Thanks to @FryAmTheEggman for a byte, @Jakube for 2 bytes, and @isaacg for a byte!

Explanation of "black magic" alluded to above: `m_W=!Td` essentially reverses every other subarray. It does this by mapping `_W=!T` over each subarray; `W` is conditional application, so it `_`s (reverses) all subarrays where `=!T` is true. `T` is a variable preinitialized to ten (truthy), and `=!T` means `(T = !T)`. So it toggles the value of a variable that starts out truthy and returns the new value, which means that it will alternate between returning falsy, truthy, falsy, truthy... (credit to Jakube for this idea)

Test suite here.

# Answer
> 7 votes
# MATL, ~~28~~ 27 bytes

```
tZyZ}:w:!+-1y^7MGn/*-X:K#S)

```

Adapted from my answer here. The general idea is to create a 2D array of the same size as the input, filled with values that increase in the same order as the zig-zag path. Then the linearized (flattened) version of that array is sorted, and the *indices* of that sorting are kept. Those are the indices that need to be applied to the input in order to produce the zig-zag path.

Input is in the form

```
[1 2 3; 5 6 4; 9 7 8; 1 2 3]

```

### Explanation

**Try it online!**

```
t       % input 2D array. Duplicate
ZyZ}    % get size as length-2 vector. Split into two numbers: r, c
:       % range [1,2,...,c] as a row vector
w:!     % swap, range [1;2;...;r] as a column vector
+       % add with broadcast. Gives a 2D array
-1      % push -1
y^      % duplicate previous 2D array. Compute -1 raised to that
7M      % push [1;2;...;r] again
Gn/     % divide by input matrix size, that is, r*c
*       % multiply
-       % subtract
X:      % linearize 2D array into column array
K#S     % sort and push the indices of the sorting. Gives a column vector
)       % index input matrix with that column vector

```

# Answer
> 6 votes
# Matlab, 134 bytes

I just tried my best to shorten my code in Matlab, like telegraphing it.

```
function V=z(M)
[m,n]=size(M);
a=(1:m)'*ones(1,n);
b=ones(m,1)*(1:n);
A=a+b-1;
B=a-b;
C=(A.^2+(-1).^A.*B+1);
[~,I]=sort(C(:));
V=M(:);
V=V(I)';

```

Notes:

1. `M` is an `m×n` matrix.
2. `a` and `b` are both matrices same size of `M`, each row of `a` consists of numbers equal to its row number, while each column of `b` is equal to its column number. Thus, `a`+`b` is a matrix whose element equals to sum of its row and column number, i.e., `matrix(p,q)=p+q`.
3. Thus, `A(p,q)=p+q-1`; and `B(p,q)=p-q`.
4. `C` is mathematically stated as equation below.  with the equation, a zigzagifiedly increasing matrix can be made like shown below.

> ```
> C =
>      1     2     6     7
>      3     5     8    14
>      4     9    13    18
>     10    12    19    25
>
> ```

5. `C` indicates the order of elements of M in zigzagified results. Then, `[~,I]=sort(C(:));`returns the order, i.e., `I`, thus, `V=V(I)'` is the result.

# Answer
> 3 votes
# JavaScript (SpiderMonkey 30+), 99 bytes

```
x=>[for(y of[...x,...x[0]].keys())for(z of Array(y+1).keys())if(a=x[y%2?z:y-z])if(b=a[y%2?y-z:z])b]

```

Tested in Firefox 44. Takes input as a 2D array.

# Answer
> 3 votes
## Python 2, 84 bytes

```
lambda N,w,h:[N[i*w+s-i]for s in range(w+h+1)for i in range(h)[::s%2*2-1]if-1<s-i<w]

```

Porting nimi's answer. Takes a flat array with given width and height. xsot saved a byte.

---

**88 bytes:**

```
lambda M,w,h:[M[i]for i in sorted(range(w*h),key=lambda i:(i/w+i%w,-i*(-1)**(i/w+i%w)))]

```

Takes a flat array with given width and height. Sorts the corresponding 2D coordinates `(i/w,i%w)` in zigzag order of increasing sum to get diagonals, tiebroken by either increasing or decreasing row value, based on whether the row plus column is odd or even.

# Answer
> 3 votes
## Haskell, ~~79~~ ~~78~~ 73 bytes

```
(m#h)w=[m!!(y*w+x-y)|x<-[0..h+w],y<-g!!x$[0..x],y<h,x-y<w]
g=reverse:id:g

```

The input is a flat list with the number of rows and columns, e.g. `( [1,2,6,3,1,2,5,9,4,7,8,3] # 2) 6` -\> `[1,2,5,9,6,3,4,7,1,2,8,3]`.

How it works: walk through the x and y coordinates of the matrix (`h` rows, `w` columns) in two nested loops:

```
  | 0 1 2 3 4 5 6 7 8    outer loop               Index is y*w+x-y, i.e.
--+------------------    x from 0 to h+w          the elements are accessed
0 | 1 2 6 3 1 2                                   in the following order:
1 | 5 9 4 7 8 3
2 |                                               1 2 4 6  8 10
3 |                                               3 5 7 9 11 12
4 |
5 |
6 |
7 | inner loop:
8 | y from 0 to x

```

i.e. from top/right to down/left, skipping out of bound indices (`y` and `x` must satisfy `y<h` and `x-y<w`). When `x` is even, the order of the inner loop is reversed: `y` goes from `x` to `0`. I do this by picking a modifying function for the y-range `[0..x]` which is the `x`th element of `[reverse,id,reverse,id,...]`.

Edit: @xnor re-arranged the loops and saved 5 bytes. Thanks!

# Answer
> 3 votes
# Husk, 6 bytes

```
Σz*İ_∂

```

Try it online!

Same idea as Zgarb's Boustrophedonize solution.

# Answer
> 3 votes
# K (ngn/k), ~~50~~ 41 bytes

-9 Can use odometer directly

```
{(,/x)@,/((#c)#(|:;::))@'c:.=+/!#'(x;*x)}

```

Try it online!

# Answer
> 2 votes
# Julia 0.7, ~~114~~ 85 bytes

```
^ =size
~A=[[i%2<1?reverse(x):x for(i,x)=pairs(-A^2:A^1.|>x->diag(rotl90(A),x))]...;]

```

Try it online!

Takes the antidiagonals (rotates and takes the main diagonals), reverses every other one, and flattens the list.

-29 bytes thanks to MarcMush:

* replace `A[end:-1:1,1:end]` with `rotl90(A)` to rotate the matrix
* rewrite with `pairs` instead of `eachindex`
* to flatten a vector of vectors `Q`, use `[Q...;]` instead of `vcat[Q...]`

# Answer
> 2 votes
# Vyxal, 6 bytes

```
Þ`⁽ṘẆf

```

Try it Online!

```
Þ`     # Antidiagonals
  ⁽ Ẇ  # To every other item
   Ṙ   # Reverse
     f # Flatten

```

# Answer
> 1 votes
# Python 2 + NumPy, 122 bytes

I admit it. I worked ahead. Unfortunately, this same method cannot be easily modified to solve the other 2 related challenges...

```
import numpy
def f(m):w=len(m);print sum([list(m[::-1,:].diagonal(i)[::(i+w+1)%2*-2+1])for i in range(-w,w+len(m[0]))],[])

```

Takes a numpy array as input. Outputs a list.

**Try it online**

### Explanation:

```
def f(m):
    w=len(m)    # the height of the matrix, (at one point I thought it was the width)
    # get the anti-diagonals of the matrix. Reverse them if odd by mapping odd to -1
    d=[list(m[::-1,:].diagonal(i)[::(i+w+1)%2*-2+1])for i in range(-w,w+len(m[0]))]
            # w+len(m[0]) accounts for the width of the matrix. Works if it's too large.
    print sum(d,[]) # join the lists

```

A lambda is the same length:

```
import numpy
lambda m:sum([list(m[::-1,:].diagonal(i)[::(i+len(m)+1)%2*-2+1])for i in range(-len(m),len(m)+len(m[0]))],[])

```

# Answer
> 1 votes
## Python 3, ~~131~~ ~~118~~ ~~115~~ 107 bytes

Based on the same principe as my answer of Deusovi's challenge

I assume we can't have zero in the input matrice

```
e=enumerate
lambda s:[k for j,i in e(zip(*[([0]*n+i+[0]*len(s))for n,i in e(s)]))for k in i[::j%2*2-1]if k]

```

## Explanation

how it works :

```
            pad with 0      transpose    remove 0    reverse line           concatenate
                                                     with even index
1 2 3       1 2 3 0 0        1 0 0        1            1
4 5 6   --> 0 4 5 6 0    --> 2 4 0    --> 2 4     -->  2 4              -->  1 2 4 7 5 3 6 8 9
7 8 9       0 0 7 8 9        3 5 7        3 5 7        7 5 3
                             0 6 8        6 8          6 8
                             0 0 9        9            9

```

## Results

```
>>> [print([i,f(i)]) for i in [[[1]], [[1, 2], [3, 1]], [[1, 2, 3, 1]], [[1, 2, 3], [5, 6, 4], [9, 7, 8], [1, 2, 3]], [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]], [[1, 2, 6, 3, 1, 2], [5, 9, 4, 7, 8, 3]], [[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]], [[1], [2], [5], [9], [6], [3], [4], [7], [1], [2], [8], [3]]]]
# [input,                                                          output]
[[[1]],                                                            [1]]
[[[1, 2], [3, 1]],                                                 [1, 2, 3, 1]]
[[[1, 2, 3, 1]],                                                   [1, 2, 3, 1]]
[[[1, 2, 3], [5, 6, 4], [9, 7, 8], [1, 2, 3]],                     [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]]
[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3]],                       [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]]
[[[1, 2, 6, 3, 1, 2], [5, 9, 4, 7, 8, 3]],                         [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]]
[[[1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]],                           [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]]
[[[1], [2], [5], [9], [6], [3], [4], [7], [1], [2], [8], [3]],     [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3]]

```

# Answer
> 0 votes
# 05AB1E, 11 bytes

```
ΣN²‰ÐOŠO<è‚

```

Inputs as `flattened_list, width, height` (even though I ignore the `height` input).

Try it online or verify all test cases.

**Explanation:**

The actual sorting algorithm is a direct port of my 05AB1E answer for the *Traverse a rectangle's antidiagonals* challenge. Even though the actual path over the matrix is different for both challenges, that linked challenge uses \\$y,x\\$ as coordinates, whereas I use \\$x,y\\$ here, so the actual sorting implementation is basically the exact same.

```
Σ            # Sort the first (implicit) input-list by:
 N           #  Push the 0-based sort-index
  ²‰         #  Divmod it by the second input-width
    Ð        #  Triplicate this coordinate
     O       #  Sum the top pair together
      Š      #  Tripleswap from pair,pair,sum to sum,pair,pair
       O     #  Sum the top pair together again
        <    #  Decrease it by 1
         è   #  Modular 0-based index this sum-1 into the pair
          ‚  #  Pair it together with the other sum
             # (after which the sorted list is output implicitly)

```

Just like in my linked answer, there are a few equal-bytes alternatives for `ÐOŠO<è‚` (not as many as in the linked answer, since we don't have access to the pair as variable `y` here, since we've just created the pair manually with `N²‰`):

```
RDODŠè‚
ÐO<è‚€O
...

```

# Answer
> 0 votes
# JavaScript (Node.js), 89 bytes

```
a=>a.flatMap((b,i)=>b.map((c,j)=>({c,k:++i-j/(-2)**i}))).sort((p,q)=>p.k-q.k).map(x=>x.c)

```

Try it online!

---
Tags: code-golf, array, matrix
---


title: Make me a s'more!

text:
# Question
Title: Make me a s'more!
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:

# Answer
> 1 votes
# 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.

```

# Answer
> 13 votes
# 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)`

# Answer
> 7 votes
# 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)

# Answer
> 7 votes
# 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

```

# Answer
> 7 votes
# 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)
)
```

# Answer
> 6 votes
# 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

```

# Answer
> 6 votes
## 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

# Answer
> 5 votes
# 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]

```

# Answer
> 4 votes
# 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!

# Answer
> 4 votes
# 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.

# Answer
> 3 votes
## 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.

# Answer
> 3 votes
# , 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

```

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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)

```

# Answer
> 3 votes
# 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

```

# Answer
> 2 votes
# Python 2, ~~67~~57 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

```

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# 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!**

# Answer
> 2 votes
# 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));
}

```

# Answer
> 2 votes
# 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

# Answer
> 2 votes
# 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;
}

```

# Answer
> 1 votes
# 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)

```

# Answer
> 1 votes
# Convex, 20 bytes

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

```

Try it online!

# Answer
> 1 votes
# 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>
```

# Answer
> 1 votes
# 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))
```

# Answer
> 1 votes
# 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

# Answer
> 1 votes
# Java 11, ~~226~~ ~~171~~ 132 bytes

```
(w,g,c,m)->{x(w,"G",g);x(w,"C",c);x(w,"M",m);x(w,"G",g);};void x(int w,String c,int x){for(;x-->0;)System.out.println(c.repeat(w));}

```

-55 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
(w,g,c,m)->{            // Main method with four integer parameters and String return-type
  x(w,"G",g);           //  Print all Graham rows
  x(w,"C",c);           //  Print all Chocolate rows
  x(w,"M",m);           //  Print all Marshmallon rows
  x(w,"G",g);}          //  Print all Graham rows again

void x(int w,String c,int x){
                        // Separated method with two integer & character parameters and
                        // String return-type
  for(;x-->0;)          //  Loop `x` amount of times:
    System.out.println( //   Print with trailing newline:
      c                 //    The given character `c`
       .repeat(w));}    //    repeated `w` amount of times

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Google Sheets, 103 Bytes

Anonymous Google Sheets worksheet formula that takes input from cells `A1,B1,C1,D1` and outputs a s'more to the calling cell

```
=REPT(REPT("G",A1)&"
",B1)&REPT(REPT("C",A1)&"
",C1)&REPT(REPT("M",A1)&"
",D1)&REPT(REPT("G",A1)&"
",B1

```

# Answer
> 1 votes
# K (oK), ~~32~~ 17 bytes

**Solution:**

```
{x#',/4#y#'"GCM"}

```

Try it online!

**Example:**

```
> {x#',/4#y#'"GCM"}[10;(3;2;1)]
("GGGGGGGGGG"
 "GGGGGGGGGG"
 "GGGGGGGGGG"
 "CCCCCCCCCC"
 "CCCCCCCCCC"
 "MMMMMMMMMM"
 "GGGGGGGGGG"
 "GGGGGGGGGG"
 "GGGGGGGGGG")

```

**Explanation:**

```
{x#',/4#y#'"GCM"} / solution
{               } / lambda function with implicit parameters x and y
        y#'"GCM"  / take input each-both (#') number "G", "C" and "M"
      4#          / 4-take, ("GGG";"CC";"M") -> ("GGG";"CC";"M";"GGG")
    ,/            / flatten list into string, ("GGG";"CC";"M";"GGG") -> "GGGCCMGGG"
 x#'              / width-take each (10#"G" -> "GGGGGGGGGG" etc)

```

**Notes:**

* -15 bytes as looking through other answers it seems acceptable to take parameters as `[width;(graham;chocolate;marshmallow)]`, which means I don't have to explicitly list the parameters to the function

# Answer
> 1 votes
# Canvas, ~~12~~ 11 bytes

```
GCMG｛²└＠＊×Ｐ

```

Try it here!

Explanation:

```
GCMG     push "GCMG"
  {      for each character
   ²       push the counter.                     Stack: [(input2, input1), "G", 1]
    └      swap two items below ToS.             Stack: [(I1, I2), "G", I1, 1]
     @     get the counter'th item of the input. Stack: [(I1, I2), "G", I1[1] ]
      *    repeat horizontally.                  Stack: [(I1, I2), "G" * I1[1] ]
       ×   repeat vertically.                    Stack: [(I2, I1), I2 × "G" * I1[1] ]
        P  print that.                           Stack: [(I2, I1)]

```

# Answer
> 1 votes
# , 69 bytes

```
function(n,u)cat(rep(strrep(c("G","C","M","G"),n),c(u,u[1])),sep="
")

```

Try it online!

Trying this `strrep` function I just heard about... Probably a `intToUtf8` approach could do better than that. Thanks @Shaggy for pointing an issue...fixing it saved 6 bytes.

# Answer
> 1 votes
# Vyxal, 11 bytes

```
`GCM`f*εǏf⁋

```

Try it Online!

```
`GCM`f      # "GCM" as a char list
      *     # repeat each by width
       ε    # repeat each by input size amounts
        Ǐ   # Append the first item
         f  # Flatten
          ⁋ # Join by newlines

```

# Answer
> 1 votes
# , 14 bytes

```
#&>'GCMG'#~4&$

```

Attempt This Online!

Takes input as `10 f 3 2 1` for the example test case.

```
#&>'GCMG'#~4&$
           4&$    Cycle the right side to length 4; [3 2 1 3]
   'GCMG'#~       Repeat each char of GCMG that many times; 'GGGCCMGGG'
#&>               Repeat each char `left side` times and stack them into a matrix

```

# Answer
> 0 votes
## 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}`

# Answer
> 0 votes
## R, ~~117~~ 114 bytes

```
f=function(w,g,h,m){s=strrep;f=function(a,b)s(paste0(s(a,w),'\n'),b);G=f("G",g);cat(G,f("C",h),f("M",m),G,sep='')}

```

Explanation:

```
function(w,g,h,m){              #width, graham, chocolate, marshmallow
  s=strrep                      #repeats strings (for each layer)
  f=function(a,b){              #for a given layer
    s(paste0(s(a,w),'\n'),b)    #repeat the corresponding letter w times, then repeat that + a newline the corresponding number of times
  }
  G=f("G",g)
  cat(                        #print to console:
      G,                 #so repeat "G" w times, over g lines
      f("C",h),                 #etc.
      f("M",m),
      G,sep='')        #with no separation
}

```

*Saved 3 bytes thanks to @Giuseppe!*

# Answer
> 0 votes
# 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'

```

# Answer
> 0 votes
# Japt, 30 26 bytes

```
"GCMG"¬mpU £XÄ pVgY)q1Ãm·q

```

Try it online!

30-byte solution:

```
Y=VÆ'GpUÃ·[YWÆ'CpUÃ·XÆ'MpUÃY]·

```

Try it online!

# Answer
> 0 votes
# T-SQL, 259 bytes

```
CREATE PROC S @ INT,@g INT,@c INT,@m INT,@b INT=0 AS SET @B=@G G:PRINT REPLICATE('G',@)SET @G-=1IF @G>0 GOTO G C:PRINT REPLICATE('C',@)SET @C-=1IF @C>0GOTO C M:PRINT REPLICATE('M',@)SET @M-=1IF @M>0GOTO M Q:PRINT REPLICATE('G',@)SET @B-=1IF @B>0 GOTO Q RETURN

```

This stored procedure loops for the first layer or graham, chocolate, and Marshmallow with a `GOTO` in order to print up to the established amount. For the last layer of graham the fourth optional parameter (previously setted to the @g value) is used to do the same as the first layer of graham. The width of the layer is created with the `REPLICATE` function.

Usage:

```
EXECUTE S @ = 5, --Width
    @g = 7, --Graham
    @c = 8, --Chocolate
    @m = 4, --Marshmallow
    @b = NULL --Control variable, can be ignored

```

# Answer
> 0 votes
# Charcoal, 23 bytes

```
↷²Ｎγ×⟦⁺⁺⁺×Gγ×CＮ×MＮ×Gγ⟧Ｎ

```

Try it online!

Input is in the form `graham`, `chocolate`, `marshmallow`, `width`

## Explanation

```
↷²                          Pivot right by 2 * 45 degrees
  Ｎγ                       Input number to g
      ⟦⁺⁺⁺×Gγ×CＮ×MＮ×Gγ⟧   "G" * g + "C" * input number + "M" * input number + "G" * g
     ×                   Ｎ Multiplied by N

```

Lists are implicitly printed joined by newlines.

# Answer
> 0 votes
# SOGL V0.12, 11 bytes

```
GCM”{e*.∙Q≥

```

Try it Here!

Explanation:

```
GCM”         push "GCM"
    {        for each
     e*        multiply horizontally by e, which, when first called, gets the numerical value of the next input
       .∙      multiply vertically by the nest input
         Q     output without popping and without disabling implicit output
          ≥    put the top item of the stack at the bottom as to keep the first item on the top

```

# Answer
> 0 votes
# Japt `-R`, 16 bytes

```
"GCMG"ËpU*VgEÃòU

```

Try it

---

## Explanation

```
                     :Implicit input of integer U=Width & array V=[Graham,Chocolate,Marshmallow]
"GCMG"               :String literal
      Ë              :Map each character at index E
       p             :  Repeat
        U*           :   U multiplied by
          VgE        :   Get the integer at index E in V (Yay, index wrapping!)
             Ã       :End mapping
              òU     :Split to an array of strings of length U
                     :Implicitly join with newlines and output

```

# Answer
> 0 votes
# 05AB1E, ~~14~~ 12 bytes

```
…GCMS×ĆIĆÅΓ»

```

Try it online.

**Explanation:**

```
…GCM          # Push string "GCM"
    S         # Convert it to a list of characters: ["G","C","M"]
     ×        # Repeat each the (implicit) input-integer `w` amount of times as string
              #  i.e. w=4 → ["GGGG","CCCC","MMMM"]
      Ć       # Enclose this list; appending its own head as trailing item
              #  → ["GGGG","CCCC","MMMM","GGGG"]
       IĆ     # Push the second input-list, and enclose it as well
              #  i.e. [3,2,1] → [3,2,1,3]
         ÅΓ   # Run-length decode, repeating the strings the integers amount of times
              #  → ["GGGG","GGGG","GGGG","CCCC","CCCC","MMMM","GGGG","GGGG","GGGG"]
           »  # And join this list by newlines
              #  → "GGGG\nGGGG\nGGGG\nCCCC\nCCCC\nMMMM\nGGGG\nGGGG\nGGGG"
              # (after which the result is output implicitly)

```

---
Tags: code-golf, ascii-art
---