# Question
Title: Find smallest period from a >1000 digit number
Your job is to take this number as input (although it should work with any other number too):

```
18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957

```

and find the smallest period, which is in this case:

```
1834957034571097518349570345710975183495703457109751834957034571097518349570345710976

```

Good luck and have fun!

---

**Clarifications**:

* The input number has in minimum one period and one partial period
* The period always starts at the beginning of the input number
* Period means in this case a sequence of numbers which repeats itself.

# Answer
> 4 votes
# CJam, ~~20~~ 16 bytes

```
Ll:Q{+_Q,*Q#!}=;

```

Reads from STDIN. Try it online.

The above code will require **O(n2)** memory, where **n** is the length of the input. It *will* work with 216 digits, as long as you have enough memory.

This can be fixed the the cost of five extra bytes:

```
Ll:Q{+_Q,1$,/)*Q#!}=;

```

### Example run

```
$ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957; echo
1834957034571097518349570345710975183495703457109751834957034571097518349570345710976
$ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 12345123451; echo
12345
$ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 1234512345; echo
12345
$ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 123451; echo
12345

```

### How it works

For input Q, the idea is to repeat the first character len(Q) times and check if the index of Q in the result is 0. If it isn't, repeat the first *two* characters len(Q) times, etc.

```
L                   " Push L := [].                                                       ";
 l:Q                " Read one line from STDIN and save the result in Q.                  ";
    {        }=     " Find the first element q ∊ Q that yields a truthy value:            ";
     +              "   Execute L += [q].                                                 ";
      _Q,*Q#        "   Push (L * len(Q)).index(Q).                                       ";
            !       "   Compute the logical NOT of the index.                             ";
               ;    " Discard the last q. This leaves L on the stack.                     ";

```

# Answer
> 8 votes
## Regex (.NET flavour), ~~23~~ 22 bytes

```
.+?(?=(.*$)(?<=^\1.*))

```

This will match the required period as a substring.

Test it here.

How does it work?

```
# The regex will always find a match, so there's no need to anchor it to
# the beginning of the string - the match will start there anyway.
.+?        # Try matching periods from shortest to longest
(?=        # Lookahead to ensure that what we've matched is actually
           # a period. By using a lookahead, we ensure that this is
           # not part of the match.
  (.*$)    # Match and capture the remainder of the input in group 1.
  (?<=     # Use a lookahead to ensure that this remainder is the same
           # as the beginning of the input. .NET lookaheads are best
           # read from right to left (because that's how they are matched)
           # so you might want to read the next three lines from the
           # bottom up.
    ^      # Make sure we can reach the beginning of the string.
    \1     # Match group 1.
    .*     # Skip some characters, because the capture won't cover the
           # entire string.
  )
)

```

# Answer
> 3 votes
# Python 60

`s` is the string of digits

```
[s[:i]for i in range(len(s))if(s[:i]*len(s))[:len(s)]==s][0]

```

eg:

```
>>> s = '18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957'
>>> [s[:i]for i in range(len(s))if(s[:i]*len(s))[:len(s)]==s][0]
'1834957034571097518349570345710975183495703457109751834957034571097518349570345710976'

```

# Answer
> 1 votes
# Pyth, 14 characters

```
hf}z*lzTm<zdUz

```

Explanation:

```
implicit:      z = input()
h              head(
 f                  filter(lambda T:
  }z                                z in
    *lz                                  len(z) *
       T                                          T,
  m                        map(lambda d:
   <zd                                  z[:d],
   Uz                                   range(len(d)))))

```

Essentially, it generates all of the initial sequences of the input, repeats each one `len(z)` times, and sees whether `z`, the input, lies within the resultant string.

---

This is not a valid answer, but a feature was recently added to Pyth, after the question was asked, that allows a 12 character solution:

```
<zf}z*lz<zT1

```

This uses the filter on integer feature.

# Answer
> 0 votes
# Japt, 8 bytes

```
å+ æ@¶îX

```

Try it

-2 bytes thanks to Shaggy!

Transpiled JS Explained:

```
// U is the input string representation of the number
U
 // cumulative reduce using the '+' operator
 // the result is an array of strings length 1, 2, ..., N
 // all substrings start with the first character from input
 .å("+")
 // find the first match
 .æ(function(X, Y, Z) {
  // repeat the substring until it is as long as the input
  // and compare it to the input
  return U === U.î(X)
 })

```

# Answer
> 0 votes
# Java 8, 125 bytes

Takes input as a string since there is no reasonable way to represent a 1000+ digit number in Java other than a string (No BigInteger please).

```
s->{String o="";for(int i=0;java.util.Arrays.stream(s.split(o+=s.charAt(i++))).filter(b->!b.isEmpty()).count()>1;);return o;}

```

Try it online!

---
Tags: code-golf
---


title: Sub-pixel Zooming

text:
# Question
Title: Sub-pixel Zooming
Your task is to take a 24 BPP sRGB image and output the same image upscaled 3x into red, green, and blue subpixels. The resulting image will be made entirely of pure black, red, green, and blue pixels.

Each pixel from the source image, when zoomed, produces an arrangement of 9 sub-pixels that can be either on or off (i.e. their respective color or black). The specific arrangement uses three columns of red, green, and blue, in that order, like so:

*(Note that the borders on these "pixels" are for demonstration only.)*

Since each of the nine subpixels can only be on or off, you will have to quantize the input image and use different subpixel patterns to achieve 3 levels of brightness.

For each subpixel in the image:

* For color levels 0-74, all subpixels should be black.
* For color levels 75-134, the middle subpixel should be the respective color and the other two should be black.
* For color levels 135-179, the middle subpixel should be black and the other two should be the respective color
* For color levels 180-255, all three subpixels should be their respective color

*I chose these level ranges because those are what happened to look good*

Apply this transformation to every pixel in the image and output the subpixel-upscaled image.

## Single-pixel examples

rgb(40, 130, 175) will produce this pattern:

rgb(160, 240, 100) will produce this pattern:

# Full Image Examples

*Images sourced from Wikipedia*

# Rules and notes

* Input and output may be in any convenient format, whether that's actual image files or (possibly nested) lists of RGB values.
* You may assume the pixels are in the sRGB colorspace with 24BPP.

Happy golfing!

# Answer
> 4 votes
# JavaScript (Node, Chrome, Firefox), 111 bytes

I/O format: matrix of `[R,G,B]` values.

```
a=>[...a,...a,...a].map((r,y)=>r.flat().map((_,x)=>a[y/3|0][x/3|0].map(v=>x--%3|511+y%3%2*3104>>v/15&1?0:255)))

```

Try it online! (just a single pixel)

### How?

All threshold values are multiples of 15. Instead of doing explicit comparison tests, it's a bit shorter to test a bitmask where each bit represents an interval of 15 values (except the most significant bit which is mapped to a single value).

```
 bit | range   | top/bottom | middle
-----+---------+------------+--------
  0  |   0- 14 |     off    |   off
  1  |  15- 29 |     off    |   off
  2  |  30- 44 |     off    |   off
  3  |  45- 59 |     off    |   off
  4  |  60- 74 |     off    |   off
  5  |  75- 89 |     off    |    on
  6  |  90-104 |     off    |    on
  7  | 105-119 |     off    |    on
  8  | 120-134 |     off    |    on
  9  | 135-149 |      on    |   off
 10  | 150-164 |      on    |   off
 11  | 165-179 |      on    |   off
 12  | 180-194 |      on    |    on
 13  | 195-209 |      on    |    on
 14  | 210-224 |      on    |    on
 15  | 225-239 |      on    |    on
 16  | 240-254 |      on    |    on
 17  |   255   |      on    |    on

```

We encode **off** as \\$1\\$ and **on** as \\$0\\$ in order to maximize the number of leading zeros.

We get:

* `000000000111111111` for top and bottom pixels (\\$511\\$ in decimal)
* `000000111000011111` for the middle pixel (\\$3615\\$ in decimal)

### Commented

```
a =>                      // a[] = input matrix
  [...a, ...a, ...a]      // create a new matrix with 3 times more rows
  .map((r, y) =>          // for each row r[] at position y:
    r.flat()              //   turn [[R,G,B],[R,G,B],...] into [R,G,B,R,G,B,...]
                          //   i.e. create a new list with 3 times more columns
    .map((_, x) =>        //   for each value at position x:
      a[y / 3 | 0]        //     get [R,G,B] from the original matrix
       [x / 3 | 0]        //     for the pixel at position (floor(x/3), floor(y/3))
      .map(v =>           //     for each component v:
        x-- % 3 |         //       1) yield a non-zero value if this is not the component
                          //          that we're interested in at this position
        511 +             //       2) use either 511 for top and bottom pixels
        y % 3 % 2 * 3104  //          or 3615 for the middle pixel (y mod 3 = 1)
        >> v / 15         //          divide v by 15
        & 1               //          and test the corresponding bit
        ?                 //       if either of the above tests is truthy:
          0               //         yield 0
        :                 //       else:
          255             //         yield 255
      )                   //     end of map() over RGB components
    )                     //   end of map() over columns
  )                       // end of map() over rows

```

### Example

The following code snippet processes the head of Mona Lisa (64x64). Doesn't work on Edge.

```
f=
a=>[...a,...a,...a].map((r,y)=>r.flat().map((_,x)=>a[y/3|0][x/3|0].map(v=>x--%3|511+y%3%2*3104>>v/15&1?0:255)))

var img;

(img = new Image).onload = function(){
  var ctx = document.getElementById('c').getContext('2d');
  ctx.drawImage(img, 0, 0);
  var data = ctx.getImageData(0, 0, 192, 192), x, y, ptr, a = [];
  for(ptr = y = 0; y < 64; y++) {
    for(a[y] = [], x = 0; x < 64; x++) {
      a[y][x] = [data.data[ptr++], data.data[ptr++], data.data[ptr++]];
      ptr++;
    }
    ptr += 512;
  }
  a = f(a);
  for(ptr = y = 0; y < 192; y++) {
    for(x = 0; x < 192; x++) {
      data.data[ptr++] = a[y][x][0];
      data.data[ptr++] = a[y][x][1];
      data.data[ptr++] = a[y][x][2];
      data.data[ptr++] = 255;
    }
  }
  ctx.putImageData(data, 0, 0);
};

document.getElementById('img').src = img.src = "data:image/png;base64,[encoded data, 17752 characters]";
```

```
<img id="img" />
<canvas id="c" width=192 height=192></canvas>
```

# Answer
> 3 votes
# Jelly, 27 bytes

```
<“⁷KṆ‘‘Ḅœ?Ɗo⁹’)×€"3⁼þ¤)ẎZ)Ẏ

```

A monadic Link accepting a list (picture) of lists (rows) of lists (pixels). Each pixel being three integers in \\$\[0,255\]\\$, `[r, g, b]`, which yields the result in the same format.

**Try it online!** This example is taking a two by two image where the top-left pixel is the first example pixel, the top-right pixel is the second example pixel, the bottom-left pixel is a black pixel and the bottom-right pixel is a white pixel.

### How?

```
<“⁷KṆ‘‘Ḅœ?Ɗo⁹’)×€"3⁼þ¤)ẎZ)Ẏ - Link: list of lists of lists of integers, I
                         )  - for each row, R, in I:
                      )     -   for each pixel, P, in R:
              )             -     for each integer, C, in P:
 “⁷KṆ‘                      -       list of code-page indices = [135,75,180]
<                           -       less than -> [C<135,C<75,C<180]
          Ɗ                 -       last three links as a monad:
      ‘                     -         increment -> [1+(C<135),1+(C<75),1+(C<180)]
       Ḅ                    -         from binary -> 4*(1+(C<135))+2*(1+(C<75))+1+(C<180)
        œ?                  -         permutation at that index of [C<135,C<75,C<180]
                            -         when all permutations sorted lexicographically
                            -       ... a no-op for all but [0,0,1]->[0,1,0]
            ⁹               -       256
           o                -       logical OR  e.g. [0,1,0]->[256,1,256]
             ’              -       decrement               ->[255,0,255]
                     ¤      -     nilad followed by link(s) as a nilad:
                  3         -       three
                    þ       -       table with: (i.e. [1,2,3] . [1,2,3])
                   ⁼        -         equal?    -> [[1,0,0],[0,1,0],[0,0,1]]
                 "          -     zip with:
                €           -       for each:
               ×            -         multiply
                       Ẏ    -   tighten (reduce with concatenation)
                        Z   -   transpose
                          Ẏ - tighten

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 186 bytes

Input and Output are lists of RGB values

```
(g=#;Flatten[(T=Transpose)@Flatten[T/@{{#,v={0,0,0},v},{v,#2,v},{v,v,#3}}&@@(If[(l=Max@#)<75,v,If[74<l<135,{0,l,0},If[134<l<179,{l,0,l},{l,l,l}]]]&/@#)&/@g[[#]],1]&/@Range[Length@g],1])&

```

Try it online!

# Wolfram Language (Mathematica), 243 bytes

this second code is a **function** that takes as input an **image** and outputs an **image**
(I don't know why people were confused in the comments)

So, if you feed this img

into this function

```
(i=#;Image[Flatten[(T=Transpose)@Flatten[T/@{{#,v={0,0,0},v},{v,#2,v},{v,v,#3}}&@@(If[(l=Max@#)<75,v,If[74<l<135,{0,l,0},If[134<l<179,{l,0,l},{l,l,l}]]]&/@#)&/@ImageData[i,"Byte"][[#]],1]&/@Range[Last@ImageDimensions@i],1],ColorSpace->"RGB"])&

```

you will get this output

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 157 bytes

```
n=>{int i=0,j=n[0].Length;for(;;Write(z(0)+",0,0|0,"+z(1)+",0|0,0,"+z(2)+"\n|"[++i%j&1]));int z(int k)=>(((511^i/j%3%2*4064)>>n[i/j/3][i%j][k]/15)&1^1)*255;}

```

Prints the RGB of the output. The output is newline separated and not aligned. Originally, I used a bit-mask with `1` being on and `0` being off, but then I saw Arnauld's answer, and I realized using `0` as on and `1` as off could save bytes in the number. The TIO link contains a 4 by 2 pixel sample "image".

Try it online!

# Answer
> 0 votes
# APL+WIN, 102 bytes

Prompts for a 2d matrix of pixels as 24 bit integers as they would appear in the image

```
((⍴a)⍴,3 3⍴255*⍳3)×a←(3 1×⍴m)⍴∊⍉((1↓⍴m)/⍳↑⍴m)⊂n←(-+⌿n)⊖n←1 0↓0 75 135 180∘.≤,m←(1 3×⍴m)⍴,⍉(3⍴256)⊤,m←⎕

```

Try it online! Courtesy of Dyalog Classic

Outputs a 2d matrix of 24 bit integers of the transformed image. Most of the code is handling the formatting of the input and output.

Example: Take a 2 x 2 image made up of the sample pixels

Input:

```
2654895 10547300
2654895 10547300

```

Output:.

```
0     0 16581375 255 65025        0
0 65025        0   0 65025 16581375
0     0 16581375 255 65025        0
0     0 16581375 255 65025        0
0 65025        0   0 65025 16581375
0     0 16581375 255 65025        0

```

# Answer
> 0 votes
# Rust - 281 bytes

```
fn z(p:Vec<u8>,wh:[usize;2])->Vec<u8>{let mut o=vec![0;wh[0]*wh[1]*27];for m in 0..wh[0]{for n in 0..wh[1]{for i in 1..=3{for j in 0..3{o[m*9+n*wh[0]*27+j*wh[0]*9+i*2]=match p[18+m*3+n*wh[0]*3+3-i]{75..=134=>[0,1,0],135..=179=>[1,0,1],180..=255=>[1,1,1],_=>[0,0,0],}[j]*255;}}}}o}

```

This line is a function that meets the challenge, however it's input is actually data in the TGA file format as described at paulbourke.net, along with pre-parsed width and height, in pixels, of the image. It returns pixel data for the output, as bytes, in a vector 9 times the size of the input pixel data.

```
use std::fs::File;use std::io::{Read,Write};fn main(){let mut p=vec![];let mut o=vec![0u8;18];File::open("i.tga").unwrap().read_to_end(&mut p).unwrap();let mut wh=[0;2];let h=|x|p[x] as usize;let g=|x|(3*x/256) as u8;for i in 0..2{wh[i]=h(12+i*2)+256*h(13+i*2);o[12+i*2]=g(wh[i]*256);o[13+i*2]=g(wh[i]);}let mut f=File::create("o.tga").unwrap();o[2]=2;o[16]=24;o.extend(z(p,wh));f.write(&o).unwrap();}

```

This second line is a main() function that can transform an input file named i.tga into an output file named o.tga, by calling the function z from the first line, without using any external libraries. It handles parsing of width/height, creating a header for the output file, and file reading + writing. It would add 402 bytes if the challenge required File I/O, for a total of 683. It is useful for testing.

---
Tags: code-golf, graphical-output
---


title: The Digit Triangles

text:
# Question
Title: The Digit Triangles
## Challenge:

**Input:** A positive integer \\$n\\$

**Output:**

Create a list in the range \\$\[1,n\]\\$, and join it together to a string (i.e. \\$n=13\\$ would be the string `12345678910111213`).

Now we output a triangle using the prefixes or suffixes of this string, in one of the following four orientations based on the input integer:

* If \\$n\equiv 0\pmod 4\\$, output it in the triangle shape ◣
* If \\$n\equiv 1\pmod 4\\$, output it in the triangle shape ◤
* If \\$n\equiv 2\pmod 4\\$, output it in the triangle shape ◥
* If \\$n\equiv 3\pmod 4\\$, output it in the triangle shape ◢

**Example:**

Input: \\$n=13\\$

Because \\$13\equiv 1\pmod 4\\$, the shape will be ◤. Here three possible valid outputs:

```
12345678910111213    11111111111111111    12345678910111213
1234567891011121     2222222222222222     2345678910111213
123456789101112      333333333333333      345678910111213
12345678910111       44444444444444       45678910111213
1234567891011        5555555555555        5678910111213
123456789101         666666666666         678910111213
12345678910          77777777777          78910111213
1234567891           8888888888           8910111213
123456789            999999999            910111213
12345678             11111111             10111213
1234567              0000000              0111213
123456               111111               111213
12345                11111                11213
1234                 1111                 1213
123                  222                  213
12                   11                   13
1                    3                    3

```

## Challenge rules:

* As you can see at the three valid outputs above, only the correct shape and using all the digits in the **correct order** is important. Apart from that you're free to use prefixes or suffixes; reverses/reflects; diagonal printing; etc. etc. Any of the six possible outputs for each shape is allowed (see the test case below to see *all* valid outputs based on the shape). This allows languages with rotation builtins to use it, but those without can also use an alternative approach of using the prefixes in the correct size from top-to-bottom, or using the prefixes for two of the shapes but suffixes for the other two shapes. Choosing the most appropriate output options for your language is part of the golfing process. :)
* Input is guaranteed to be a positive integer. For \\$n=1\\$ we simply output `1`.
* Any amount of leading/trailing newlines/spaces are allowed, as long as it prints the correct triangle (without vertical nor horizontal delimiters!) somewhere on the screen.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

Input: \\$n=5\\$
All possible valid outputs:

```
12345    54321    12345    54321    11111    55555
1234     5432     2345     4321     2222     4444
123      543      345      321      333      333
12       54       45       21       44       22
1        5        5        1        5        1

```

Input: \\$n=6\\$
All possible outputs:

```
123456    654321    123456    654321    111111    666666
 12345     65432     23456     54321     22222     55555
  1234      6543      3456      4321      3333      4444
   123       654       456       321       444       333
    12        65        56        21        55        22
     1         6         6         1         6         1

```

Input: \\$n=7\\$
All possible outputs:

```
      1          1          7          7          7          1
     12         21         67         76         66         22
    123        321        567        765        555        333
   1234       4321       4567       7654       4444       4444
  12345      54321      34567      76543      33333      55555
 123456     654321     234567     765432     222222     666666
1234567    7654321    1234567    7654321    1111111    7777777

```

Input: \\$n=8\\$
All possible outputs:

```
1           1           8           8           8           1
12          21          78          87          77          22
123         321         678         876         666         333
1234        4321        5678        8765        5555        4444
12345       54321       45678       87654       44444       55555
123456      654321      345678      876543      333333      666666
1234567     7654321     2345678     8765432     2222222     7777777
12345678    87654321    12345678    87654321    11111111    88888888

```

Input: \\$n=1\\$
Only possible output:

```
1

```

Input: \\$n=2\\$
All possible outputs:

```
12    21    12    21    11    22
 1     2     2     1     2     1

```

# Answer
> 9 votes
# JavaScript (ES6),  ~~93~~  89 bytes

Returns a matrix of characters.

```
n=>[...(g=n=>n?g(n-1)+n:'')(n)].map((d,y,a)=>a.map(_=>y-(n&2)*y--<0?' ':d)).sort(_=>-n%2)

```

Try it online!

Alternate pattern (same size):

```
n=>[...(g=n=>n?g(n-1)+n:'')(n)].map((_,y,a)=>a.map(d=>y-(n&2)*y--<0?' ':d)).sort(_=>-n%2)

```

Try it online!

### Commented

```
n =>                 // n = input
  [...               // split the result of ...
    ( g = n =>       //   ... a call to the recursive function g, taking n
      n ?            //     if n is not equal to 0:
        g(n - 1)     //       append the result of a recursive call with n - 1
        + n          //       append n
      :              //     else:
        ''           //       stop recursion and return an empty string
    )(n)             //   initial call to g
  ].map((d, y, a) => // for each digit d at position y in this array a[]:
    a.map(_ =>       //   for each character in a[]:
      y -            //     we test either y < 0 if (n AND 2) is not set
      (n & 2)        //     or -y < 0 (i.e. y > 0) if (n AND 2) is set
      * y-- < 0      //     and we decrement y afterwards
      ?              //     if the above condition is met:
        ' '          //       append a space
      :              //     else:
        d            //       append d
    )                //   end of inner map()
  )                  // end of outer map()
  .sort(_ => -n % 2) // reverse the rows if n is odd

```

### Shape summary

Below is a summary of the base shape (generated by the nested `map` loops) and the final shape (after the `sort`) for each \\$n\bmod 4\\$:

```
 n mod 4  | 0     | 1     | 2     | 3
----------+-------+-------+-------+-------
 n & 2    | 0     | 0     | 2     | 2
----------+-------+-------+-------+-------
 test     | y < 0 | y < 0 | y > 0 | y > 0
----------+-------+-------+-------+-------
 base     | #.... | #.... | ##### | #####
 shape    | ##... | ##... | .#### | .####
          | ###.. | ###.. | ..### | ..###
          | ####. | ####. | ...## | ...##
          | ##### | ##### | ....# | ....#
----------+-------+-------+-------+-------
 n % 2    | 0     | 1     | 0     | 1
----------+-------+-------+-------+-------
 reverse? | no    | yes   | no    | yes
----------+-------+-------+-------+-------
 final    | #.... | ##### | ##### | ....#
 shape    | ##... | ####. | .#### | ...##
          | ###.. | ###.. | ..### | ..###
          | ####. | ##... | ...## | .####
          | ##### | #.... | ....# | #####

```

# Answer
> 9 votes
# Python 2, 94 bytes

```
n=0;s=''
exec"n+=1;s+=`n`;"*input()
K=k=len(s)
while k:k-=1;print s[k^n/-2%-2:].rjust(n%4/2*K)

```

Try it online!

# Answer
> 7 votes
# Japt, 8 bytes

Returns an array of lines.

```
õ ¬å+ zU

```

Try it

Saved 2 bytes thanks to Kevin.

```
õ ¬å+ zU     :Implicit input of integer U
õ            :Range [1,U]
  ¬          :Join to a string
   å+        :Cumulatively reduce by concatenation
      zU     :Rotate clockwise by 90 degrees U times

```

# Answer
> 4 votes
# Canvas, 8 bytes

```
ŗ］∑［］⁸［↷

```

Try it here!

# Answer
> 4 votes
# Perl 6, 94 bytes

```
{[o](|(&reverse xx$_/2+.5),|(*>>.flip xx$_/2+1))([\~](my@a=[~](1..$_).comb)>>.fmt("%{+@a}s"))}

```

Try it online!

Anonymous code block that takes a number and returns a list of lines.

# Answer
> 3 votes
# Charcoal, 17 bytes

```
Ｎθ≔⭆θ⊕ιηＧLＬηη⟲⊗θ‖

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input `n`.

```
≔⭆θ⊕ιη

```

Create a string by concatenating the numbers `1` to `n`.

```
ＧLＬηη

```

Fill a triangle of that length with the string.

```
⟲⊗θ

```

Rotate the triangle anticlockwise by `n*90` degrees.

Reflect everything, thus ending up with a triangle that is rotated clockwise by `n*90` degrees.

# Answer
> 3 votes
# Ruby, ~~95~~ ~~82~~ 79 bytes

```
->n{r=(0...z=/$/=~s=[*1..n]*'').map{|i|" "*n[1]*i+s[0,z-i]};-n&2>0?r:r.reverse}

```

Try it online!

3 bytes saved by G B.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 128 bytes

```
n=>{var s="";int i=0,j,p;for(;i<n;s+=++i);for(p=j=s.Length;;)Write("{0,"+(n%4>1?p:0)+"}\n",new string(s[--j],-~n%4>1?j+1:p-j));}

```

Try it online!

# Answer
> 3 votes
# , ~~152~~ ~~139~~ ~~137~~ 134 bytes

```
function(n,N=nchar(s<-Reduce(paste0,1:n,'')),A=!n%%4%%3)for(i in 1:N)cat(rep('',(M=c(N-i+1,i))[1+!A]*(n%%4>1)),substr(s,1,M[1+A]),'
')

```

Unrolled code :

```
function(n){
  s = Reduce(paste0,1:n,'')      # concat the digits from 1 to n into a string s

  N = nchar(s)                   # store the length of s

  A = !n%%4%%3                   # A = TRUE if n MOD 4 == 1 or 2

  for(i in 1:N){                 # for 1 to N (length of s)

    M = c(N-i+1,i)               # store N-i+1 and i into a vector

    nSpaces = M[1+!A]*(n%%4>1)   # if n MOD 4 == 1 or 2 then nSpaces = i else nSpaces = N-i+1,
                                 # but if n MOD 4 == 0 or 1, then force nSpaces = 0

    nDigits = M[1+A]             # if n MOD 4 == 1 or 2 then nDigits = N-i+1 else nDigits = i

    prfx = rep('',)              # create a character vector repeating '' nSpaces times

    sufx = substr(s,1,M[1+A])    # substring s by taking the first nDigits characters

    cat(pr,su,'\n')              # print prfx and sufx using space as separator for the values
                                 # contatenation (cat function default) and append a newline
  }

```

Try it online!

# Answer
> 2 votes
# APL+WIN, 45 bytes

Prompts for integer

```
m←⊃(⍳⍴s)↑¨⊂s←(⍕⍳n←⎕)~' '⋄⍎(' ⊖⍉⌽'[1+4|n]),'m'

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# 05AB1E (legacy), ~~14~~ ~~12~~ 10 bytes

Using the legacy verion as the rewrite is extremely slow on this for some reason.

Saved 2 bytes thanks to *Kevin Cruijssen*

```
LSηsFRζ}J»

```

Try it online!

**Explanation**

```
L           # push range [1 ... input]
 S          # split to list of individual digits
  η         # calculate prefixes
   sF  }    # input times do:
     R      # reverse list
      ζ     # and transpose it
        J   # join to list of strings
         »  # and join on newlines

```

# Answer
> 2 votes
# PowerShell, 108 bytes

```
param($n)0..($y=($x=-join(1..$n)).length-1)|%{' '*(0,0,$_,($z=$y-$_))[$n%4]+-join$x[0..($_,$z,$z,$_)[$n%4]]}

```

Try it online!

A bit rough around the edges but works. Joins the digits 1 to `n` into a string then iterates from 0 to the length of that string-1. Each time, it uses list indexing to swap to the correct spacing method and number range used to slice our new string.

# Answer
> 2 votes
# Jelly, 12 bytes

```
D€Ẏ;\z⁶U$⁸¡Y

```

Try it online!

# Answer
> 2 votes
# Stax, 10 bytes

```
Ç√çZ╟84Γó║

```

Run and debug it

# Answer
> 2 votes
# PowerShell, ~~105~~ ~~101~~ 95 bytes

*-4 bytes thanks Arnauld for the trick with Sort.*

```
param($n)($x=1..$n-join'')|% t*y|%{($s+="$_")}|sort -d:($n%4-in1,2)|% *ft($x.Length*($n%4-ge2))

```

Try it online!

Less golfed:

```
param($n)
$x=1..$n-join''
$x|% toCharArray |% {
    ($s+="$_")
} | sort -Descending:($n%4-in1,2) |% PadLeft ($x.Length*($n%4-ge2))

```

# Answer
> 2 votes
# , ~~175~~ ~~172~~ 154 bytes

```
function(n)write(c(" ",0:9)[1+(x=utf8ToInt(Reduce(paste0,1:n,""))-47)*!upper.tri(diag(y<-sum(x|1)))["if"(n%%4>1,1:y,y:1),"if"(!n%%4%%3,y:1,1:y)]],1,y,,"")

```

Try it online!

A horrible in-line mess!

*-3 bytes by changing the rotation condition*

*-17 bytes thanks to digEmAll's suggestion, and another byte after golfing that further*

# Answer
> 1 votes
# Wolfram Language (Mathematica), 137 bytes

```
(t=Table[Table[" ",If[(m=#~Mod~4)>1,Tr[1^s]-k,0]]<>ToString/@s[[;;k]],{k,Length[s=Join@@IntegerDigits/@Range@#]}];If[0<m<3,Reverse@t,t])&

```

Try it online!

# Answer
> 1 votes
# Python 2, 116 bytes

```
n=input()
s=''.join(map(str,range(1,n+1)));L=len(s)
p=-~n/2%2;i=~-L*p+1
exec'print s[:i].rjust(n/2%2*L);i+=1-2*p;'*L

```

Try it online!

# Answer
> 1 votes
# Red, 155 bytes

```
func[n][b: copy""repeat i n[append b i]repeat i l:
length? b[t:[l - i + 1]set[k m]pick[i t[l t][l i]]n % 4 + 1
print pad/left copy/part b do do m do do k]]

```

Try it online!

# Answer
> 1 votes
# perl 5, 117 bytes

```
$p=$_++&2?'/ ':'$/';$s='(.*\d.\n)';$r=$_--&2?$s.'\K$':"^(?=$s)";$_=(join"",1..$_).$/;1while s,$r,'$1=~s/\d'."$p/r",ee

```

TIO

# Answer
> 1 votes
# PHP, ~~116~~ ~~111~~ 109 bytes

```
for($m=$l=strlen($s=join(range(1,$n=$argn)));$l--;)printf('%'.($n&2?$m:-$l).'.'.($n-1&2?$m-$l:$l+1)."s
",$s);

```

Try it online!

Run with `php -nF` input from `STDIN`.

`$ echo 6|php -nF t.php`

```
123456
 12345
  1234
   123
    12
     1

```

# Answer
> 1 votes
# Java (JDK), ~~247~~ ~~209~~ ~~188~~ ~~186~~ ~~160~~ 148 bytes

```
i->{String s="";int l=0,w;for(;l<i;s+=++l);for(w=s.length(),l=0;l<w;)System.out.printf("%"+(1>i%4/2?1:w)+"s\n",s.substring(0,1>~-i%4/2?w-l++:++l));}

```

Try it online!

`-38 bytes` thanks to @KevinCruijssen
`-21 bytes` by letting `printf` handle the padding.
`-2 bytes` by doing substring before replace, allowing us to increment `l` in one location rather than two.
`-26 bytes` \- with `printf` doing the padding, the string full of spaces was no longer necessary, and the digit strings could be generated in a shorter way apparently.
`-12 bytes` by not messing about with single digits instead of printing substrings of the perfectly servicable digit string we already have.

# Ungolfed

```
input->{
    // Lambda expression with target type of IntConsumer
    String allDigits = "";
    int lineLength, line = 0;

    // Collect a list of all digits in order.
    for (;line < input; allDigits += ++line) {}

    // Save the max length of a line, and create a string of that many spaces.
    for (lineLength=allDigits.length(), line=0; line < lineLength;) {
        System.out.printf(   "%" // construct a format string to handle the padding
                           + (   1 > input%4/2
                               ? 1 // No padding
                               : w // Yes padding
                             )
                           + "s\n"
                         , allDigits.substring( 0
                                              ,   1 > (i-1)%4/2
                                                ? w - l++
                                                : ++l
                                              ) // A string containing only the digit we want.
                         );
    }
}

```

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


title: Walkers Join! - Alan Walker's logo

text:
# Question
Title: Walkers Join! - Alan Walker's logo
You might know Alan Walker from his ever popular song Faded. Now his "followers" are called Walkers and they have a logo, here is a simplified version:

```
\\
 \\              //\\
  \\            //  \\            //
   \\          //    \\          //
    \\        //      \\        //
     \\      //        \\      //
      \\    //          \\    //
       \\  //    //\\    \\  //
        \\//    //  \\    \\//
         //    //    \\    \\
        //\\  //      \\  //\\
           \\//        \\//  \\
                              \\

```

The goal of this challenge is to print this logo.

**RULES:**

1. If you return a list of strings from a function as per meta standards, please provide a footer that prints it to the screen.
2. All characters of the above logo have to be there. No shortcuts!
3. Shortest number of bytes wins!

# Answer
> 14 votes
# Charcoal, ~~31~~ ~~30~~ ~~29~~ 27 bytes

```
Ｆ²«Ｊι⁰↙χ↖↖⁵↙↙⁵↖↖²Ｐ↖χ↙↗χ↘↘¹²

```

Try it online! Link is to verbose version of code. Sadly `Copy` doesn't do what I want in this case, so I have to loop instead. Explanation:

```
Ｆ²«Ｊι⁰

```

Draw everything twice, but with the cursor starting one character to the right the second time.

```
   ↙χ↖↖⁵↙↙⁵↖↖²Ｐ↖χ

```

Draw the main W from right to left, but leave the cursor near the inverted V.

```
   ↙↗χ↘↘¹²

```

Draw the inverted V.

# Answer
> 13 votes
# JavaScript (ES6), ~~172~~ 139 bytes

```
let f =

_=>`1
3s1
5o5o
7k9k
9gdg
bchc
d8l8
f48194
h08590
i899
g14d41
n0h05
1p`.replace(/.p?/g,n=>' '.repeat((n=parseInt(n,36))/2)+(c='/\\'[n&1])+c)

O.innerText = f()
```

```
<pre id=O>
```

### How?

The logo basically consists of groups of spaces followed by either `//` or `\\` and line feeds.

Spaces and ending patterns are encoded using base-36 values:

* The least significant bit gives the ending pattern: `0` for `//`, `1` for `\\`.
* All other bits give the number of spaces before the ending pattern.

Everything can be encoded this way with a single base-36 digit except the last line which consists of 30 spaces followed by `\\`, leading to 30\*2+1 = 61 = `1p` in base-36. This `p` should be interpreted as 12 spaces followed by `\\` but this pattern doesn't appear anywhere. So, we can simply handle this special case at the cost of 2 extra bytes in the regular expression: `/.p?/`.

---

# First version, 186 bytes

*NB: This one was submitted prior to the logo update.*

```
let f =

_=>[...`WALKER'S`].reduce((s,c)=>(x=s.split(c)).join(x.pop()),`E
 ELSRE
'LK'
 'LRWLR
WSKS'SK
S ESRLESR
S'KL'K
S 'RKEWR
LEAK'WA
L AKWW
SKERS'RE
L 'ALEA'
LLLS'S    '  ER  AE\\\\KSALSSA//WSE`)

O.innerText = f()
```

```
<pre id=O>
```

# Answer
> 7 votes
# brainfuck, 579 bytes

```
+++++++++[>+>+++++>+++>++++++++++<<<<-]>+>++>+++++>++..<<<.>>.>..<..............<..>>..<..<<.>>..>..<............<..>..>..<............<..<.>>...>..<..........<..>....>..<..........<..<.>>....>..<........<..>......>..<........<..<.>>.....>..<......<..>........>..<......<..<.>>......>..<....<..>..........>..<....<..<.>>.......>..<..<..>....<..>>..<....>..<..<..<.>>........>..<<..>....<..>..>..<....>..<<..<.>>.........<..>....<..>....>..<....>..<<<.>>........<..>>..<..<..>......>..<..<..>>..<<<.>>...........>..<<..>........>..<<..>..>..<<<.>>..............................>..

```

Try it online!

Generates the constants `47 92 32 10` in memory, then selects and outputs them as appropriate.

# Answer
> 6 votes
# SOGL V0.12, 38 bytes

```
6«╝5╚@┼╬⁷7«8ž'⁸3L╚ž92L╚╬5L«26«╝╬5:21╬5

```

Try it Here!

# Answer
> 4 votes
# Bubblegum, ~~77~~ 76 bytes

Hexdump:

```
0000000: 75cf c109 8000 0c43 d17b a6c8 0659 28fb  u......C.{...Y(.
0000010: cf21 05cb a782 3de9 4b5a b495 5b9f 4946  .!....=.KZ..[.IF
0000020: 870f dac3 f8ea 5704 51b9 2284 c611 0114  ......W.Q.".....
0000030: 9029 f09e ec67 2362 21e1 075e 2136 29b9  .)...g#b!..^!6).
0000040: 08b9 bf97 8939 cf33 ebbf d33e            .....9.3...>

```

Try it online!

Bubblegum threshold. :P

# Answer
> 3 votes
# ///, 166 bytes

```
/-/!#//,/%"//'/%#//&/!!//%/  //#/\\\/\\\///"/\\\\\\\\//!/%%/"
 "&!'"%
,&-,&-
% "&'!"&'
!"&#!,&#
! "!'&"!'
!,-&,-
!% "'-"!"'
&"#-,!"#
& #-!"!"
&#"'!,'"
&% "#&"#,
&&&!,

```

Try it online!

# Answer
> 3 votes
# C (gcc), 377 bytes

```
char*r="2\\01 2\\14 2/2\\02 2\\12 2/2 2\\12 2/03 2\\10 2/4 2\\10 2/04 2\\8 2/6 2\\8 2/05 2\\6 2/8 2\\6 2/06 2\\4 2/10 2\\4 2/07 2\\2 2/4 2/2\\4 2\\2 2/08 2\\2/4 2/2 2\\4 2\\2/09 2/4 2/4 2\\4 2\\08 2/2\\2 2/6 2\\2 2/2\\011 2\\2/8 2\\2/2 2\\030 2\\";char d[9];main(i){do{if(*r==48)puts(""),r++;for(i=0;isdigit(*r);d[i++]=*r++);for(d[i]=0,i=atoi(d);i--;putchar(*r));}while(*r++);}

```

Try it online!

# Answer
> 3 votes
# Python 2, 197 bytes

```
print''.join(i>'/'and(i<'2'and['/','\\'][int(i)]*2or' '*int(i))or i for i in"""1
 19501
2193021
319 0419 0
41806180
51608160
61409 140
71204014120
8104021410
90404141
8012061201
921081021
99931""")

```

Try it online!

Uses the logic from the JS answer.

# Answer
> 3 votes
## Haskell, ~~161~~ 160 bytes

```
foldr(\a->(++(' '<$[1..fromEnum a-last(96:[64|a<'`'])])++last("\\\\":["//"|a<'`'])))""<$>words"` `Na LbLb JdJc HfHd FhFe DjDf Bd`DBg @dbD@h ddDI `BfB`H b@h@k ~"

```

Try it online!

Spaces before `\\` are encoded as lowercase letters and before `//` as uppercase letters where the number of spaces is the ASCII value minus 96 (or 64). Zero spaces is ``` / `@`. The Spaces of each line are stored in reverse order, because the are consumes by a right-fold.

# Answer
> 2 votes
# Charcoal, 51 bytes

```
Ｐ↘¹²→↘¹²↑Ｐ↗⁵→↗⁵↓Ｐ↘⁵→↘⁵↑Ｐ↗χ→↗χＭ¹¹↓Ｍ⁵←Ｐ↖¹²←↖¹²↓Ｐ↙χ←↙χ

```

Try it online!

# Charcoal, 50 bytes

```
Ｐ↘χ→↘χ↑Ｐ↗⁵→↗⁵Ｍ⁵↑←Ｐ↙χ←↙χＭχ↗‖ＭＭ¹⁸←Ｐ↖²←↖²Ｊ²⁷¦⁹Ｐ↘²→↘²¦

```

Try it online!

# Answer
> 2 votes
# Charcoal, ~~50~~ 31 bytes

```
Ｆ²«↘¹²↗↗⁵↘↘⁵↗↗⁹Ｍχ↓Ｍ⁴←↖¹²↙↙χＪ¹¦⁰

```

Try it online! Link is to verbose version.

I tried. (Also, I will point out that I did this completely on my own, even if it looks somewhat similar to the other one. \[Shiz, I did it again. This is still different, by the way. :P\])

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 122 bytes (121 chars)

```
_=>@"
A
9;13) +!(# 0$(	-)
4	(	€".SelectMany(j=>(j%2>0?"//":@"\\").PadLeft(j/4)+(j%4>1?"\n":""))

```

Try it online!

# Explanation

Each part of the logo is just 0+ spaces with either a `\\` or a `//` at the end, plus maybe a newline. There are 52 of these. We then encode each segment into a character:

* Take the number of spaces in each segment, then add 2 to that number.
* Bit shift the number to the left 2 times.
* If the segment ends with `//`, bit-wise OR the number by one.
* If the segment ends with a newline, bit-wise OR the number by two.
* Take the number, and cast it into a char.
* Repeat for each segment.

Here are all of the 52 segments and the numeric value they encode into:

```
10,12,65,10,16,57,16,59,20,49,24,51,24,41,32,43,28,33,40,35,32,25,48,27,36,17,25,8,24,19,40,9,25,16,24,11,45,25,24,26,41,8,17,32,17,10,52,9,40,9,18,128
```

# Answer
> 1 votes
# PowerShell, ~~221~~ 220 bytes

```
$ofs=''
"b
 b$(' '*14)/b
$((2..6|%{' '*$_+"b$(($a=' '*(14-++$i*2)))/$(' '*$i*2)b$a/`n"}))   4b  /4/b4b  /
44b/4/  b4b/
44 /4/4b4b
44/b  /4  b  /b
44   b/44b/  b
$(' '*30)b"-replace4,'    '-replace'/','//'-replace'b','\\'

```

Try it online!

Fairly naïve approach (*and 50 bytes worse than the JS answer, cringe*). Anyone know of a way to do multiple `-replace`s in PowerShell?

*-1 byte thanks to Veskah.*

# Answer
> 1 votes
# Jelly, 65 bytes

```
“<fṭY2Ẹ<ƭẹ£ʋ¥¹)Œ<Ẓ⁹ḣ⁶ıĠ\ṃṛ?04|ẏḌẉƙ+’b36⁶ẋ“ÇỴ$ñ⁵FḄ’Bị⁾\/¤ẋ€2¤żFs36

```

Try it online!

Returns a list of characters. TIO link has a footer to print on separate lines.

# Answer
> 1 votes
# PHP, 186 bytes:

Both versions require PHP 5.5 or later.

Run with `-nr` or try them online

---

space compression gives the shortest alternative:

(double backslash mapped to `0`, double slash to `f`, sapces compressed to digits)

```
while(~$c="0
1077f0
2066f2066f
3055f4055f
408f608f
506f806f
604f5504f
702f4f0402f
80f4f2040f
9f4f4040
8f02f602f0
560f80f20
87870"[$i++])echo+$c?str_pad("",$c):strtr($c,["\\\\",f=>"//"]);

```

PHP 7.1 yields warnings; replace `+$c` with `$c>0` to fix.

---

base 64 encoded bitmap (**187 bytes**):

(mapped space to `00`, newline to `01`, double backslash to `10` and double slash to `11`, then concatenated 3 "pixels" each to one character, prepended `1` and converted from binary to ASCII)

```
for(;$c=ord("d`@@@@yB@@@@p`@@@M@`@@C@H@@@t@`@@p@H@@M@B@@p@@`@M@@`C@@@H@t@@`pC`BCP@@l@p`Bt@@C@L@`BP@@xL@BCd@@@K@@Bpd@@@@@@@@@B"
[$i++]);)for($b=6;$b;)echo[" ","
","\\\\","//"][3&$c>>$b-=2];

```

(first linebreak for reading convenience; the other one is essential)

# Answer
> 1 votes
# Bubblegum, 74 bytes

```
00000000: 758c 4b11 0400 0885 eea6 a081 85e8 9f63  u.K............c
00000010: 4fb2 7f4f 0e30 4f07 e5ed 7615 8613 e16f  O..O.0O...v....o
00000020: 321c ab89 d484 4a22 2591 8a48 45a0 2052  2.....J"%..HE. R
00000030: 809e dfd5 481e 3d0d 7a24 4d96 bc43 b2fd  ....H.=.z$M..C..
00000040: 96d3 cdbf fff9 7fa7 f300                 ..........

```

Try it online!

# Answer
> 1 votes
# Python 2, 180 bytes

```
print''.join(c<'3'and'\\/\n\\/'[int(c)::3]or' '*(int(c,36)-2)for c in'0230g104240e140e1250c160c1260a180a127081a08128061c0612904161060412a0161406012b16160602a1041804102d01a01402w0')

```

Try it online!

The encoding is base 36:

```
0 => \\
1 => //
2 => \n

```

and otherwise,

```
n => (n-2) spaces

```

# Answer
> 0 votes
# C (gcc), ~~144~~ ~~140~~ 139 bytes

-4 bytes thanks to ceilingcat.

Each character in the string encodes a number of spaces to use before a certain string. If it's a lower-case letter (or a backtick), then the string is "\\", and if upper-case or @, it's "//". A space signifies a newline.

```
f(c,i){for(i=0;c="` aN` bLbL cJdJ dHfH eFhF fDjD gBD`dB h@Dbd@ IDdd H`BfB` k@h@b ~"[i++];)printf("%*s",c%32+2,c<33?"\n":c<96?"//":"\\\\");}

```

Try it online!

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


title: Nearest hamming cycle period in MD5

text:
# Question
Title: Nearest hamming cycle period in MD5
This riddle was inspired by that thread. Consider that you are super-hacker and try to break MD5 hashing algorithm by looking for a hash collisions for a given hash string which your friend gave to you. But this is a non-trivial task and you have a migraine disorder so you try to break the problem into smaller parts. First thing which you try is to look for a hamming distance patterns in a repeated execution of MD5() feeding it's last output to an input. For example, if your friend gave to you a hash bb2afeb932cc5aafff4a3e7e31d6d3fb, then you will notice a such pattern :

```
e3b86f8d25e5a71a88eabef0d7ed9840=md5(bb2afeb932cc5aafff4a3e7e31d6d3fb), hamming 95
45fcdb59517b39f18d1622a84be0a301=md5(e3b86f8d25e5a71a88eabef0d7ed9840), hamming 91
0b3f2eac737b916f3b78f240e7fc97ec=md5(45fcdb59517b39f18d1622a84be0a301), hamming 77
fe56b1802722cc30b936186aacce1e01=md5(0b3f2eac737b916f3b78f240e7fc97ec), hamming 95

```

So after 4 iterations you arrived at hamming distance 95 between an output and a first input, which is the same 95 number which you have started from. So nearest hamming cycle period of MD5(bb2afeb932cc5aafff4a3e7e31d6d3fb) is **4**. You have found *a hamming collision* !

Your task is to write a program which takes an arbitrary MD5 hash from the standard input, and outputs it's nearest hamming cycle period on standard output. For example:

```
Input:  45fcdb59517b39f18d1622a84be0a301, Output: 3
Input:  1017efa1722ba21873d79c3a215da44a, Output: 7
Input:  edc990163ff765287a4dd93ee48a1107, Output: 90
Input:  c2ca818722219e3cc5ec6197ef967f5d, Output: 293

```

Shortest code wins.

Notes:

1. If your language doesn't have an `md5()` built-in, feel free to implement that yourself and then write in the solution *total* byte count and byte count *without* md5() sub-program implementation, the later will be considered as an answer.
2. Hamming distance is defined as number of differing bits between two strings. If strings converted to binary (by character ASCII code) has different lengths - smaller one is padded from the left with 0. Example:

```
Word1: nice Binary1: 01101110011010010110001101100101
Word2: car  Binary2: 00000000011000110110000101110010
Hamming distance (differing bits): 12

```
3. In this task you should calculate hamming distance between a **FIRST** input in a cycle and current output. So according to a given hamming cycle example above you should calculate

```
hamming(bb2afeb932cc5aafff4a3e7e31d6d3fb,e3b86f8d25e5a71a88eabef0d7ed9840)
hamming(bb2afeb932cc5aafff4a3e7e31d6d3fb,45fcdb59517b39f18d1622a84be0a301)
hamming(bb2afeb932cc5aafff4a3e7e31d6d3fb,0b3f2eac737b916f3b78f240e7fc97ec)
hamming(bb2afeb932cc5aafff4a3e7e31d6d3fb,fe56b1802722cc30b936186aacce1e01)

```

# Answer
> 3 votes
# Jelly, 37 bytes

```
Ç,³OBU+0x8¤_/FAS,Ç
Ç;0ịÇƊ$⁺-ịn1ị$Ʋ¿LH

```

Try it online!

Try it online! - using full implementation of MD5

I'll comment it when I have time. Jelly doesn't have an MD5 built-in, so the header for the first TIO implements MD5 for a fixed length (32 bytes) input. I've also now extended this to a general purpose MD5 routine (second TIO link). For the purposes of the challenge, there is a monadic link just above the challenge code that takes a 32 character string and returns the MD5 hash. The remaining code (as displayed above here) calculates the hamming distance between the original input and sequential hashes until it matches the first one.

# Answer
> 2 votes
# Python 2, ~~199~~ 196 bytes

*-3 bytes thanks to Kevin Cruijssen*

```
from md5 import*
B=bytearray
h=lambda a,b:sum(bin(i^j).count('1')for i,j in zip(B(a),B(b)))
m=lambda a:new(a).hexdigest()
def f(x):
 a=b=m(x);i=1
 while 1:
    b=m(b);i+=1
    if h(x,a)==h(x,b):return i

```

Try it online!

# Answer
> 1 votes
# perl 5 (`-MDigest::MD5=md5_hex` `-M5.01` `-pl`), 83 bytes

may be golfed

```
$x=$_;$h=(unpack'B*',($x=md5_hex($x))^$_)=~y/1//,$i||=$h while$c++<2|$i!=$h;$_=$c-1

```

TIO

# Answer
> 1 votes
# JavaScript (Node.js), 157 bytes

```
f=(s,n,a=(B=Buffer)(s))=>a.map((x,i)=>r+=(g=x=>x&&x%2+g(x/2))(x^B(s)[i]),s=require('crypto').createHash('md5').update(s).digest`hex`,r=0)|r==n||1+f(s,n||r,a)

```

Try it online!

---
Tags: code-golf, math, hashing
---


title: Write a Quine Suite

text:
# Question
Title: Write a Quine Suite
We've had a lot of challenges, but a lot of the quine formats are similar, lets create some variance in our quines.

Your task is to create a selection of programs in the same language (at least 2), all of which output their own source code, however, none of these programs can share any characters.

For example, if you create a program using:

```
printf+qw(printf+qw(%s)x2)x2

```

Your next program cannot include any of:

```
%()+2finpqrstwx

```

and so on.

## Rules

* You may use unicode characters, but you must still score in bytes.
* All programs must meet the community definition of a proper quine. This means that the empty string does not count as a valid quine, among other things.
* Standard loopholes are forbidden.
* Functions or full programs are allowed as long as they meet the above definition.
* Symbol independent languages (including Lenguage and Headsecks) are disallowed.
* Most programs wins, with shortest total code as a tie breaker.

# Answer
> 27 votes
# , ~~3~~, 5 quines, 46 bytes

```
2A2A

```

Try it online!

Hexdump:

```
00000000: 3241 3241                                2A2A

```

Explanation:

```
2     " 2 times...
 A    " (A)ppend the following text...
  2A  "   '2A'

```

---

```
5a5a

```

Try it online!

Hexdump:

```
00000000: 35ad adad 6135 adad ad61                 5...a5...a

```

Explanation:

```
5---        " 5 - 3 times...
    a       " (a)ppend the following text...
     5---a  "   '5---a'

```

---

```
1«I1«I

```

Try it online!

Hexdump:

```
00000000: 31ab 4931 ab49                           1.I1.I

```

Explanation:

```
1«      " 1 + 1 times...
  I     " (I)nsert the following text...
   1«I  "   '1«I'

```

---

Here's where they start to get funky...

```
ñi34x@-qPÉÑ~ÿ

```

Try it online!

Hexdump:

```
00000000: f169 1633 341b 7840 2d71 50c9 d17e ff    .i.34.x@-qP..~.

```

Explanation:

```
ñ                       " Wrap all the following in macro '"q':
 i<C-v>34               "   Insert character code 34 `"`
         <esc>          "   Return to normal mode
              x         "   Delete the character we just inserted. Now, running `@-` will be equal to running `"`
                  P     "   Paste...
               @-       "   From Register...
                 q      "   "q
                   ÉÑ   "   Insert 'Ñ' at the beginning of this line
                     ~  "   Toggle the case of the character we just inserted
                      ÿ "   Black magic

```

---

```
:norm é:":p

```

Try it online!

Hexdump:

```
00000000: 3a6e 6f72 6d20 e93a 223a 70              :norm .:":p

```

Explanation:

```
:norm       " Run the following commands as if typed:
      é:    "   insert ':'. Somehow also does black magic and resets the value of '":`
        ":p "   Paste the last ex command to be run ('norm é:":p')

```

This answer is filled with black magic. Quines 1 and 4 are not new, but the other 3 all have never been found before, so more than half of these quines were just discovered today.

# Answer
> 18 votes
# Jelly, ~~2 3 4~~ 5 quines, ~~14 18 81 65 59 56 326 265 247 229~~ 216 bytes

### 3 bytes

```
”ṘṘ

```

Try it online!

Standard quine. `”Ṙ` is the one character literal for .  prints the string representation of this then the string  implicitly gets printed.

### 4 bytes

```
⁾⁾ḤḤ

```

Try it online!

begins a two character string literal and  doubles it's argument. With a string input,  gets mapped onto each character. Thus  acting on the string `⁾Ḥ` yields `⁾⁾ḤḤ`, the source code.

### 11 bytes

```
ȮṾṖƊ}“ȮṾṖƊ}

```

Try it online!

On the right hand side, `“ȮṾṖƊ}` is the string literal for `ȮṾṖƊ}`. The string closing character is tacitly added at EOF.

To the left of the string literal, `Ɗ` wraps `ȮṾṖ` into a single monad and `}` turns it into a dyad which uses it's right argument, the string literal. `Ȯ` prints the string (`ȮṾṖƊ}`),  creates a string representation of the string (`“ȮṾṖƊ}”`) and  removes the  character. The string `“ȮṾṖƊ}` is left after the monad and is implicitly printed.

### ~~38 49~~ 36 bytes

```
32,52,52,7884,106,64,44,7884 44Ọj@,Ọ

```

Try it online!

First time I've ever used a space in Jelly golfing.

The list of numbers at the beginning holds the `ord` of the rest of the characters in code. After that:

```
jṛ44Ọ$,Ọ
j           Join this list with...
 ṛ          right argument. Avoiding using ¤ so I can use it in the next program.
  44Ọ       chr(44)==',': [106, ',', ...]
     $      Causes Ọ to act on 44 before j acts on it.
      ,     Pair this list with...
       Ọ    chr of each number in the list. Yields jṛ44Ọ$,Ọ

```

### ~~270 198 180~~ 162 bytes

```
⁽¢_;⁽⁽¤;⁽¡_;⁽⁽¡;⁽¡¤;⁽$+;⁽⁽y;⁽Ẹ$;⁽⁺$;⁽AƑ;⁽?€;⁽b⁽;⁽¢¡;⁽_⁽;⁽¡¡;⁽¤ị;⁽ØJ;⁽µṭ;⁽€⁽;⁽¡S;⁽;⁽;⁽¡ʠ;⁽¤ị;⁽ØJ;⁽¤F;⁽ḊṄ;⁽ȧF
¢_⁽¤¡_⁽¡¡¤$+⁽yẸ$⁺$AƑ?€b⁽¢¡_⁽¡¡¤ịØJµṭ€⁽¡S;⁽¡ʠ¤ịØJ¤FḊṄȧF

```

Try it online!

Uses base 250 numbers and indexes into Jelly code page. Saved 72 bytes by changing the algorithm. Was using each number to index in to Jelly's code page but am now converting the integer back to base 250 then indexing into Jelly's code page, basically halving the number of literals I need in the first line. This also reduces the number of unique characters needed, but I can't think of a way to make any more quines.

I've used up `⁾“”` which create string literals and  and `ØJ` which create strings from numbers. I can't think of any other ways of making strings. I still have the digit `9` and `‘’` available, so if there is a another way of making strings from numbers it may be possible to make another quine.

# Answer
> 13 votes
# Haskell, 3 quines, 1119 bytes

## Quine 1, 51 bytes

An anonymous `IO` action printing directly to stdout.

```
putStr`mappend`print`id`"putStr`mappend`print`id`"

```

Try it online!

## Quine 2, 265 bytes

The function `f` takes a dummy argument and returns a string.

```
f	c=[b=<<g]!!0++show	g;b	c=[[[show	9!!0,show	1!!0..]!!6..]!!c];g=[93,0,90,52,82,89,52,51,51,94,84,24,24,39,34,34,106,95,102,110,0,94,50,89,0,90,52,82,82,82,106,95,102,110,0,48,24,24,39,35,106,95,102,110,0,40,24,24,39,37,37,84,24,24,45,37,37,84,24,24,90,84,50,94,52]

```

Try it online!

## Quine 3, 803 bytes

Everything after the `LANGUAGE` pragma is an anymous function taking a dummy argument and returning a string.

```
{-#LANGUAGE CPP#-}(\q(_:_:_:_:_:_:_:_:z)y(#)_->(y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z)'\''__TIME__(\(?)v k x->v$k?x)$ \(&)(%)v->v&'{'&'-'&'#'&'L'&'A'&'N'&'G'&'U'&'A'&'G'&'E'&' '&'C'&'P'&'P'&'#'&'-'&'}'&'('%'\\'&'q'&'('&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'_'&':'&'z'&')'&'y'&'('&'#'&')'&'_'&'-'&'>'&'('&'y'&'('%'\\'&'k'&' '&'x'&'-'&'>'%'\''&'&'%'\''&':'&'q'&':'&'k'&':'&'q'&':'&'x'&')'&'#'&'y'&'('%'\\'&'k'&' '&'x'&'-'&'>'%'\''&'%'%'\''&':'&'q'&':'%'\''%'\\'%'\\'%'\''&':'&'k'&':'&'q'&':'&'x'&')'&'$'&'y'&'('&':'&')'&'#'&'y'&'('&':'&')'&'$'&' '%'\\'&'x'&'-'&'>'&'x'&')'&'z'&')'%'\''%'\\'%'\''%'\''&'_'&'_'&'T'&'I'&'M'&'E'&'_'&'_'&'('%'\\'&'('&'?'&')'&'v'&' '&'k'&' '&'x'&'-'&'>'&'v'&'$'&'k'&'?'&'x'&')'&'$'&' '%'\\'&'('&'&'&')'&'('&'%'&')'&'v'&'-'&'>'&'v'

```

Try it online!

## Characters

Quine 1:

```

"S`adeimnprtu

```

Quine 2:

```
	!+,.0123456789;<=[]bcfghosw

```

Quine 3:

```
 #$%&'()-:>?ACEGILMNPTU\_kqvxyz{}

```

## How it works

### Quine 1

```
putStr`mappend`print`id`"putStr`mappend`print`id`"

```

Quine 1 is a modified version of my recent Golf you a quine answer (with improvements by H.PWiz):

* Since full programs are not needed, `main=` has been removed.
* `<>` and `$` have been replaced by their near-synonyms `mappend` and `id`.

This frees up the vital characters `=<>` and the helpful operator `$` for the other quines.

### Quine 2

```
f	c=[b=<<g]!!0++show	g;b	c=[[[show	9!!0,show	1!!0..]!!6..]!!c];g=[93,0,......]

```

Quine 2 uses somewhat similar methods to program 2 of my recent Mutually Exclusive Quines answer, but adapted to quine itself directly and especially to avoid using character literals, which are needed for quine 3. Both of these are achieved with the help of the `show` function, which by sheer luck hasn't had any of its characters used yet.

This quine uses tabs instead of spaces, but I've used spaces below for readability.

* `g` is the quine data, as a list of integers at the end of the code. Each number represents a character from the rest of the code.
    + The numbers are shifted by `9`, so that tab is `0`. This makes the encoding a bit shorter by allowing the lowercase letters for the function and variable names to fit in 2 digits.
* `b c=[[[show 9!!0,show 1!!0..]!!6..]!!c]` is a function to convert a number to a character (actually a one-character string).
    + `[[show 9!!0,show 1!!0..]!!6..]` is a character range starting with a tab character, which is indexed into with `!!c`.
    + The tab character itself is produced by indexing into another range `[show 9!!0,show 1!!0..]`, starting with the digit characters `'9'` and `'1'` and jumping down in steps of 8.
    + The digit characters are produced by indexing into the `show` string of the corresponding digit.
* `f c=[b=<<g]!!0++show g` is the main function. `c` is a dummy argument.
    + `b=<<g` uses `=<<` to convert each number in `g` to its character. (The use of `=<<` rather than e.g. `map` is why `b` needs to wrap its returned character in a list.)
    + `show g` gives the string representation of `g`'s list, and `++` concatenates the strings.
    + Because `=<<` has lower precedence than `++`, some bracketing is needed. To avoid using `()` (reserved for quine 3), `[...]!!0` indexes into a list with one element.

### Quine 3

By design of the other quines, quine 3 still has access to parentheses, lambda expressions, character literals, and the string/list constructor `:`. This will be enough to construct a function that *prepends* the quine's code to a string.

Unfortunately, all lower case vowels (except sometimes `y`) have been used, leaving no useful alphanumeric builtin functions. Also `[]""` are gone. This leaves no normal way to construct an empty string to *start* pretending the code to.

However, nearly all uppercase letters are still available, so a `LANGUAGE` pragma to get a language extension is possible. Again by sheer luck, `CPP` (enable C preprocessor) is the only language extension named with only uppercase letters. And CPP macros often have uppercase names.

So to get the essential empty string, the quine enables `CPP`, uses the `__TIME__` macro to get a string constant of the form `"??:??:??"` (conveniently guaranteed to always have the same length), and pattern matches on it.

```
{-#LANGUAGE CPP#-}(\q(_:_:_:_:_:_:_:_:z)y(#)_->(y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z)'\''__TIME__(\(?)v k x->v$k?x)$ \(&)(%)v->v&'{'&'-'&......

```

After the language pragma, the quine consists of a lambda expression binding its parameters to these four arguments (leaving a final dummy parameter `_` to be applied later):

* `q` bound to `'\''`, giving a single quote character;
* `_:_:_:_:_:_:_:_:z` bound to `__TIME__`, aka a string like `"??:??:??"`, thus making `z` an empty string;
* `y` bound to `(\(?)v k x->v$k?x)`, a lambda combinator used to help convert the quine data from left associated ("foldl") to right associated ("foldr") form;
* The operator `(#)` bound to `\(&)(%)v->v&'{'&'-'&...`, the quine data itself.

The quine data is given in a form of Church encoding, a lambda expression with parameters `(&)(%)v`.

* By applying the expression to particular values to instantiate `(&)`, `(%)` and `v`, this encoding can be used either to build the core code of the quine or to rebuild the quine data representation itself.
* By Haskell's default fixity rule, `&` and `%` become left associative operators inside the lambda. Thus the character parameters become combined with the initial `v` starting from the left.
* For most characters `k`, there is a corresponding `&'k'`.
* When `k` is `'` or `\`, which need to be escaped inside character literals, the encoding is instead `%'\k'`.

Since the data encoding is left associative, but strings are built in a right associative manner, the combinator `y = (\(?)v k x->v$k?x)` is introduced to bridge the mismatch.

* `y(...)` is intended to build suitable functions for using as the quine data's `(&)` and `(%)` operators.
* `v` is a function from strings to strings (the quine data's intended `v`s being examples).
* `k` is a character, `x` a string, and `?` an operator that combines them into a new string. (For the core code, `(?)=(:)`. For actually reconstructing the quine data representation, it's more complicated.)
* Thus `y(?)v k = \x->v$k?x` is another function from strings to strings.
* As an example of how this changes associativity, if `(&)=y(:)`:

```
(v&k1&k2&k3) x
= (((v&k1)&k2)&k3) x
= y(:)(y(:)(y(:)v k1)k2)k3 x
= y(:)(y(:)v k1)k2 (k3:x)
= y(:)v k1 (k2:(k3:x))
= v (k1:(k2:(k3:x)))
= v (k1:k2:k3:x)

```

More generally, when `(#)` is the quine data function and `f1,f2` are functions combining characters with strings:

```
(y(f1)#y(f2)$v) x
= (...(y(f1)(y(f1)v '{') '-')...) x
= v(f1 '{' (f1 '-' (... x)))

```

applying the quine data function with `(&)=y(f1)` and `(%)=y(f2)`, and this uses the prescribed `f1` and `f2` to combine the quine data's characters with `x`, and then passes the resulting string to `v`.

The body of the main lambda expression puts this all together:

```
(y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x)$y(:)#y(:)$ \x->x)z

```
* `'&':q:k:q:x` for a character `k` prepends `&'k'` to the string `x`, while `'%':q:'\\':k:q:x` prepends `%'\k'`, which are their original quine data forms.
* Thus `y(\k x->'&':q:k:q:x)#y(\k x->'%':q:'\\':k:q:x` are the right parameters for rebuilding the quine data representation, prepended to the final `z` (the empty string), and then passed on to the following function.
* `y(:)#y(:)` are the right parameters to prepend the quine's core code to a string, without other modification.
* Finally the `\x->x` gets to do nothing with the constructed quine, which is returned.

# Answer
> 9 votes
# Perl 6, 3 quines, 274 bytes

### Quine 1, 52 bytes

```
my&d={S{\d}=$_};say
d
Q{my&d={S{\d}=$_};say
d
Q{4}}

```

Try it online!

### Quine 2, 102 bytes

```
printf	|(q[printf	|(q[@]xx	2	Z~|(q[printf	|(q[!3]]Xx	qw[1	0]))]xx	2	Z~|(q[printf	|(q[!3]]Xx	qw[1	0]))

```

Try it online!

### Quine 3, 120 bytes

```
<'.EVAL'.UC,' GIVEN ',｢｢PRINT "<'.EVAL'.UC,' GIVEN ',｢｢".UC,.UC,"｣｣>.LC",".EVAL.EVAL".UC｣｣>.lc.EVAL.EVAL

```

Try it online!

Verification of distinct sets of bytes

There was a lot of maneuvering in getting that third quine. Perl 6 has 4 methods of output (that I'm aware of), `say`, `put`, `print` and `printf`. Both `say` and `put` output newlines, as I can't use both. `put`, `print`, `printf` all contain `p` and `t`. We can get around this partially by using `EVAL` to use the uppercase `PRINT`. From there, I don't think it's possible to get 4 quines... (though perhaps something like `shell "echo 'quine'"` might work)

We can then get around spacing issues by using different type of whitespace to separate operators, spaces, tabs and newlines.

### Explanations:

### Quine 1:

```
my&d={        };         # Declare a function d which
      S{\d}=$_           # Which substitutes a digit with the string again
                say      # Print with a newline
d                        # The function
Q{my&d={S{\d}=$_};say    # Applied to the string with the program
d
Q{4}}                    # With a digit where the it should be inserted again

```

### Quine 2:

This is a quine in the format `printf |(q[printf q[%s]]xx 2)`, i.e. it formats a copy of the string into itself. However we can't use `s` since that's used in the previous quine's `say`. So we use the string OR operator (`~|`) on `@` and `!3`, to produce the `%s` part, but we can't do that to both the format string and the string to be inserted, so we have to do `Z~` with the extra string and an empty string, though we then can't use `,` to separate the two, so we then do `Xx qw[1 0]` to string multiply by 1 and 0.

```
printf |(                                  )      # Print with formatting
         q[...]       # The string of the program
               xx 2   # Duplicated
                    Z~| (                 )     # String or'd with
                         q[...]                 # A copy to insert the %s
                                Xx              # String multiplied to
                                   qw[1 0]      # itself and an empty string

```

### Quine 3:

This is an EVAL quine that tries its best to make everything uppercase to avoid conflict with the other quines. This involves a *lot* of `EVAL`s as well as quite a few `lc` and `uc` to convert between cases.

```
<...>.lc.EVAL        # Evaluate the lowercase version of the string which results in
.EVAL  given  ｢print "<'.eval'.uc,' given ',｢｢".uc,.uc,"｣｣>.lc",".eval.eval".uc｣
             .EVAL   # Evaluate again

.EVAL  given  ｢...｣   # Set the string to $_ and pass it to .EVAL
print "<'.eval'.uc,' given ',｢｢".uc       # Print the first half of the quine uppercased
                                   ,.uc   # Print the string uppercased
                                       ,"｣｣>.lc"  # Print the .lc part lowercased
                                                ,".eval.eval".uc # Print the EVAL part uppercased

```

# Answer
> 9 votes
# MathGolf, ~~4 5~~ 6 quines, 193,535 bytes

## 9 bytes

```
ÿ'ÿ⌐_'ÿ⌐_

```

Try it online!

## 45 bytes

```
û]∙ûxôû¬ûûûûû╡¬ûô╡û╡xûxxû¬ô]∙xô¬ûûû╡¬ô╡╡xxx¬ô

```

Try it online!

## 49 bytes

```
ùa6æù\a\ù+6┼ù\ùùùùù\ù§\+ùΣ\Σa6æ\a\+6┼\ùùùù\§\+Σ\Σ

```

Try it online!

## 99 bytes

```
"""▐ ⌠▌ ⌠▌ ⌠▌ ⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠"`~

```

Try it online!

## 4488 bytes

```
♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((♠((((((((((((((((((((((((((((((((((((((((((((DÄß─·ö♠,♦M-$*DÄß─ö7($$$qq$Äq╘

```

Try it online!

## 188,845 bytes

I'm can't really link to this one, so here's a Perl 6 program that generates the actual quine

Verification of distinctness

~~I can most definitely squeeze another quine out of this, though I think I've run out of ways to push strings straight to the stack, so I'll have to resort to stranger methods. Even *stranger* methods incoming as I try for a sixth quine. In some cases the quines could be shorter, but I'm reducing used bytes in preparation.~~

Okay, I might *technically* be able to do one more quine, since I still have a few operators that I need (push string, increment string, duplication, mapping, popping), it's the looping that constricts us. The `{}` are the only operators that can can indicate a code block of arbitrary length, and I really need them in the 6th quine. I could use some of the other code blocks, but they're limited, and I doubt the looping sections are going to be that short, since we're running out of easy operators.

Okay, some belated explanations:

All the quines have almost the same structure:

* Push a string, or list of strings, or list of characters to the stack.
* Combine it all into one list
* Duplicate the list
* Map over the copy, printing/pushing the characters used to get the original characters
* Print the original list of characters as a string

### Quine 1:

This is basically the same as the one I posted in the normal quine question.

```
ÿ'ÿ⌐_'ÿ⌐_
ÿ            Push the next 4 bytes as a string
 'ÿ⌐_        Stack ["'ÿ⌐_"]
     'ÿ      Push the byte ÿ (I realise I could have used this in a later quine)
       ⌐     Rotate the ÿ to the bottom of the stack : ["ÿ", "'ÿ⌐_"]
        _    Duplicate top of stack: ["ÿ", "'ÿ⌐_", "'ÿ⌐_"]
             Implicitly print stack joined together : ÿ'ÿ⌐_'ÿ⌐_

```

### Quine 2

```
û                Push the next 2 bytes as a string
 ]∙              Stack: ["]∙û"]
   û  û...      Repeat this for the rest of the code
           ]              Wrap the stack in an array : [["]∙","xô"...]]
            ∙             Triplicate                 : [[..],[..],[..]]
             x            Reverse the top array
              ô           Loop over the array, executing the next 6 instructions
                          Stack: [[..],[..],str]
               ¬          Rotate the stack : [str,[..],[..]]
                ûûû╡      Push the string "ûû" and discard the left character
                    ¬     Rotate the "û" to the bottom : ["û",str,[..],[..]]
                          This produces the initialisation part
                     ô    Loop over the array with the next 6 characters again
                      ╡╡xxx¬      Basically discard the string
                            ô     Flatten the last copy of the array onto the stack
                                  Implicitly output the code

```

### Quine 3:

```
ùa6æù\a\ù+6┼ù\ùùùùù\ù§\+ùΣ\Σa6æ\a\+6┼\ùùùù\§\+Σ\Σ
ù...          Push the next 3 bytes as a string
              You know how this goes
    a         Wrap the top element in an array
     6æ       Repeat the next 4 instructions 6 times
       \      Swap the two top items
        a     Wrap the top item in an array
         \    Swap back
          +   Combine the two arrays
              This puts all the strings into a single array
           6            Push a 6
            ┼           Push the element two items down (the array)
             \          Swap with the 6 (this basically duplicates the array)
              ùùùù      Push "ùùù"
                  \§    Swap and get the 6th character (wrapping)
                    \   Swap with array : ["ù", [..]]
                     +  Prepend to array (implicitly mapping)
                      Σ\Σ     Join both the lists to strings and output

```

### Quine 4:

```
"""▐ ⌠▌ ⌠▌ ⌠▌ ⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠ ⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠"`~
""             Push the empty string
  "..."        Push some code : ['','...']
       `       Copy the top two elements of the stack : ['','...','','...']
        ~      Evaluate the top element as code : ['','...','']
▐              Prepend the empty string to the code
  ⌠            Push a space and increment by 2 to get a quote
   ▌           Prepend to the array
     ⌠▌ ⌠▌ ⌠   Repeat three more times, leaving the last on top : ['', '""...','"']
              ⌠⌠...       Push a space and increment until it reaches a '`'
                    ⌠⌠... Repeat for the '~' : ['','"""...','"','`','~']
                          Implicitly output

```

### Quine 5:

```
♠              Push 256
 ((...         Decrement until it reaches the correct byte representing the code
               Repeat for each character of the code
      DÄ       Repeat the next instruction 14 times
        ß      Wrap the top 4 elements in an array
         ─     Flatten the resulting monstrosity
          ·    Triplicate the array
           ö   Map the next 7 instructions over the array
                      Stack : [[..],[..],num]
            ♠         Push 128
             ,        Reverse subtraction : [[..],[..],128-num
              ♦M-$    Push the ( character
                  *   Repeat it 128-num times
                   DÄß─         Gather that up in an array and flatten again
                       ö        Map the next 6 instructions
                        7($$$qq
                    7($$$q    Print a ♠, without newline
                              q   Print the brackets without newline
                                  Stack : [[..],[..]]
                               $     Map the number to their values in the code page
                                Äq   Map print over each element
                                  ╘  Discard the last element of the stack

```

### Quine 6:

The reason this quine is *so* much longer than the others is that incrementing strings uses unicode representations, which really sucks for the some of the characters in the code, especially when we're trying to create the character  in the code, which inflates the code by over 8000 characters, which then inflates the representation part by a very large amount.

```
⌂         Push an * character
 ))...    Increment until we reach the right character + 8
      ♫{ }            Repeat 10000 times
        α             Wrap the top two elements in an array
          ♫{     }    Then repeat 10000 times
            m{{}}     Shallowly flatten the array
                  h∞<     Double the array
                     m{          Map the doubled array to
                       ïí½<¿{    If it is the first half of the array
                             ⌂⌂  Push two asterisks
                               )))...    Increment into a '⌂' (there are something like 8000 )s here, with a couple of ! to help
                                     @   Rotate the top three elements
                                         Stack : ["⌂",char,"*"]
                                      0{     α4<{}=}←  Repeat while the asterisk is not the char
                                        ⌂⌡)   Push a )
                                           @  Rotate it under the char
                                            ) Increment the asterisk
                                                     ;;   Pop the extra copies of the character
                                                       }{  Else
                                                         ⌡⌡⌡⌡}   Subtract 8 from the character
                                                              }{}  End map and flatten array
                                                                   Print implicitly

```

This last quine would be reduced significantly if MathGolf was consistent on whether strings used the native code page or not.

# Answer
> 6 votes
# Python 2, 2 quines, ~~434~~ ~~353~~ ~~349~~ 446 bytes

This was mostly just to see if I could do it in Python.

30 bytes (including a trailing newline):

```
z='z=%r;print z%%z';print z%z

```

and 416 bytes, with no trailing newline:

```
exec"696d706f7274207379730a793d222222696d706f7274207379730a793d7b7d0a7379732e7374646f75742e777269746528276578656322272b792e666f726d6174282722272a332b792b2722272a33292e656e636f6465282268657822292b27222e6465636f64652822686578222927292222220a7379732e7374646f75742e777269746528276578656322272b792e666f726d6174282722272a332b792b2722272a33292e656e636f6465282268657822292b27222e6465636f6465282268657822292729".decode("hex")

```

(Golfed 81 bytes thanks to Lynn but added a load due to caring about the newline.)

# Explanation

The first one is just the standard short Python quine, but modified not to use `_`. Since this is Python 2 it also doesn't use `(` or `)`.

The second one took some thought. The long string is encoded using the `hex` codec (thus guaranteeing that it will only contain `0`-`9` and `a`-`f`) and decodes as

```
import sys
y="""import sys
y={}
sys.stdout.write('exec"'+y.format('"'*3+y+'"'*3).encode("hex")+'".decode("hex")')"""
sys.stdout.write('exec"'+y.format('"'*3+y+'"'*3).encode("hex")+'".decode("hex")')

```

This uses quine trickery to get its own source code, then encodes it using `hex_codec`, and then prints it surrounded by `exec"".decode("hex")`, using `sys.stdout.write` to avoid printing a newline. Running this code outputs the second quine, which is how I generated it.

I suspect that more than two is impossible in Python, though I would like to see it if I'm wrong!

# If you don't mind eval quines

Ørjan Johansen suggested the following for the pre-encoded second quine

```
y="""import sys
sys.stdout.write('exec"'+('y='+'"'*3+y+'"'*3+';exec y').encode("hex")+'".decode("hex")')""";exec y

```

which would score 30+248=**278** bytes for the following output:

```
exec"793d222222696d706f7274207379730a7379732e7374646f75742e777269746528276578656322272b2827793d272b2722272a332b792b2722272a332b273b65786563207927292e656e636f6465282268657822292b27222e6465636f64652822686578222927292222223b657865632079".decode("hex")

```

The use of `exec` in this way is not cheating according to the PPCG proper quine rules but it feels somewhat cheaty to me (elegant and clever, but still cheaty), because some characters are being used as both code and data. (Although my version does use `exec`, the code and the data are separate.) So I will keep my score at 446.

# Answer
> 5 votes
# Japt, ~~2~~ 3 quines, ~~106~~ 172 bytes

The first one is a pretty verbose version of my N char quine answer.

```
[91,57,49,100,185,44,85,44,186,57,51,100,185,44,186,49,48,100,185,44,186,85,109,100,185,172,93,172]
[91d¹,U,º93d¹,º10d¹,ºUmd¹¬]¬

```

Try it here.

The second quine is ETHProduction's greater good quine, which is a good standard quine for Japt.

```
"iQ ²"iQ ²

```

Try it here.

The third one uses ```` and char-code XORing to store the data.

```
T=`f=fR;Zff-R-ReX%`;`T=\``+T+Tc^#

```

Try it here.

Since `()'` are still available, it *might* be possible to squeeze out one more quine.

# Answer
> 4 votes
# Javascript ES6, 2 quines, 43 + 22 = 65 bytes

Quine 1:

```
(function f(){return[,f,'))'].join('(')}())

```

Quine 2:

```
g=z=>"g="+g+";g``";g``

```

# Answer
> 4 votes
# Gol\>\<\>, <sub>~~2~~</sub> 3 quines, <sub>~~17 28 27~~</sub> 26 bytes

## 6 bytes

```
"r2ssH

```

Try it online!

## <sub>~~11 10~~</sub> 9 bytes

```
'3d*Wo{|;

```

Try it online!

## 11 bytes

```
Eh`#Ma0piS0

```

Try it online!

Gol\>\<\> has three ways to print any char:

* `o` Pop one value and print as char
* `H` Pop everything, print as char, and halt
* `S"..."` Print string literal without affecting the stack at all

But I couldn't find a way to write a quine using `S"..."` as the only output method, so I came up with the above two, utilizing the two kinds of string literals.

The third one (by Jo King) uses the `p` command to create the `"` in `S"` on the fly, which in turn prints everything except the zero at the end. Then `Eh` prints the zero and exits.

Now that we used up all the output commands AND the `p` command, I believe it's impossible to create another quine (unless someone comes up with the `S"` quine without `p`).

# Answer
> 3 votes
# Ruby, 2 quines, 27 + 44 = 71 bytes

```
$><<<<2*2<<2
$><<<<2*2<<2
2

```

Try it online!

```
s=%q{s=%q{S};s[?S]=s;puts s};s[?S]=s;puts s

```

Try it online!

I'm mainly limited by methods of output, here. There are quite a few ways of manipulating strings, but aside from `$><<` all the usable output methods seem to intersect too much. I think there might be a way out with `eval` but it's tricky having to nest multiple string manipulations of different kinds.

# Answer
> 3 votes
# \>\<\>, 2 quines, 8 + 16 = 24 bytes

### 8 bytes

```
#o<}-1:"

```

Try it online!

Taken from this answer.

---

### 16 bytes

```
'r3d*d8*7+e0p>>|

```

Try it online!

This is based on the `'r3d*>o<` quine, except `o` and `<` cannot be used, so I replaced `<` with `|` and dynamically created `o` (111 = 8\*13 + 7) and placed it where the 2nd `>` is.

---

**2 quines is the limit**

Unfortunately, we're limited by the number of output commands. `n` is not useful because it only outputs numbers, so `o` must be executed in any quine. The only way to dynamically create `o` is with `p`. So one quine can use `o`, and another can create it with `p`, but there can be no 3rd quine.

It might be possible to have a third quine leave the source code on the stack if that counts.

# Answer
> 2 votes
# Java 10, 2 quines, ~~1448~~ 1248 bytes

# ~~1350~~ 1122 bytes

```
\u0076\u002D\u003E\u007B\u0076\u0061\u0072\u0020\u0072\u003D\u0022\u0076\u002D\u003E\u007B\u0076\u0061\u0072\u0020\u0072\u003D\u0025\u0063\u0025\u0073\u0025\u0031\u0024\u0063\u003B\u0072\u002E\u0066\u006F\u0072\u006D\u0061\u0074\u0028\u0072\u002C\u0033\u0034\u002C\u0072\u002C\u0039\u0032\u0029\u002E\u0063\u0068\u0061\u0072\u0073\u0028\u0029\u002E\u0066\u006F\u0072\u0045\u0061\u0063\u0068\u0028\u0063\u002D\u003E\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0066\u0028\u0025\u0031\u0024\u0063\u0025\u0063\u0025\u0033\u0024\u0063\u0075\u0025\u0025\u0030\u0034\u0058\u0025\u0031\u0024\u0063\u002C\u0063\u0029\u0029\u003B\u007D\u0022\u003B\u0072\u002E\u0066\u006F\u0072\u006D\u0061\u0074\u0028\u0072\u002C\u0033\u0034\u002C\u0072\u002C\u0039\u0032\u0029\u002E\u0063\u0068\u0061\u0072\u0073\u0028\u0029\u002E\u0066\u006F\u0072\u0045\u0061\u0063\u0068\u0028\u0063\u002D\u003E\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u0066\u0028\u0022\u005C\u005C\u0075\u0025\u0030\u0034\u0058\u0022\u002C\u0063\u0029\u0029\u003B\u007D

```

Try it online.

Equivalent to:

```
v->{var r="v->{var r=%c%s%1$c;r.format(r,34,r,92).chars().forEach(c->System.out.printf(%1$c%c%3$cu%%04X%1$c,c));}";r.format(r,34,r,92).chars().forEach(c->System.out.printf("\\u%04X",c));}

```

**Explanation:**

```
v->{                   // Method with empty unused parameter and no return-type
  var r="v->{var r=%c%s%1$c;r.format(r,34,r,92).chars().forEach(c->System.out.printf(%1$c%c%3$cu%%04X%1$c,c));}";
                       //  Unformatted source code
  r.format(r,34,r,92)  //  Formatted quine
   .chars()            //  Loop over the characters as integers
   .forEach(c->System.out.printf("\\u%04X",c));}
                       //   Print "\u" with hexadecimal value of these characters

```

---

# 126 bytes

```
v->{int i='}'-'[';var s="v->{int i='}'-'[';var s=%c%s%c;System.console().printf(s,i,s,i);}";System.console().printf(s,i,s,i);}

```

`System.console()` will return `null` when none is provided, so TIO returns a `NullPointerException` in this case.

To prove it's a working quine, replace `System.console()` with `System.out`: Try it online.

**Explanation:**

```
v->{              // Method with empty unused parameter and no return-type
  int i='}'-'[';  //  Integer `i` = 34 (unicode value for double-quote)
  var s="v->{int i='}'-'[';var s=%c%s%c;System.console().printf(s,i,s,i);}";
                  //  Unformatted source code
  System.console().printf(s,i,s,i);}
                  //  Print formatted quine

```

---

**General explanation:**

In Java a is usually done like this:

* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.

In which case the shortest quine lambda-function in Java 10 would be this (**82 bytes**):

```
v->{var s="v->{var s=%c%s%1$c;return s.format(s,34,s);}";return s.format(s,34,s);}

```

Try it online.

Since the only way to have two quines in Java is using the unicode version with `\uHEXA`, which is converted to characters during compilation, I'm unable to use the characters `0123456789ABCDEF\u` in the non-unicode version. So, the smaller non-unicode version will use `System.console()` instead of `return` or `System.out` (both containing a 'u'), and will use `'}'-'['` and two times `%c` instead of `34` and `%1$c`.

Some things to note about the unicode version:

* I'm on purpose using `%04X` instead of `%04x` (for uppercase Hexadecimal instead of lowercase).
* I'm using `92`, `%c` and `%3$c` to format the slashes.
* Using a capital `\U` instead of lowercase `\u` isn't allowed apparently, otherwise I would have just used `return` in the shorter non-unicode version.

---
Tags: code-challenge, restricted-source, quine
---