title: Polyglot Interpreters

text:
# Question
Title: Polyglot Interpreters
## Challenge

1. Choose any number of languages. Call this set `L`.
2. Write a program so that running it in any language in L produces an interpreter for a **different** language in `L`. Each language in `L` must have **exactly one** interpreter for it. This is to prevent, for example, Nothing or Text being part of `L` and all interpreters being for that single language.
3. Your score is the number of bytes of your code divided by the number of languages in `L`. Lowest score wins.

## Rules

* Any language may have an interpreter for any other language -- it doesn't need to be one large cycle.
* An interpreter can input program code and input however you see fit.
* Standard loopholes apply.
* Different versions of a language count as distinct (e.g. Python 3.4 and 3.5) but not patch versions (e.g. Python 3.4.1 and 3.4.4). *Thanks to caird coinheringaahing for this.*

## Example Submission *(clarified due to Kaddath's comment)*

# [Julia 1.0](https://julialang.org) and [Brainf***](https://esolangs.org/wiki/brainfuck), B bytes / 2 languages = B/2
```
#=
<julia interpreter written in brainf***>
[-][
=#
<brainf*** interpreter written in julia>
# ]
```
Julia 1.0: [Try it online!](https://tio.run/#julia1x)
Brainf***: [Try it online!](https://tio.run/#brainfuck)
Explanation:
When ran in Brainf***, the Brainf*** code is run. The `[-]` sets the current cell to zero, then we skip over the rest of the code using `[ ... ]` since we know the current cell is zero.
When ran in Julia, the `#= ... =#` marks a comment, letting the Brainf*** code not get executed. After that is the Brainf*** interpreter, then the final line would have an unmatched `]`, so it is commented out.

# Answer
# Jelly `u` / Python 3 \+ jelly, 70 bytes = 35

```
from jelly import*
a=sys.argv
main(a[1],[*map(try_eval,a[2:])],'')
ŒV

```

Try it online! (Jelly)

Try it online! (Python)

Both error after executing the other language.

This is a bit of a cheat tbh. Jelly has an "execute as Python" builtin, `ŒV`, and, as of April 9, 2018, Jelly is a `pip`-installable package, meaning that we can just import it and run it.

## How they work

Jelly ignores every line except for the last, and just runs that:

```
ŒV - Main link. Takes a string on the left
ŒV - Execute the string as Python code

```

For some reason, I think because of the `[...]` in the above lines, there's some parsing error thrown afterwards.

For Python, we import the contents of the `jelly` package, read and evaluate the command-line arguments, then run the program in the first command-line argument with the values in the second and third arguments
> 6 votes

# Answer
# Windows Batch/Powershell 7, 38 bytes, 19 score

```
ls >$null&&cmd /c "$args"
pwsh -c "%*"

```

Assumes that there is no file named `ls` in current directory plus Powershell 7 executable `pwsh.exe` is in PATH.

It needs Powershell 7 because `&&` and `||` syntactic sugar was introduced in that version.

It first checks if any command is `ls`, `>$null` suppresses the output. If it succeeded we assume the interpreter is Powershell, so we execute Batch code and vice versa.

It generates some extra errors besides the STDOUT, but I think that's fine because @caird's answer also errors.
> 2 votes

# Answer
# Windows Batch / PHP \< 8, 25 bytes, Score: 12.5

```
php -r %1;echo`$argv[1]`;

```

(cannot really) Try it online for PHP! (it runs, but external scripts seem to be disabled, for security reasons I guess)

Cannot test Windows Batch in TIO and haven't found another site for it (makes sense actually) -\> you can place the code in a `test.bat` file and run something like `test.bat "echo 42;"` to pass the PHP code as parameter

* Assumes that PHP executable is in PATH under the `php` command.
* in PHP below version 8, `php` and `r` are assumed string constants, and `-` `%` are operators, this part tries to calculate the result but does nothing with it. The rest of the code executes the argument as command-line code and outputs the result.
* in Windows Batch, executes the first argument received as PHP code and outputs the result. The rest of the code is considered as a second argument and is ignored.
> 1 votes

---
Tags: code-challenge, interpreter, polyglot
---


# Question
Title: Convert number to a base where its representation has most "4"s
Inspired by this. There is a number, given as either integer, string or array of digits (your choice). Find the base in which the representation of the number will have most "4"s and return that base.

```
Number    Result
624        5
444       10
 68       16

```

restrictions:

* The base returned should not be greater than the input.
* Numbers less than or equal to 4 should not be considered valid input, so undefined returns are acceptable

# Answer
## APL (~~31~~ 19)

Now tests all possible bases.

```
⊃⍒{+/4=K⊤⍨K⍴⍵}¨⍳K←⎕

```

Explanation:

* `⍳K←⎕`: read user input, store in K. Make a list from 1 to K, which are the bases to try.
* `{`...: for each of these, run the following function
* `K⊤⍨K⍴⍵`: encode K into that base giving a list of digits (as numbers) per base. Use K digits (a big overestimate, but it doesn't matter because the unused ones will all be zero anyway).
* `4=`: see which of these are equal to 4
* `+/`: sum these, now we know how many fours per base
* `⊃⍒`: give the indices of the list if it were sorted downwards, so the index of the biggest one is at the front. Take the first item of this list.
> 24 votes

# Answer
### GolfScript, 30 characters

```
.,{[2+.2$\base{4=},,\]}%$)~p];

```

Works for any base - test the code online.

*Comment:* This solution was based on the original version of the question. It thus may return a base larger than the input, e.g. for the input 4 it correctly returns base 5 - which is no longer valid by the new rules.
> 5 votes

# Answer
## VBA, 121

```
Function k(a)
For w=5 To a
Z=0:q=a:Do:c=q Mod w:Z=Z-(c=4):q=Int(q/w):Loop Until q=0
If Z>x Then x=Z:k=w
Next
End Function

```

usage:

* direct window: `?k(num)`
* Excel formula: `=k(A1)`
> 4 votes

# Answer
## Python 2.x, 77 chars

```
F=lambda x:max((sum(x/b**d%b==4for d in range(99)),b)for b in range(5,99))[1]

```

Works up to base 98 and numbers at most 98 digits long.
> 4 votes

# Answer
## J, 38 characters

```
f=.[:(i.>./)[:+/[:|:4=(10#"0(i.37))#:]

```

Usage:

```
   p 624
5
   p 444
10
   p 68
16

```
> 4 votes

# Answer
## GolfScript (23 chars)

```
~:^,2>{^\base[4]/,~}$0=

```

or

```
~:^,2>{^\base[4]/,}$-1=

```

or

```
~:^,2>{^\base[4]/,}$)\;

```

Note that this takes input from stdin: for a fair comparison with Howard's GolfScript version subtract one char.

---

Howard points out that the rules have changed, and it's not very logical that they now exclude `4` as a possible input when it has a valid output (any integer greater than 4). To cover that case as well requires an extra 2 characters, which can be added in all kinds of ways:

```
~:^)),2>{^\base[4]/,}$)\;

```

or

```
~:^,{))^\base[4]/,}$)))\;

```

being a couple of the obvious ones.
> 4 votes

# Answer
# Jelly, 6 bytes

```
bⱮċ€4M

```

Try it online!

Outputs "all" bases up to N which gives the most 4's. If you want maximal or minimal base, add  (max) or  (min) respectively.

### How it works

```
bⱮċ€4M    Main link (monad). Input: integer N.
bⱮ        Convert N to each base of 1..N
  ċ€4     Count 4's in each representation
     M    Take maximal indices

```
> 4 votes

# Answer
# Mathematica 59

**Code**

```
Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[5, 36]][[-1, 2]]

```

Let's give the above function a name.

```
whichBase[n_] := Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[2, 36]][[-1, 2]]

```

**Explanation**

1. `Count[IntegerDigits[n,k],4]`: Count the number of fours in the base *k* representation of *n*.
2. `Sort` the bases from fewest to most 4s.
3. Return the base from the last item in the list, that is, the base that had the representation with the most 4's.

**Some special numbers**

Now let's apply whichBase to the following special numbers.

```
numbers= {1953124, 8062156, 26902404, 76695844, 193710244, 444444444,
943179076, 1876283764, 3534833124, 6357245164, 10983816964,
18325193796, 29646969124, 46672774204, 71708377284, 107789473684,
158856009316, 229956041484, 327482302084, 459444789604, 635782877604,
868720588636, 1173168843844, 1567178659764, 2072449425124,
2714896551724, 3525282954756, 4539918979204, 5801435550244,
7359635486844, 9272428079044, 11606852190676}

```

> {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, \ 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}

If you convert each number to the corresponding base, you will see what is special about them.
> 3 votes

# Answer
# Japt `-h`, 10 bytes

`444` in base `10` is `[4,4,4]` which contains the number *and* digit `4` 3 times but `444` in base `100` is `[4,44]` which also contains the digit `4` 3 times, but only as a number once. Given the expected output in the challange for the `444` test case, I'd guess we're supposed to be counting the number 4:

```
õ ñ@ìX è¥4

```

Try it

But if we *are* counting the digit 4 then:

```
õ ñ@ìX ¬è4

```

Try it

```
õ              :Range [1,...,input]
  ñ@           :Sort by passing each X through a function
    ìX         :  Convert the input to a base X digit array
               :(VERSION 1)
       è       :  Count the elements
        ¥4     :    Equal to 4
               :(VERSION 2)
       ¬       :  Join to a string
        è4     :  Count the occurrences of "4"
               :Implicitly output the last element in the sorted array

```
> 3 votes

# Answer
# C - (114 characters)

In all it's golfy glory:

```
x,k,c,d,n;main(v){scanf("%d",&v);for(k=5;v/k;++k){x=v;c=0;while(x)c+=x%k==4,x/=k;c>=d?n=k,d=c:0;}printf("%d",n);}

```

And somewhat ungolfed:

```
x,k,c,d,n; // declare a bunch of ints, initialized to 0
main(v){   // declare one more, without using an extra comma
    scanf("%d",&v); // get the input (v)
    for(k=5;v/k;++k){ // loop over each base (k) greater than or equal to (/)
                      // our input (v)
        x=v;          // temp value (x) set to input (v)
        c=0;          // number of 4s in the current base (c) re-initialized
        while(x)       // loop over our temp until it's used up
            c+=x%k==4, // if the next digit (x%k) is 4 (==4) increment the
                       // current count (c+=)
            x/=k;      // remove the current digit
        c>=d?n=k,d=c:0; // if the number of 4s in this base (c) is greater
                       // than the current maximum number of 4s (d), then
                       // save the new best base (n), and new maximum
                       // number of 4s
    }
    printf("%d",n);   // output the result
}

```

Just for fun here's the output for the numbers `[0,127]` (these are the largest bases under the input number itself).

> 0, 0, 0, 0, 0, 5, 6, 7, 8, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 5, 21, 22, 23, 6, 25, 26, 27, 7, 29, 30, 31, 8, 33, 34, 35, 9, 37, 38, 39, 10, 41, 42, 43, 11, 5, 46, 47, 12, 49, 50, 51, 13, 53, 54, 55, 14, 57, 58, 59, 15, 61, 62, 63, 16, 65, 66, 67, 17, 69, 5, 71, 18, 73, 74, 75, 19, 7, 78, 79, 20, 81, 82, 83, 21, 85, 86, 87, 22, 89, 90, 91, 23, 93, 94, 5, 24, 97, 98, 99, 25, 101, 102, 103, 26, 5, 106, 107, 27, 109, 5, 111, 28, 113, 114, 5, 29, 9, 5, 5, 5, 121, 122, 123
> 2 votes

# Answer
**R - ~~148~~ 137 chars**

(so, far away from the rest of the competition but still)

```
f=function(n){s=sapply;which.max(s(lapply(strsplit(s(4:n,function(x){q=n;r="";while(q){r=paste(q%%x,r);q=q%/%x};r})," "),`==`,4),sum))+3}

```

Basically transform the input from base 10 to all bases from 4 to n (using modulo `%%` and integer division `%/%`) and pick the index of the first one having the most 4s.

```
f(624)
[1] 5
f(444)
[1] 10

```
> 2 votes

# Answer
J translation of @marinus' APL solution:

```
NB. Expression form (22 characters, not including "n" - the "argument"):
{.\:(+/@(4=$#:[)"0 i.)n
NB. Function form (24 characters, not including "f=:"):
f=:{.@\:@(+/@(4=$#:[)"0 i.)

```

Just for interest, here are some values:

```
(,.f"0)9+i.24
 9  5
10  6
11  7
12  8
13  9
14  5
15 11
16  6
17 13
18  7
19  5
20  5
21  5
22  5
23  5
24  5
25  6
26  6
27  6
28  6
29  5
30  7
31  7
32  7

```

It outputs the smallest base that gives a fouriest transform. For the last few values in the table, the representations look like “4n” (e.g 31 in base 7 is “43”).
> 2 votes

# Answer
# 05AB1E, ~~10~~ 9 bytes

```
LBε4¢}Zk>

```

-1 byte thanks to *@Cowabunghole*.

If multiple bases have the same amount of 4s, it will output the smallest one (i.e. `16` will result in `6`, but `12` would also have been a possible output).

Try it online or verify all test cases.

**Explanation:**

```
L           # Create a list in the range [1, (implicit) input]
            #  i.e. 624 → [1,2,3,...,622,623,634]
 B          # Convert the (implicit) input integer to Base-N for each N in this list
            #  i.e. 624 and [1,2,3,...,622,623,624]
            #   → ["1","1001110000","212010",...,"12","11","10"]
  ε  }      # Map this list to:
   4¢       #  Count the number of 4s in the number
            #   → [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0]
      Z     # Take the max (without popping the list)
            #  i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] → 4
       k    # Get the index of this max in the list
            #  i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] and 4 → 4
         >  # Increase it by to convert the 0-index to our base (and output implicitly)
            #  i.e. 4 → 5

```
> 2 votes

# Answer
# , 18 bytes

```
{*>+/'4=x{y\x}'!x}

```

Try it online!

```
{                } /function(x)
        x     '!x  /for every y in 0, 1, ..., (x-1):
         {y\x}     /    do x in base y
      4=           /see which digits equal four
   +/'             /sum, to get number of 4s per base
 *>                /get index (which equals base) of largest number of 4s

```
> 2 votes

# Answer
C# (482 ~423 Bytes)

First attempt at a 'golfed' solution. I used basically the same algorithm as the VBA above. I could probably save some bytes inlining the conversion function, or shortening the name. Like I said this is a first attempt, so please be gentle.

With whitespace:

```
using System;
class Program
{
    static void Main(string[] args)
    {
        int n = int.Parse(args[0]);
        int c=0, m=0;
        string r="";
        int t = 0;
        for (int i = 5; i < 37; i++)
        {
            while (n > 0)
            {
                r = (char)((int)(n % i) + 48 + (7 * ((int)(n % i) > 9 ? 1 : 0))) + r;
                n = (int)(n / i);
            }
            t = r.Length - r.Replace("4", "").Length;
            if (t > c) { c = t; m = i; }
        }
        Console.WriteLine("Base: " + m);
    }
}

```
> 1 votes

# Answer
**C# with Linq 273**

```
using System;using System.Linq;class P{static void Main(){int r,z,k=int.Parse(Console.ReadLine());if(k<=4) return;Console.WriteLine(Enumerable.Range(4, k).Select(x =>{r = 0;z = k;while (z > 0){if(z % x==4){r++;}z/=x;}return new[]{r, x};}).OrderBy(n => n[0]).Last()[1]);}}

```

or

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        int r, z, k = int.Parse(Console.ReadLine());
        if (k <= 4) return;
        Console.WriteLine(
            Enumerable.Range(4, k).Select(x =>
                {
                    r = 0;
                    z = k;
                    while (z > 0)
                    {
                        if (z % x == 4)
                        {
                            r++;
                        }
                        z /= x;
                    }
                    return new[] { r, x };
                }).OrderBy(n => n[0]).Last()[1]);

    }
}

```

Pretty sure the number of variables can be reduced and the if's can be converted to ?s. Oh well...
> 1 votes

# Answer
## Burlesque - 28 bytes

```
Jbcjro{dg}Z]J{4CN}Cmsb[~Fi?i
Jbcjro                        create a list 1..input and convert input
                              to an infinite list.
      {dg}Z]                  convert number to base (zipWith operation)
            J                 duplicate
             {4CN}Cm          create comparison function
              4CN             count the number of fours.
                    sb        sort by
                      [~      take the last element (which is going to be
                              the base-n representation where count of fours
                              is highest)
                        Fi    Find the index of this last element in the original
                              unsorted list
                          ?i  increment (because base 1 is index 0)

```

Try it online.
> 1 votes

# Answer
# Perl 6, 44 bytes

```
{max 5..$^a,by=>{grep 4,$a.polymod($_ xx*)}}

```

Try it online!

Good old polymod.
> 1 votes

# Answer
# Husk, 9 bytes

```
S€►#4ṠMBḣ

```

Try it online!

```
 €           The 1-based index in
      MB     the list of the input's representations in every base
     Ṡ  ḣ    from 1 to itself
S ►          of its element which has the largest
   #         number of
    4        fours.

```
> 1 votes

# Answer
# Julia, 50 bytes

```
n->sort(2:n+1,by=b->-sum(digits(n,base=b).==4))[1]

```

Try it online!
> 0 votes

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


title: Parse the resistors

text:
# Question
Title: Parse the resistors
The aim is simple: given the string of resistance values, draw the part of "electrical circuit" of those resistors. Examples follow.

1. Input: `3`. Output:

```
--3--

```
2. Input: `1,2,3`. Output:

```
--1----2----3--

```

Next, the resistors can be joined parallel (by 2 or 3 resistors per join), but the required depth of parallel joins is only 1.

3. Input: `1|2`. Output:

```
 |--1--|
-|     |-
 |--2--|

```
4. Input: `1|2|3`. Output:

```
 |--1--|
-|--2--|-
 |--3--|

```

**Note**, that `--2--` resistor is now centered.
5. Input: `1|2,3|4|5`. Output:

```
 |--1--|  |--3--|
-|     |--|--4--|-
 |--2--|  |--5--|

```

Combined joins:

6. Input: `1,2,3|4,5,6|7|8,9`. Output:

```
           |--3--|       |--6--|
--1----2---|     |---5---|--7--|---9--
           |--4--|       |--8--|

```

If it would be more convenient, the input can be a two-dimensional array. I.e. the input for the last example would look like this: `[1,2,[3,4],5,[6,7,8],9]`.

Some notes:

* No other forms of (in|out)puts are allowed.
* The resistance of each resistor can vary in the range from 1 to 9. Other values, like `-`, `42` or `0` are disallowed.
* The joins like `1|2|3|4` are invalid. As already mentioned, max 3 per parallel join. Empty joins, i.e. `...,|,...` or `...,,...` are invalid.
* Oh, and this is code golf :)

# Answer
## Python 2, 195 bytes

```
a=b=c=''
B=' '*5
H='--'
S=' |'+H;E=H+'| '
for x in input():
 if x>9:a+=S+`x[0]`+E;c+=S+`x[-1]`+E;b+='-|'+[B,H+`x[1]`+H][len(x)>2]+'|-'
 else:b+=H+`x`+H;a+=B;c+=B
print[b,a+'\n'+b+'\n'+c]['|'in a]

```

Takes input as:

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

```

Output:

```
           |--3--|       |--6--|
--1----2---|     |---5---|--7--|---9--
           |--4--|       |--8--|

```
> 4 votes

# Answer
# Vyxal, 64 bytes

```
ƛI⁼[h\-dpømð5*:‟W|ƛ`|--`pøm;:L2=[÷`|   `øm$W]];DvhṄ,ƛ1i;\-j,vtṄ,

```

Try it Online!
> 5 votes

# Answer
# 05AB1E, ~~45~~ 42 bytes

```
ε€…--ÿDgið.ø.BëÁð3×ª3£À'|ì… - SδìÅ\]€.ºøJ»

```

Try it online!
> 5 votes

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

```
n=>(H=M=>n.map(e=>(T=e[M]||e[1])?` |${(G=e=>`--${e}--`)(T)}| `:'     ').join``)(0)+`
${n.map(e=>+e?G(e):`-|${e[2]?G(e[1]):'     '}|-`).join``}
`+H(2)

```

Try it online!

No need to overcomplicate things, just keep it simple
> 3 votes

# Answer
# Haskell, 132 bytes

```
foldr(zipWith(:))e.(>>=g)
a=" - "
b="|||"
s%c=[a,b,c,c,s,c,c,b,a]
g[x]=[a,a,' ':x:" ",a,a]
g[x,y]=[x,' ',y]%"- -"
g z=z%"---"
e=[]:e

```

Try it online!

Takes input as a `[[Char]]` and outputs a list of lines.
> 2 votes

# Answer
# Julia 1.5, 129 bytes

```
s=" "^5
+x="--$x--"
!x=map(*,[" |","-|"," |"],x,["| ","|-","| "])
-x=[[s,.+x,s],![+x[1],s,+x[(l=end;)]],!.+x][l]
~x=map(*,.-x...)

```

Try it online!

output is a list of lines
> 1 votes

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


title: Output a Sudoku board

text:
# Question
Title: Output a Sudoku board
Today's challenge is simple: Without taking any input, output any valid sudoku board.

In case you are unfamiliar with sudoku, Wikipedia describes what a valid board should look like:

> The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") contains all of the digits from 1 to 9.

Now here's the thing... There are 6,670,903,752,021,072,936,960 different valid sudoku boards. Some of them may be very difficult to compress and output in fewer bytes. Others of them may be easier. Part of this challenge is to figure out which boards will be most compressible and could be outputted in the fewest bytes.

Your submission does not necessarily have to output the same board every time. But if multiple outputs are possible, you'll have to prove that every possible output is a valid board.

You can use this script (thanks to Magic Octopus Urn) or any of these answers to verify if a particular grid is a valid solution. It will output a `[1]` for a valid board, and anything else for an invalid board.

I'm not too picky about what format you output your answer in, as long as it's clearly 2-dimensional. For example, you could output a 9x9 matrix, nine 3x3 matrices, a string, an array of strings, an array of 9-digit integers, or nine 9-digit numbers with a separator. Outputting 81 digits in 1 dimension would not be permitted. If you would like to know about a particular output format, feel free to ask me in the comments.

As usual, this is , so write the shortest answer you can come up with in the language(s) of your choosing!

# Answer
# Pyth, ~~22~~ ~~14~~ ~~12~~ 10 bytes

```
.<LS9%D3 9

```

Saved 2 bytes thanks to Mr. Xcoder.

Try it here

```
.<LS9%D3 9
     %D3 9     Order the range [0, ..., 8] mod 3.
  >            For each, ...
.< S9          ... Rotate the list [1, ..., 9] that many times.

```
> 13 votes

# Answer
# Python 2, 47 bytes

```
l=range(1,10)
for x in l:print(l*9)[x*8/3:][:9]

```

Try it online!
> 12 votes

# Answer
# T-SQL, ~~96~~ 89 bytes

Found one shorter than the trivial output!

```
SELECT SUBSTRING('12345678912345678',0+value,9)FROM STRING_SPLIT('1,4,7,2,5,8,3,6,9',',')

```

Extracts 9-character strings starting at different points, as defined by the in-memory table created by `STRING_SPLIT` (which is supported on SQL 2016 and later). The `0+value` was the shortest way I could do an implicit cast to integer.

Original trivial output (96 bytes):

```
PRINT'726493815
315728946
489651237
852147693
673985124
941362758
194836572
567214389
238579461'

```
> 9 votes

# Answer
# Jelly, 7 bytes

```
9Rṙ%3$Þ

```

Try it online!

*And a little bit of this...*
-1 thanks to Jonathan Allan('s thinking?)
> 7 votes

# Answer
# Python 2, 53 bytes

```
r=range(9)
for i in r:print[1+(j*10/3+i)%9for j in r]

```

Try it online!

---

Alternatives:

# Python 2, 53 bytes

```
i=0;exec"print[1+(i/3+j)%9for j in range(9)];i-=8;"*9

```

Try it online!

# Python 2, 54 bytes

```
for i in range(81):print(i/9*10/3+i)%9+1,'\n'*(i%9>7),

```

```
i=0;exec"print[1+(i/3+j)%9for j in range(9)];i+=10;"*9

```

```
r=range(9);print[[1+(i*10/3+j)%9for j in r]for i in r]

```
> 6 votes

# Answer
# Python 3, ~~58~~ 55 bytes

```
l=*range(10),
for i in b"	":print(l[i:]+l[1:i])

```

Try it online!

* -3 bytes thanks to Jo King,

The elements of the byte string end up giving the numbers `[1, 4, 7, 2, 5, 8, 3, 6, 9]` which are used to permute the rotations of `[0..9]`. The `0` is removed in `l[1:i]` and there is no need for a null byte which takes two characaters (`\0`) to represent in a bytes object.

**55 bytes**

```
_,*l=range(10)
for i in b"	":print(l[i:]+l[:i])

```
> 5 votes

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

Output as an array of the rows.

```
_=>[...w="147258369"].map(x=>(w+w).substr(x,9))

```

Try it online!

Generates this:

```
472583691
583691472
691472583
725836914
836914725
914725836
258369147
369147258
147258369
```
> 5 votes

# Answer
# Jelly, ~~9~~ 8 bytes

```
9Rṙ`s3ZẎ

```

Try it online!

```
9Rṙ`s3ZẎ
9R         Range(9) -> [1,2,3,4,5,6,7,8,9]
   `       Use the same argument twice for the dyad:
  ṙ        Rotate [1..9] each of [1..9] times.
           This gives all cyclic rotations of the list [1..9]
    s3     Split into three lists.
      Z    Zip. This puts the first row of each list of three in it's own list,
           as well as the the second and third.
       Ẏ   Dump into a single list of nine arrays.

```
> 4 votes

# Answer
## Batch, 84 bytes

```
@set s=123456789
@for %%a in (0 3 6 1 4 7 2 5 8)do @call echo %%s:~%%a%%%%s:~,%%a%%

```

Uses @Mnemonic's output. `call` is used to interpolate the variable into the slicing operation (normally it only accepts numeric constants).
> 4 votes

# Answer
# Perl 6, ~~40 32~~ 27 bytes

*-5 bytes thanks to nwellnhof*

```
{[^9+1].rotate($+=3.3)xx 9}

```

Try it online!

Anonymous code block that returns a 9x9 matrix. Maps each row to a different rotation of the range 1 to 9.
> 4 votes

# Answer
# 05AB1E, ~~14~~ 12 bytes

```
8ÝΣ3%}ε9Ls._

```

-2 bytes by creating a port of *@Mnemonic*'s Pyth answer.

Try it online. (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)

**Explanation:**

```
8Ý              # List in the range [0, 8]
  Σ  }          # Sort the integers `i` by
   3%           #  `i` modulo-3
      ε         # Map each value to:
       9L       #  List in the range [1, 9]
         s._    #  Rotated towards the left the value amount of times

```

---

**Original 14 bytes solution:**

```
9Lε9LN3*N3÷+._

```

Try it online. (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)

**Explanation:**

```
9L                # Create a list of size 9
  ε               # Change each value to:
   9L             #  Create a list in the range [1, 9]
     N3*N3÷+      #  Calculate N*3 + N//3 (where N is the 0-indexed index,
                  #                        and // is integer-division)
            ._    #  Rotate that many times towards the left

```

Both answers result in the Sudoku:

```
123456789
456789123
789123456
234567891
567891234
891234567
345678912
678912345
912345678

```
> 4 votes

# Answer
# Java 10, ~~82~~ 75 bytes

```
v->{for(int i=81;i-->0;)System.out.print((i/9*10/3+i)%9+1+(i%9<1?" ":""));}

```

-7 bytes by creating a port of one of *@TFeld*'s Python 2 answers.

Try it online.

**Explanation:**

```
v->{                    // Method with empty unused parameter and no return-type
  for(int i=81;i-->0;)  //  Loop `i` in the range (81, 0]
    System.out.print(   //   Print:
     (i/9               //    (`i` integer-divided by 9,
         *10            //     then multiplied by 10,
         /3             //     then integer-divided by 3,
           +i)          //     and then we add `i`)
             %9         //    Then take modulo-9 on the sum of that above
               +1       //    And finally add 1
    +(i%9<1?            //    Then if `i` modulo-9 is 0:
            " "         //     Append a space delimiter
           :            //    Else:
            ""));}      //     Append nothing more

```

Outputs the following sudoku (space delimited instead of newlines like below):

```
876543219
543219876
219876543
765432198
432198765
198765432
654321987
321987654
987654321

```
> 4 votes

# Answer
# , 18 bytes

```
>:(,&|:|."{,)i.3 3

```

Try it online!

### Output

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

```

### How it works

```
>:(,&|:|."{,)i.3 3
             i.3 3  The 2D array X = [0 1 2;3 4 5;6 7 8]
   ,&|:|."{,        3-verb train:
   ,&|:               Transpose and flatten X to get Y = [0 3 6 1 4 7 2 5 8]
           ,          Flatten X to get Z = [0 1 2 3 4 5 6 7 8]
       |."{           Get 2D array whose rows are Z rotated Y times
>:                  Increment

```

## Fancy version, 23 bytes

```
|.&(>:i.3 3)&.>|:{;~i.3

```

Try it online!

Output:

```
┌─────┬─────┬─────┐
│1 2 3│4 5 6│7 8 9│
│4 5 6│7 8 9│1 2 3│
│7 8 9│1 2 3│4 5 6│
├─────┼─────┼─────┤
│2 3 1│5 6 4│8 9 7│
│5 6 4│8 9 7│2 3 1│
│8 9 7│2 3 1│5 6 4│
├─────┼─────┼─────┤
│3 1 2│6 4 5│9 7 8│
│6 4 5│9 7 8│3 1 2│
│9 7 8│3 1 2│6 4 5│
└─────┴─────┴─────┘

```

### How it works

```
|.&(>:i.3 3)&.>|:{;~i.3
                    i.3  Array [0 1 2]
                 {;~     Get 2D array of boxed pairs (0 0) to (2 2)
               |:        Transpose
|.&(>:i.3 3)&.>          Change each pair to a Sudoku box:
            &.>            Unbox
    >:i.3 3                2D array X = [1 2 3;4 5 6;7 8 9]
|.&                        Rotate this 2D array over both axes
                             e.g. 1 2|.X gives [6 4 5;9 7 8;3 1 2]
            &.>            Box again so the result looks like the above

```
> 4 votes

# Answer
# Octave & Matlab,50 48 29 bytes

```
mod((1:9)+['furRaghAt']',9)+1

```

Try it online!

*-2 thanks to Johnathon frech*

*-14 thanks to Sanchises Broadcast addition suggestion, who also pointed out the non-compatibility.*

*-5 by noticing that the vector can be written in matlab with a char string and transposition.*

Was intuitive, now not so. Uses broadcast summing to spread 1:9 over 9 rows, spread by values determined by the char string.

Sudoku board produced:

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

```
> 4 votes

# Answer
# Haskell, 41 bytes

```
[[x..9]++[1..x-1]|x<-[1,4,7,2,5,8,3,6,9]]

```

Try it online!
> 3 votes

# Answer
# Ruby, 34 bytes

```
(a=*1..9).map{|x|p a.rotate x*3.3}

```

Try it online!
> 3 votes

# Answer
# MathGolf, ~~16~~ 11 bytes

```
9{9╒♂ï*3/Ä╫

```

Try it online!

Saved 5 bytes thanks to JoKing
> 3 votes

# Answer
# Python - 81 bytes

```
l=list(range(1,10))
for i in range(1,10):print(l);l=l[3+(i%3==0):]+l[:3+(i%3==0)]

```

Try it Online

I like having 81 bytes, but after some optimizing :(

# Python 2 - ~~75 68 59~~ 58 bytes

*-7 bytes thanks to @DLosc*

*-9 bytes thanks to @Mnemonic*

*-1 byte thanks to @JoKing*

```
l=range(1,10)
for i in l:print l;j=i%3<1;l=l[3+j:]+l[:3+j]

```

Try it Online
> 2 votes

# Answer
Huge Thanks to @Shaggy!

# JavaScript (Node.js), 61 bytes

```
t=>[...s='123456789'].map(e=>s.slice(t=e*3.3%9)+s.slice(0,t))

```

Try it online!
> 2 votes

# Answer
**R****, 54 bytes**

```
x=1:9;for(y in(x*3)%%10)print(c(x[-(1:y)],x[(1:y)]))

```

**Output:**

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

```

Try it online!
> 2 votes

# Answer
# Python 3, 51 bytes

```
r='147258369';print([(r*4)[int(i):][:9]for i in r])

```
> 2 votes

# Answer
# Python 2, 48 bytes

```
r='147258369'
for i in r:print(r*4)[int(i):][:9]

```

Try it online!
> 2 votes

# Answer
# Canvas, ~~13~~ 11 bytes

```
◂ｊ３［«３［Ｔ３［«

```

Try it here!
> 1 votes

# Answer
# Charcoal, 14 bytes

```
Ｅ⁹⭆⁹⊕﹪⁺÷×χι³λ⁹

```

Try it online! Link is to verbose version of code. Uses @Mnemonic's output. Explanation:

```
Ｅ⁹              Map over 9 rows
  ⭆⁹            Map over 9 columns and join
          ι     Current row
         χ      Predefined variable 10
        ×       Multiply
       ÷   ³    Integer divide by 3
            λ   Current column
      ⁺         Add
     ﹪       ⁹  Modulo 9
    ⊕           Increment
                Implicitly print each row on its own line

```
> 1 votes

# Answer
# Japt, ~~11~~ 10 bytes

```
9õ ñu3
£éX

```

Try it or verify the output

---

## Explanation

```
9õ         :Range [1,9]
   ñ       :Sort by
    u3     :  Mod 3 of each
\n         :Assign to variable U
£          :Map each X
 éX        :  U rotated right by X

```
> 1 votes

# Answer
# C (clang), 65 bytes

```
f(i){for(i=0;i<81;)printf("%d%c",(i/9*10/3+i)%9+1,i++%9>7?10:9);}

```

The function is now able to be reused

Try it online!
> 1 votes

# Answer
# K (ngn/k), 16 bytes

```
1+9!(<9#!3)+\:!9

```

Try it online!

First answer in ngn/k, done with a big help from the man himself, @ngn.

### How:

```
1+9!(<9#!3)+\:!9 // Anonymous fn
              !9 // Range [0..8]
    (     )+\:   // Sum (+) that range with each left (\:) argument
        !3       // Range [0..2]
      9#         // Reshaped (#) to 9 elements: (0 1 2 0 1 2 0 1 2)
     <           // Grade up
  9!             // Modulo 9
1+               // plus 1

```
> 1 votes

# Answer
# Husk, 8 bytes

```
ṠmṙÖ%3ḣ9

```

Try it online!
> 0 votes

# Answer
# Deadfish~, 344 bytes

```
{iiiii}icicicicicicic{d}iicic{dddd}c{iiii}iiiicicicic{d}iicicicicic{dddd}dddc{iiiii}dddc{d}iicicicicicicicic{dddd}ddddddc{iiii}cicicicicicicic{d}iic{dddd}ic{iiii}iiicicicicic{d}iicicicic{dddd}ddc{iiii}iiiiiicic{d}iicicicicicicic{dddd}dddddc{iiii}dcicicicicicicicic{ddddd}iiic{iiii}iicicicicicic{d}iicicic{dddd}dc{iiii}iiiiicicic{d}iicicicicicic

```

Try it online!
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, grid, sudoku
---


title: 2 Cats in a Quine

text:
# Question
Title: 2 Cats in a Quine
# Challenge

Make two programs, A and B, which are both cat programs in the same language. When concatenated, AB (also in the same language) should be a quine.

For example, suppose `hello` and `world` are both cat programs in language XYZ. If `helloworld` is a quine in said language, then your solution is valid.

For those of you unfamiliar with cats and quines, a cat program is one that prints exactly what was given to it via stdin and a quine is a program that prints its own source code.

# Scoring and Rules

* The total byte count of the concatenated AB program is your score. As this is code golf, the lowest score wins.
* Standard loopholes are forbidden
* Input must be taken from stdin and output must go to stdout.
* The cat programs do not need to take arguments; they only need to copy stdin to stdout.
* The quine should work when the program is given no input, but does not have to work correctly (but may) for other inputs.
* The quine does not need to terminate, provided it prints exactly its source code once, nothing more.
* The quine needs to be at least one byte long.
* A and B can be the same program.
* BA does not need to be a quine or even a valid program.

# Answer
# , 2 + 2 == 4 bytes

```
2i2i

```

Try the quine!

Try the cat!

**A** is `2i`

**B** is also `2i`

## How does it work?

First off, some explanations of how V works. One notable thing that makes this answer possible is that in V, the empty program *is* a cat program. This isn't a special case, it's inherent to how V operates. On startup, all input is loaded into a "buffer", each command modifies the buffer in someway, and then when the program is done, the buffer is implicitly printed. This means that any string of NOPs is also a cat program.

The `i` command means *enter insert mode*, which means every character following an `i` will be added into the buffer. With a number preceding it, that text will be duplicated **n** times.

This means that for the cat program, nothing will be added to the buffer, and it will be printed as it was read. In other words:

```
        " (Implicitly) Load all input
2       " 2 times,
 i      " Insert the following text into the buffer...
        " (nothing)
        " (Implicitly) Print the buffer

```

But for the quine, there is text after the `i`:

```
2       " 2 times,
 i      " Insert the following text into the buffer...
  2i    "   "2i"
        " (Implicitly) Print the buffer

```

## Cheeky non-answer

# , 0 bytes

Try it online!

**A** is the empty program.

**B** is also the empty program.

:P
> 37 votes

# Answer
# Ruby, 71 bytes

```
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2

```

Can be broken up into cats as follows:

```
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2

```

and

```
;puts (<<2*2+?2)[/.+2/m]||$<.read
2

```

The two cats are identical except for the leading 2, which is a no-op in all three programs. The `<<2` is a herestring, meaning that everything starting on the next line until a terminating 2 on its own line is a string, which we concatenate to itself (`*2`) and append a trailing 2. In the cats the herestring is well-formed but empty, so the regular expression won't match it and we'll fall through to the `$<.read` expression and output STDOUT. Once we concat the cats, though, the string won't terminate until the third line, so the regex matches and we short-circuit and output the quine.
> 13 votes

# Answer
# C# (Visual C# Compiler), 551 bytes

### A: 95 bytes

```
class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//

```

Try it online!

### B: 438 + 18 bytes

```
class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}

```

Try it online!

### A+B: 533 + 18 bytes

```
class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}

```

Try it online!

A and B take input as a command-line argument. A+B ignores any input. 18 bytes on B and A+B are added for the `/p:StartupObject=B` option sent to MSBuild. It's only strictly necessary on A+B, but it seemed like cheating to not also have it in B. This way, the compiler flags for A+B are the compiler flags for A (none) plus the compiler flags for B.

**Explanation**

Program A is straightforward. Class A contains an (unused) static variable `i` initialized to `2`, and prints its first argument when run. The `//` at the end is important for the A+B code, but does nothing in A itself.

Program B is weird in isolation, but essentially the same. It creates a Class A containing a static variable `i` initialized to `0`, and then runs the Main method of Class B, which does the same as Program A because `A.i` is less than 1, and returns before any of the weird stuff. The newlines aren't necessary here, but are important for A+B.

When combined, the `//` from Program A comments out the Class A declaration from Program B, but because of the newline Class B is fine, allowing `A.i` to refer to the `2` value from Program A instead. The Compiler Flag makes the Program run B.Main() since A.Main() also exists. The result is that Program A+B does not output its argument, but instead goes to the following segment of B.Main(), which is basically just the standard C# quine.
> 13 votes

# Answer
# Pyth, ~~29 bytes (5 + 24)~~ 27 bytes (5 + 22)

```
pz=T0?TzjN*2]"pz=T0?TzjN*2]     # Quine
pz=T0                           # Cat A
     ?TzjN*2]"pz=T0?TzjN*2]     # Cat B

```

That was fun.
Try the quine here
Try the first cat here
Try the second cat here

### Explanations

```
Cat A
pz=T0
pz       Print the input.
  =T0    (Irrelevant for cat)

Cat B
?TzjN*2]"pz=T0?TzjN*2]
?Tz                      If T (10) is truthy, output the input.
   jN*2]"pz=T0?TzjN*2]   (Irrelevant for cat)

Quine
pz=T0?TzjN*2]"pz=T0?TzjN*2]
pz                            Print the (empty) input (without a newline).
  =T0                         Set T to 0.
     ?Tz                      If T (0) is truthy, output the input.
             "pz=T0?TzjN*2]   Otherwise, get this string...
          *2]                 ... take two copies...
        jN                    ... and join them with a quote.

```
> 11 votes

# Answer
# Haskell, 116 + 20 = ~~187~~ ~~175~~ ~~174~~ 136 bytes

*A bunch of bytes saved since Ørjan Johansen showed me `interact`*

## Cat 1

```
g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact id

```

Try it online!

## Cat 2

```
main|1>0=interact id

```

Try it online!

## Quine

```
g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact idmain|1>0=interact id

```

Try it online!

---

The basic principle at work here is that when we add the second cat to the first we change the name of the function we are interacting with from `a` to `idmain`. Since `interact id` is a cat we want `idmain` to me a function that returns a quine. The obvious solution would be to use `const`, however since we can assume the input is empty `(++)` works as well. From here we find the source code via pretty standard means, we have a variable `g` that encodes the source and we use a special wrapper to print it in string form and code form. There is a slight exception that we need to put our encoder at the front because we already need to end with `interact id`. This means an extra `g=` is not encoded and has to be handled manually. Our next cat is pretty standard except we need to make it valid code when tacked on to the end of the other cat so we need both cats to be instances of pattern guards.

# Alternative Strategy, 43 + 105 = ~~186~~ 148

## Cat 1

```
g="";main|idmain<-(++g++show g)=interact id

```

Try it online!

## Cat 2

```
main|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="

```

Try it online!

## Quine

```
g="";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="

```

Try it online!
> 9 votes

# Answer
# Python 3, 286 bytes

My first Python golf and my first quine! Not very elegant, but it works.

## Program A (238 bytes)

```
from atexit import*;s="from atexit import*;s=%r;register(lambda:print(end='b'in globals()and s%%s or open(0).read()));b=0\nif's'not in vars():print(end=open(0).read())";register(lambda:print(end='b'in globals()and s%s or open(0).read()));

```

(no trailing newline)

## Program B (48 bytes)

```
b=0
if's'not in vars():print(end=open(0).read())

```

(no trailing newline)

## Try It Online

## Acknowledgments

* -24 bytes thanks to Jo King
* -82 bytes thanks to Jo King
> 8 votes

# Answer
# Python 3, ~~137~~ 78 + 37 = 115 bytes

*-22 bytes thanks to Jakque!*

Program A:

```
s='s=%r;exec(s[20:45])#print(end=open(0).read())\nprint(s%%s)';exec(s[20:45])#

```

Try it online!

And program B:

```
print(end=open(0).read())
print(s%s)

```

Try it online!

Make Quine AB!

```
s='s=%r;exec(s[20:45])#print(end=open(0).read())\nprint(s%%s)';exec(s[20:45])#print(end=open(0).read())
print(s%s)

```

Try it online!

Only works when input is empty, otherwise it prepends the input to the output.
> 7 votes

# Answer
# C++ (clang), 313 + 102 = 415 bytes

Program A (ends in a newline):

```
#include<cstdio>
#define Q(x,y)#x,B=#y;x
int c;auto I="#include<cstdio>",A=Q(int main(){if(c)printf("%s\n#define Q(x,y)#x\",\"#y;x\nint c;auto I=\"%s\",A=Q(%s,)\n#ifdef Q\nint n=++c;\n#else\n%s\n%s\n#endif",I,I,A,I,B);else while((c=getchar())>=0)putchar(c);},int c;int main(){while((c=getchar())>=0)putchar(c);})

```

Program B (does not end in newline):

```
#ifdef Q
int n=++c;
#else
#include<cstdio>
int c;int main(){while((c=getchar())>=0)putchar(c);}
#endif

```

Not terribly sneaky, and as usual C++ isn't that great for quining. I won't be surprised if there are ways to shave bytes here and there off the same idea. The one little catch is changing the behavior of something after it's been defined, and a dynamic variable initializer with side effect does the trick. (Can this even be done in C without compiler extensions?)

Try it online: , , AB

(The only portability concern I'm aware of is that the program assumes `<cstdio>` puts names both in the global namespace and in `std`.)
> 6 votes

# Answer
# Befunge-98 (FBBI), 8 + 15 = 23 bytes

**A + B:** (only works for no input)

```
+9*5~,#@#@~,9j>:#,_:@#"

```

Try it online!

**A:**

```
+9*5~,#@

```

Try it online!

**B:**

```
#@~,9j>:#,_:@#"

```

Try it online!
> 5 votes

# Answer
# Stax, 16 + 12 = 28 bytes

Cat 1:

```
"yi|d|ca34b4lr"y

```

Run and debug it

```
"yi|d|ca34b4lr"y Full program, implicit input
"yi|d|ca34b4lr"  Push the string
               y Push raw input
                 Implicit output of top item

```

Cat 2:

```
i|d|ca34b4lr

```

Run and debug it

```
i|d|ca34b4lr Full program, implicit input
i            Don't parse input (prefix directive)
 |d          Push main stack depth, always zero
   |c        Cancel because top item is falsy, and implicitly print
     a34b4lr Never executed

```

Quine:

```
"yi|d|ca34b4lr"yi|d|ca34b4lr

```

Run and debug it

```
"yi|d|ca34b4lr"yi|d|ca34b4lr Full program
"yi|d|ca34b4lr"              Push the string
               y             Push input
                i            No-op
                 |d          Push main stack depth, i.e. 2
                   |c        Do nothing because top is truthy
                     a       Get the string to the top
                      34     Push 34 (charcode of ")
                        b    Copy both
                         4l  Listify top 4
                           r Reverse
                             Implicit output

```
> 4 votes

# Answer
# Attache, 15 + 126 = 141 bytes

**A:**

```
AllInput[]|Echo

```

Try it online!

**B:**

```
@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call

```

Try it online!

**A + B:**

```
AllInput[]|Echo@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call

```

Try it online!

## Explanation

Each of the cat program encodes `AllInput[]|Echo`, which is a simple cat program. **B** is the main quine phase; alone, it is a vectorized function (through unary `@`) called with no inputs (being called as `|Call`). Thus, the first conditional `If[_,A,B]` executes `B`, which is simply `AllInput[]|Echo`.

When **A + B** is executed, unary `@` becomes binary `@` due to `Echo` merging with the lambda:

```
AllInput[]|Echo@{If[_, ...

```

Now, this means that the lambda is executed before `Echo` is. Back to the conditional, this function now has all of STDIN as an argument. So, `If[_,A,B]` executes `A`, which is the standard quine framework.
> 4 votes

# Answer
# Cat 1 :

# Lua, 41 bytes

```
a=io.read;while a(0)do io.write(a(1))end;

```

Try it online!

---

# Cat 2 :

# Lua, 70 bytes

```
if a then io.input(arg[0])end;a=io.read;while a(0)do io.write(a(1))end

```

Try it online!

---

# Quine :

# Lua, 111 bytes

```
a=io.read;while a(0)do io.write(a(1))end
if a then io.input(arg[0])end;a=io.read;while a(0)do io.write(a(1))end

```

Try it online!

`io.input(arg[0])` in Cat 2 sets the current file as standard input, and as a result, the cat prints the source code
> 3 votes

# Answer
# \>\<\>, 12 +3 = 15 bytes

Program A:

```
<oi

```

Try it online!

And Program B:

```
>i!o|o<}*d3'

```

Try it online!

Make Program AB:

```
<oi>i!o|o<}*d3'

```

Try it online!
> 2 votes

# Answer
# Python 3.8 (pre-release), 26 + 71 = 97 bytes

## Cat 1 (26 bytes):

```

id=print(open(0).read());

```

Try it online!

## Cat 2 (71 bytes):

```
exec(s:='id=print(open(0).read()if id else s[:23]+");exec(s:=%r)"%s)')

```

Try it online!

## Quine = Cat 1 + Cat 2 (97 bytes):

```

id=print(open(0).read());exec(s:='id=print(open(0).read()if id else s[:23]+");exec(s:=%r)"%s)')

```

Try it online!

## How it works:

Cat 1:

* `open(0).read` reads the STDIN
* `id=print(...)` prints it and returns `None` which will be stored into `id` (remember it for later)

Cat 2:

* `<instructions for cat> if id else <other instuctions>` will execute `<instructions for cat>` because `id` is a built-in and is evaluated as `True`.

Quine:

* Because of Cat 1, id is now equal to `None` and `<instructions for cat> if id else <other instuctions>` will now execute `<other instructions>`
* Because both our program have the same structure for cat, we print the cat part of Cat 2 for quining cat1 : `s[:23]+");`
* Then the programm is just a variant of `exec(s:='print("exec(s:=%r)"%s)')`, a quine in Pyhton 3.8+

## Notes:

Both my cat programs add a trailing new line at the end. I assume that it was accepted since it wasn't frormally banned and since most of the cat challenges accept it.

Otherwise I have a 103 bytes solution which doesn't add trailing newlines:

```
id=print(end=open(0).read());                                                                           #Cat1
                             exec(s:='id=print(end=open(0).read()if id else s[:27]+");exec(s:=%r)"%s)') #Cat2
id=print(end=open(0).read());exec(s:='id=print(end=open(0).read()if id else s[:27]+");exec(s:=%r)"%s)') #Quine

```

Try it online!

### Bonus:

Here is a solution in 116 bytes which accepts not-empty input for the quine program:

```
while 1:id or print(input());id=0;                                                                                #Cat1
                                  exec(s:='id or~input(s[36:]+"exec(s:=%r)"%s)\nwhile 1:id or print(input());id=0;') #Cat2
while 1:id or print(input());id=0;exec(s:='id or~input(s[36:]+"exec(s:=%r)"%s)\nwhile 1:id or print(input());id=0;') #Quine

```

Try it online!
> 2 votes

# Answer
# Klein 0XX, 6 + 7 = 13 bytes

*Works in 000, 001, 010 and 011.*

*Note that these answers all contain the unprintible byte 17, or "device control 1".*

## Cat 1

```
<:2*@

```

Try it online!

The `<` redirects the pointer off the left. It appears on the right at `@` and halts immediately spilling its input as output.

## Cat 2

```
@*2:<"

```

Try it online!

It immediately encounters `@` and halts with no further execution. It outputs the input with no changes.

## Quine

```
<:2*@@*2:<"

```

Try it online!

Like **cat 1** this first encounters `<` which sends it off the left and onto the right. But this time on the right we encounter `"` which puts us into string mode. This causes us to push the entire program (minus the quote) to the stack *backwards*. In order to make things easier for myself this part of the program is a palindrome, so we don't have to reverse it. Now we just need to add the `"` at the end. The program begins with a , which is chosen because multiplying it by 2 gives us `"`. So we duplicate and multiply by two to make the `"` and exit at `@`.
> 1 votes

# Answer
# Vyxal `ajṠ`, 13 + 1 = 14 bytes

**A:** (Try it Online!)

```
`:qpw$$`:qpw$

```

**B:** (Try it Online!)

```
$

```

**A + B:** (Try it Online!)

```
`:qpw$$`:qpw$$

```

## Explained

```
`:qpw$$`:qp      # Modified standard Vyxal quine
           w     # Wrap quine in array, so join on newline works
            $    # Swap the quine and the input

$                # Swap
                 #   If the program is standalone, this does nothing
                 #   If concatenated, this undoes the previous swap and puts the quine at the top

```
* `a`: Push entire input split on newlines to the top of the stack
* `j`: Join top of stack on newlines and output (undo split from `a`)
* : Treat all inputs as strings, so proper output is given for inputs like `[]` and `""`
> 1 votes

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

```

a=()=>console.log(require('fs').readFileSync(0)+'');a();var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()

```

Try it online!

## Cat A, 57 bytes

```

a=()=>console.log(require('fs').readFileSync(0)+'');a();

```

Try it online!

## Cat B, 142 bytes

```
var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()

```

Try it online!
> 0 votes

---
Tags: code-golf, quine, source-layout
---


title: Simplify K combinatory logic expression

text:
# Question
Title: Simplify K combinatory logic expression
## Background

Combinatory logic is a system where a term is written using a finite set of combinators and function application between terms, and reduction rules are defined for each combinator. The well-known S and K combinators have the following reduction rules:

$$ \begin{aligned} S\\;x\\;y\\;z & \overset{S}{\implies} x\\;z\\;(y\\;z) \\ K\\;x\\;y & \overset{K}{\implies} x \end{aligned} $$

A term is in *normal form* when no reduction is possible. A term has a normal form if a series of reductions applied to it gives a normal form. The halting problem in combinatory logic is essentially about determining whether a term has a normal form.

In a previous challenge of mine, I mentioned that the halting problem for K is trivial; it always terminates, and we can always find the normal form of a K expression.

## Challenge

Given a K combinatory logic expression, simplify it into its normal form. For this challenge, the expression is to be input/output as a string (list of chars or charcodes is also acceptable), using prefix notation:

```
expr := "K" | "@" expr expr

```

So the expression \\$K(KK)(KK)K\\$ is given as `@@@K@KK@KKK`. The reduction rule can be also rewritten as

```
@@Kab => a

```

where `a` and `b` are valid expressions. The input is guaranteed to be a valid expression as a whole. You may use `k` instead of `K`, and any non-`kK` non-space printable ASCII character instead of `@`.

Standard rules apply. The shortest code in bytes wins.

## Test cases

Generated using this Python script.

```
K -> K
@KK -> @KK
@K@KK -> @K@KK
@@KK@KK -> K
@@@@KK@KKKK -> K
@K@@@KKK@K@KK -> @K@K@K@KK
@@@KKK@@@KKK@@KKK -> @K@KK
@@@@@@@KK@KKK@@KK@@KK@KK@@@@KKK@@KKK@@K@KK@KKK@@@@K@@KK@KK@K@KK@@@KKK@K@K@KK@@@K@KK@K@K@KK@@@KK@@KK@KK@@KKK -> @K@K@K@K@KK

```

# Answer
# Perl 5 `-p`, ~~28~~ 27 bytes

```
s/@(.K)(\1*K)\1*K/$2/&&redo

```

Try it online!

### How it works

Each term in the \\$K\\$ calculus normalizes to \\$a\_i = (\texttt{@K})^i\texttt K\\$ for some \\$i \ge 0\\$, because \\$\texttt K = a\_0\\$, \\$\texttt @a\_0a\_j = a\_{j + 1}\\$, and \\$\texttt @a\_{i + 1}a\_j \to a\_i\\$. So the innermost redex always looks like \\$\texttt @(\texttt{@K})^{i + 1}\texttt K(\texttt{@K})^j\texttt K\\$ for some \\$i, j \ge 0\\$, and reduces to \\$(\texttt{@K})^i\texttt K\\$.

To avoid the need to escape `@K` (which would otherwise refer to an array) as `\@K`, we relax it to `.K`, using backreferences for further copies. This doesn’t introduce bugs because any invalid redex \\$\texttt @(\texttt{KK})^{i + 1}\texttt K(\texttt{KK})^j\texttt K\\$ must be preceded by a valid redex \\$\texttt @(\texttt{@K})^{i + 1}\texttt K(\texttt{@K})^j\texttt K\\$.
> 9 votes

# Answer
# Haskell, 137 bytes

```
p('K':x)=(K,x)
p(_:x)|(s,z)<-p x,(u,v)<-p z=(s:@u,v)
data M=K|M:@M
f(x:@y)|K<-x="@K"++f y|K:@z<-x=f z|(u,_)<-p$f x=f$u:@y
f K="K"
f.fst.p

```

Try it online!

This one actually parses the strings into a tree. I'm sure this is not the most efficient way to do this but I actually couldn't beat it. `p` is our parser, and `f` performs the actual function.
> 4 votes

# Answer
# JavaScript (ES2019), 70 bytes

```
s=>(i=0,T=(p=s[i++],N=p<s?[p,p=T(),T()]:[p])=>p[1]>s?p[2]:N)().flat(i)

```

Try it online!

This one try to parse the string into a tree, and then convert back.

```
s=> // Input String
(i=0, // cursor for reading the string
T=( // We try to parse the string into a prefix expression tree
    // Tree structure would be `<exp> ::= ["K"] | ["@", <exp>, <exp>]`
p=s[i++], // get character under cursor, and move cursor to next character
N= // Node for expression tree
  p<s? // s would be a single "K" or start with "@"
       // In either cases, `p<s` indicate `p` is "@"
  [p, // Expression node, "@" character
   p=T(), // We reuse `p` variable to storage left child of current node
   T() // And right child here
  ]:
  [p] // `["K"]` as leaf node
)=>
  p[1] // If current character is "K", then p === "K", p[1] would be (void 0)
       // If current character is "@", then p is left child
       //    If left child is leaf node ["K"], p[1] is (void 0)
       //    If left child is non-leaf node ["@", <exp>, <exp>], p[1] is its left child
  >s? // p[1]>s whenever p[1] is "K" since s would start with "@"
      // For the special case s === "K", p[1] is (void 0) and compare would always be false
  p[2]: // Current node is ["@", ["@", "K", <exp = p[2]>], <exp>]
        // We keep p[2] and drop the right child expression
  N // Otherwise, we keep current expression as is
)().flat( // We flat the expression so we got an array of characters
          // which would be acceptable for string I/O
i) // `i` would equals to length of original string
   // And the expression nested level would always less than `i`
   // So we use `i` here to flatten the array

```

---

# JavaScript (ES6), 51 bytes

```
f=s=>s<(s=s.replace(/@(@K)(\1*K)\1*K/,'$2'))?f(s):s

```

Try it online!

The regex used in this Perl answer.
> 3 votes

# Answer
# Retina 0.8.2, 43 bytes

```
+`@@K(((@)|(?<-3>K))*(?(3)$)K){2}(?<-1>)
$1

```

Try it online! Link includes test cases. Explanation: The `+` simply repeats until the entire expression is normalised. The `@@K` represents a potential normalisation, but we still need to find `a` and `b`. The next portion of the regex achieves this by counting `@`s and `K`s, stopping only after an equal number followed by a `K`. This is matched twice, but the second match `b` is then is dropped using `(?<-1>)`, allowing the first match `a` to be used as the substitution.

Of course this is all blown out of the water when you consider @AndersKaesorg's observation that all you have to do is to normalise depth first for 20 bytes:

```
+`@(@K)(\1*K)\1*K
$2

```

Try it online! Link includes test cases.
> 3 votes

# Answer
# Python 3, 82 bytes

```
import re
def f(e,n=1):
 while n:e,n=re.subn(r'@(@K)(\1*K)\1*K',r'\2',e)
 return e

```

Try it online!

Obligatory translation of Anders Kaseorg's excellent Perl solution. I will admit to not being sure this works.

Without regex:

# Python 3, ~~125~~ ~~122~~ ~~97~~ ~~96~~ ~~94~~ 89 bytes

```
def f(e,*s):
 for x in e[::-1]:s=[x,*s]*(x>'@')or[s[0][2:]or'@K'+s[1]]+s[2:]
 return s[0]

```

Try it online!

*-3 bytes because naming `o` was entirely pointless*

*-23 bytes thanks to tsh, and then I also shaved another 2 off since not needing list mutability opens the door to some splat abuse*

*-1 byte because it's not like `s` has to not be a list either*

*-2 bytes thanks to ovs replacing the ternary with another `or`*

*-5 porting Wheat Wizard's second golf to my Haskell solution*

(Note: there are old explanations in the edit history)

```
def f(e   ):             # Define a function f taking an argument e
       ,*s               # and collecting any extra arguments into a tuple s.
                         # (There are no extra arguments, so s is empty.)
 for x in e[::-1]:       # For each element x of e, in reverse order:
  s=[    ]*(x>'@')       # if x is 'K', set s to a list
     x,*s                # containing x followed by the elements of s,
  s=              or     # else set s to:
   [ ... ]+s[2:]         # s without its first two elements, appended to:
                         # (note: this would error if s was not a list,
                         # but a valid input must end in K)
    s[0]                 # the first element of s
        [2:]             # without its first two characters
            or           # unless that's empty, otherwise
              '@K'+s[1]  # the second element of s appended to 'K@'.
 return s[0]             # Return the sole remaining element of s.

```

I'd attempted to remove the final reversal before, but it came out longer because I tried using `insert` instead of removing `pop`.

Since Python 2 doesn't require you to import `reduce` (why would they change that? :/ also thanks again to tsh), porting to it saves two more bytes:

# Python 2, ~~93~~ ~~92~~ 86 bytes

```
lambda e:reduce(lambda s,x:([x]+s)*(x>'@')or[s[0][2:]or'@K'+s[1]]+s[2:],e[::-1],[])[0]

```

Try it online!

*-1 porting ovs's golf*

*-5 porting Wheat Wizard's second golf to my Haskell solution*
> 2 votes

# Answer
# Python 3, 190 bytes

```
lambda x:h(c(g(x)))
g=lambda x:x.pop(0)>"@"and"K"or[g(x),g(x)]
c=lambda x:x=="K"and"K"or(lambda x:x[0][0]=="K"!=x[0]and x[0][1]or x)([*map(c,x)])
h=lambda x:x=="K"and x or"@"+h(x[0])+h(x[1])

```

Try it online!

Horribly long answer. But, it's the most direct way I could think of at first.

And a horribly scuffed one-liner using weird something-combinators just because this challenge is about combinators:

# Python 3, 227 bytes

```
lambda x:(lambda h,c,g:h(h,c(c,g(g,x))))(lambda f,x:x=="K"and"K"or"@"+f(f,x[0])+f(f,x[1]),lambda f,x:x=="K"and"K"or(lambda x:x[0][0]=="K"!=x[0]and x[0][1]or x)([f(f,y)for y in x]),lambda f,x:x.pop(0)>"@"and"K"or[f(f,x),f(f,x)])

```

Try it online!
> 1 votes

# Answer
# Jelly, ~~22~~ 21 bytes

```
Ṫṫ3ȯṪ⁾0K;Ɗṭ
ṚṭÇ}V?@/Ṛ

```

Try it online!

A full program that takes a single argument consisting of `K`s and `0`s and prints the output to STDOUT using the same symbols.

Based on @UnrelatedString’s Python answer so be sure to upvote that one too!

Thanks also to @UnrelatedString for saving a byte!

## Explanation

### Helper link

Takes the current draft output list and processes it where there was a zero in the next position

```
Ṫ            | Tail (pop last element from list)
 ṫ3          | Third character onwards
   ȯ     Ɗ   | Or the following as a monad:
    Ṫ        | - Tail (pop last element from list)
     ⁾0K;    | - Concatenate "0K" to this
          ṭ | Tag onto end of draft output list (this will have lost its last two members via the action of Ṫ twice)

```

### Main link

```
Ṛ         | Reverse
      @/  | Reduce using the following, swapping left and right arguments:
    V?    | - If the next value in the reversed list evaluates to non-zero (i.e. is a K)
 ṭ        | - Then wrap it in a list and add to the end of the draft output list
   Ç      |   - Otherwise call helper link on draft output list
        Ṛ | Finally reverse, and implicitly smash together and print

```
> 1 votes

# Answer
# Haskell, ~~68~~ 64 bytes

```
head.foldr(#)[]
'K'#s="K":s
a#(t:n:s)|_:_:v<-t=v:s|u<-a:t++n=u:s

```

Try it online!

*-4 thanks to Wheat Wizard actually using the destructured arguments and realizing that the input only consists of one expression (so at the end there should only be one on the stack)*

Another translation of my Python answer.

```
    .            -- The relevant function is the composition of
     foldr(#)    -- right-associative folding #
             []  -- starting from an empty list
head             -- and taking the first element from the result.

'K'#s=           -- If the item encountered is the character 'K', # yields
      "K":s      -- the string "K" prepended to the accumulator.
a#               -- If it's something else (that is, '@', which we bind to a),
  (t:n: )        -- let t and n be the first two elements of the accumulator
       s         -- and s the remaining elements;
  |_:_:v<-t      -- if t has at least two elements to ignore let v be the rest
           =v:s  -- and yield v prepended to s,
  |u<-           -- else t must be "K", let u be
      a:t        -- "@K"
         ++n     -- concatenated with n
            =u:s -- and yield u prepended to s.

```
> 1 votes

---
Tags: code-golf, string, functional-programming, combinatory-logic
---


title: ASCII Art Mayan Numerals

text:
# Question
Title: ASCII Art Mayan Numerals
This challenge is simple. Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.

### What is the Mayan system?

The Mayans used base 20 to store numbers, so the first position was the `1`s place, the next the `20`s place, then the `400`s, etc.

So Mayan number `1` is `1` in base 10, but `10` is actually `20` in base 10, `207` is `807` in base 10, etc..

And they represented their numbers as pictographs, with a special symbol for `0`.

```
 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

```

That was their zero. (at least the half picascii half my artisticness ascii art version)

That is a ~~real~~ picture of the mayan zero symbol.1

This was their five:

```
--------------------------------
|                              |
--------------------------------

```

And a 4:

```
 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

```

Finally, to put it together:

```
 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

```

So they have `x//5` bars, and `x%5` dots on top of the bars. And if `x=0`, they use the shell/loaf instead of a blank space.

For more images, try the Wikimedia Commons page of Maya number images.

But this is only for numbers up to `19`. We aren't allowed to have more than `4` bars and `4` dots *in a single 'story'*... So we go up!

The output for 20 is:

```
 ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

```

Note this would normally be invalid, because is has a `1` and a `0` at the same time. But the `3` (note that, your answer needs at least 3) newlines before the `0` mean a new place value.

The bottom story has dots, meaning `1`, and bars meaning `5`. But it actually has dots meaning `20^0` and bars meaning `20^0 * 5`.

Each story goes up a power. The second story dots mean `20` (`20^1`) and `100` (`20^1 * 5`).

So the number `506` can be represented as:

```
 ----
|    |
|    |
 ----

--------------------------------
|                              |
--------------------------------

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------

```

This is `(20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506`.

Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.

### Other Rules:

* Leading/trailing space is okay, as long as the dots, bars, and shells are intact.
* The bars, dots, and shells must be *exactly* what the test cases have. No resizing.
* Leading '0's are okay. (leading shells on the output)
* You don't have to have exactly 3 newlines between each place value or story, just at least 3.

### Test Cases:

```
15

--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

12

 ----   ----
|    | |    |
|    | |    |
 ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

4

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

0

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

24

 ----
|    |
|    |
 ----

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

33

 ----
|    |
|    |
 ----

 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

20

 ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

```

1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/zelda chest will be used.

# Answer
> 4 votes
# Ruby, ~~223~~ ~~180~~ ~~177~~ 179 bytes

Anonymous function, returns a multiline string.

Forgot to add some extra spacing that was needed, and also the recursion. Also golfed a bit more by shifting things around.

```
f=->n{s=?|;e=' ';n<20?(n<1?[t=e+d=?-*19,a=s+(e*4+s)*4,a,s+d+s,b=s+e*19+s,b,t]:((r=n%5)>0?[t=" ----  "*r,m="|    | "*r,m,t]:[])+[a=?-*32,s+e*30+s,a]*(n/5))*$/:f[n/20]+$/*5+f[n%20]}

```

# Answer
> 6 votes
# Python 3.5, 404 400 392 312 311 308 290 281 285 281 bytes:

(*Thanks to Adnan for a tip on saving 9 bytes(`290->281`) and Neil for a tip on saving 4 bytes(`285->281`)!*)

```
def u(z):
 p=[];P=print;S,N,M,X=' -|\n'
 while not p or z:p+=[z%20];z=z//20
 E=lambda i:(S+N*4+S)*i+X+((M+S*4+M)*i+X)*2+(S+N*4+S)*i+X;F=N*32+X+M+S*30+M+X+N*32+X;[P(S+N*19+S+X+M+((S*4+M)*4+X+M)*2+N*19+M+X+(M+S*19+M+X)*2+S+N*19+S+X*3)if y<1else P(E(y%5)+F*(y//5)+X*3)for y in p[::-1]]

```

Try it online! (Ideone)

# Analysis

For the purposes of this analysis, we will use the character set `0123456789ABCDEFGHIJ` to represent each digit in base 20.

So, I could have gone and converted base 10 into base 20 using one of two algorithms I have. The first algorithm I thought of using is what I call the **powers algorithm**. This is not the one that I used in the code though as it would have made it way longer than it should have been, so I'm not going to talk about this one. However, I did create a python script that converts any integer in base 10 into any other base provided using this method, which you can use here on repl.it. The one I used instead for this challenge is what I call the **division algorithm**, which I think is explained pretty good here. But basically what happens is that it takes the base 10 number provided and divides it by the base it needs to convert the number to, which in this case is 20, until the remainder is either 0 or 1. It then takes the quotiant and remainder, in that order, from the *last* division operation, and then all the other remainders from the other division operations in the order from last to first. All these digits are then joined together, and that joined sequence *reversed* is your base 10 number in base 20! To illustrate this, assume you want to convert the base 10 number `431` to base 20. So, what we would do is this:

```
[]=list we will put all remainders and the last quotient in
R = Remainder

1. 431/20 = 21 R11 [B (B=11 in base 20)]
2. 21/20 = 1 R1 [Add the remainder and quotient: B11]

```

Then, finally we would take the list we have, which in this case contains `B11`, and *reverse* it so that we now have `11B`. In doing this, we have finally got our final answer! 431 in base 10 converted to base 20 is `11B`, which can be confirmed using my Python script that uses the powers algorithm which I already shared a link to above, but I will do it again here. Here is one that also uses the division algorithm described in this answer and returns the same answer as the powers one.

This entire process is essentially what happens in my script in this `while` loop: `while not p or z:p+=[z%20];z=z//20`. The only difference is that numbers `>9` are *not* represented as letters but instead as themselves.

Moving on, after the base 10 number has been converted to base 20, for each digit in the base 20 integer, which we will call `g`, `g mod 5` dots are printed out and then `g//5` bars are printed out. Then the program prints 3 blank lines and moves on to the next digit. However, if the digit is `0`, then a single "loaf" is printed out followed by 3 new lines, and then the program moves onto the next digit. So, taking the base 20 number `11B`, we go to the first digit. The first digit is `1`, and therefore it would print 0 bars since `1//5=0`, and 1 dot since `1%5=1`. So, we would first get this:

```
 ----
|    |
|    |
 ----

```

and then 3 new lines. Moving onto the the second digit, we also see that it is 1, so it would output the same thing:

```
 ----
|    |
|    |
 ----

```

and also 3 new lines. Finally, moving onto the last digit, we see that it's a `B`. Since `B=11` in base 20, the program would output 1 dot since `11%5=1` and 2 bars since `11//5=2`. So now, we get this:

```
 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

```

Finally, putting all this together, we get this:

```
 ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

```

And, that's the mayan numeral for 431! You finally have your base 10 number represented in base 20 Mayan numerals.

**Note:** You may or may not have noticed that `lambda` function in my code. Regardless, this function is used for the creation of the dots since multiple dots must be output next to each other.

# Answer
> 3 votes
# Python 3, 243 bytes

```
s,v,h,x=' |-\n';P=print
t=s+h*19+s+x
def m(n):
 n//20and m(n//20);r=n%20
 if r:
  for a,b,f in[(r%5*' ----  ',r%5*'|    | ',1),('-'*32,'|'+' '*30+'|',r//5)]:P(*((a,b,b,a)*f),sep=x)
 else:P(t+2*(v+(4*s+v)*4+x)+v+h*19+v+x+2*(v+s*19+v+x)+t)
 P(x)

```

# Discussion

`n//20and m(n//20)` calls `m()` recursively if there are higher powers of 20 to be handled. The recursion is done before printing the current place value, so that higher powers get printed first.

If the current place value is non-zero (r!=0), the `for a,b,f`-loop prints the units and then the fives. `a` is the first/forth row and `b` is the second/third row. The trick is in the `print(*((a,b,b,a)*f),sep=x)`. For the units, f = 1 resulting in `print(*(a,b,b,a),sep=x)`, which prints the 4 rows that make up the units symbols (x is a '\n'). For the fives, f = the number of fives to print (r//5), so the tuple (a,b,b,a) gets multiplied (i.e., repeated) by the number of fives to print. If f = 2, we get `print(*(a,b,b,a,a,b,b,a),sep=x)`, which prints two symbols for five.

If the current place value is 0, then the zero symbol is printed.

# Answer
> 2 votes
# Python, 411 bytes

```
w,m=input(),[]
for i in[20**i for i in range(int(w**0.25))][::-1]:m.append(w/i);w=w%i
for i in m or[0]:print(lambda x,y='\n',w=' ----  ',z='|    | ':w*(x%5)+y+z*(x%5)+y+z*(x%5)+y+w*(x%5)+y+('-'*32+'\n|'+' '*30+'|\n'+'-'*32+y)*(x/5)if x else''' -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 ------------------- ''')(i),'\n\n\n'

```

I created this to generate test cases, you can use it as a benchmark. Sorta golfed.

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

```
f=(n,r=(s,n=19)=>s.repeat(n))=>(n>19?f(n/5>>2)+`

`:``)+(n%5?`${r(s=` ----  `,n%5)}
${t=r(`|    | `,n%5)}
${t}
${s}
`:``)+r(`${s=r(`-`,32)}
|${r(` `,30)}|
${s}
`,n/5&3)+(n%20?``:` ${s=r(`-`)}
${t=r(`|    `,4)}|
${t}|
|${s}|
|${t=r(` `)}|
|${t}|
 ${s}
`)

```

# Answer
> 1 votes
# Python 3, 213 bytes

Came up with an even shorter version using a different approach:

```
s,v,h,x=' |-\n'
t=s+h*19+s
k=4*s+v
w=v+4*k
y=v+s*19+v
a=' ----  '
b=v+k+s
c=h*32
d=v+s*30+v
m=lambda n:m(n//20)+([n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4]+n%20//5*[c,d,d,c]if n%20else[t,w,w,v+h*19+v,y,y,t])+[x,x]if n else[]

```

# explanation

The first 9 lines or so, build up strings that are used to make the symbols

```
s,v,h,x = ' |-\n'
k = '    |'

    # parts for a unit
a = ' ----  '
b = '|    | '

    # parts for a five
c = '--------------------------------'
d = '|                              |'

    # parts for a zero
t = ' ------------------- '
w = '|    |    |    |    |'
y = '|                   |'

```

The core of the solution is the recursive function `m`, which builds a list of strings, one string for each line in the output. Schematically, `m` looks like:

```
m(n//20) + (ones + fives if n%20 else zero) + [x,x] if n else []

```

`m` can be rewritten like:

```
def m(n):
  if n:
    ans = m(n//20)                             # process high digits first

    if n%20:                                   # if there is a base-20 digit
      ans += [n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4] # add strings for the 'ones' if any
      ans += n%20//5 * [c, d, d, c]            # add strings for the 'fives' if any

    else:
      ans += [t,w,w,v+h*19+v,y,y,t]            # otherwise, add strings for a `zero`

    ans += [x,x]                               # blank lines between digit groups

  else:
    ans = []                                   # base case

  return ans

```

The recursive call `m(n//20)` comes first so that the most significant digits are done first.

`[n%5*a,n%5*b,n%5*b,n%5*a]` are the string for ones symbols. `a` is the top row for a single symbol. `n%5` is the number of one symbols for this digit. So, `n%5*a` is a string for the top (and bottom) row of `n%5` ones. Similarly, 'n%5\*b\` is a string for the 2nd (and 3rd) row.

The expression `[:n%5*4]` acts like an `if` to avoid extra blank lines in the output if there aren't any 'ones' to output. It's not needed, but makes the output look better.

`n%20//5` is the number of symbols for five that are needed. `[c,d,d,c]` are the strings to make one symbol for five.

`[t,w,w,v+h*19+v,y,y,t]` are the strings to make the zero symbol

`[x,x]` puts at least three blank lines between groups of Mayan digits

# Answer
> 1 votes
# Vyxal, 89 bytes

```
20τƛ¶3*,¬[ð19-…\|4꘍4*\|+…,\|19-\|+,\|19꘍\|+…,,]5ḋ£ð4-ðd+`|  `mð+"mƛ¥*t,;n5ḭ(32\|15꘍-m3/⁋,

```

Try it Online!

Outputs a *lot* of extra newlines.

---
Tags: code-golf, math, ascii-art, base-conversion
---


title: Reorder it up and down

text:
# Question
Title: Reorder it up and down
Given infinite different integers, order them into a sequence \\$a\_1, a\_2, a\_3, ...\\$ such that \\$a\_i\>a\_{i+1}\\$ iff \\$i\\$ is even(or odd, as long as it's constant for all possible inputs and all \\$i\\$). In other word, make the sequence go alternately up and down (or down first, as long as it's constant).

Examples:

```
ℤ => 0,1,-1,2,-2,3,-3,...
ℕ => 0,2,1,4,3,6,5,8,7,...

```

`ℤ => -1,1,-2,2,-3,3,...` is invalid, as 0 never appears, claiming it appears infinitely far away doesn't help. Also it is worth to mention that these two examples covers all possible input types(No maximum or minimum / One border exists).

---

Default sequence IO applies. You can take input as an unordered(aka. you can't specify the order it has) sequence or a function checking if a value is in the set.

Shortest code in each language wins.

# Answer
> 4 votes
# Python 3.8 (pre-release), 140 bytes

```
k=lambda:[int(input())]
S=sorted
c,*p=S(k()+k()+k())
u=0
while 1:print(c);p=S(p+k());p.remove(c:=[x for x in p if x-p[u]if(x>c)^-u][u]);u=~u

```

Try it online!

-3 bytes thanks to l4m2
-9 bytes thanks to Wasif
-5 bytes thanks to l4m2
-9 bytes thanks to Don Thousand
-13 bytes thanks to Don Thousand
-11 bytes thanks to Don Thousand
-3 bytes thanks to l4m2
-2 bytes thanks to l4m2
-6 bytes thanks to ovs
-4 bytes thanks to Don Thousand
-12 bytes thanks to l4m2
-5 bytes thanks to ophact

# Answer
> 2 votes
# Jelly, 28 bytes

```
i»2$ịḟñ@ḟ
;ƓṢNÞƭçṄ}
Ɠ;Ɠ$⁺çṂƊ

```

Try it online!

A full program that reads an infinite unsorted series from STDIN and writes it in an order meeting the criteria in the question (up-down-up-down…).

Uses a modified version of @hyper-neutrino’s Python algorithm.

## Explanation

### Helper link 1

Takes a sorted list of 4 integers (x) as well as the most recent output (y) and calls helper link 2 with the same list after filtering out the most recent output as the left argument and the next output as the right argument.

```
i         | Index of y in x
 »2$      | Max of this and 2
    ịḟ    | Index into x after filtering out y (call this z)
      ñ@ḟ | Call helper link 2 with the filtered y on the left and z on the right

```

### Helper link 2

Takes a list of 3 integers on the left (v) and the next output on the right (w). Appends a new input to the list, sorts it, prints the output and calls helper link 1 with the new sorted list and the output just printed

```
;Ɠ        | Append next input to list
  ṢNÞƭ    | Sort upwards on first call, downwards on next call and alternate for each subsequent call
      çṄ} | Call helper link 1 with the sorted list on the left and w on the right

```

### Main link

```
Ɠ        | Input from STDIN
 ;Ɠ$     | Append next input
       Ɗ | Following as a monad:
    ⁺    | - Append next inlut
     çṂ  | - Call helper link 2 with all three inputs on left and min of first two on right

```

# Answer
> 2 votes
# JavaScript (SpiderMonkey), 74 bytes

```
x=>y=>i=g=z=>print(x-(x=(z+=Math.random(i=!i)>.5&&y-(y=z))>x!=i?x:z)+z)||g

```

Try it online!

I cannot find out any discuss about function reusable requirements for infinite inputs... I hope this one is acceptable..

To my understanding, this should work with probability 1.

# Answer
> 2 votes
# Japt, ~~21~~ 17 bytes

Uses an even-sized moving window with a size of at least 4, moving it 2 slots on every iteration. This way we can't get stuck on intermediate values, while also not needing separate handling for upwards or downwards movement. Originally, I used a window 4 elements wide, but using `A = 10` saves a byte due to automatic comma insertion.

Uses reducing to move through the array, mapping works just the same but is a few bytes longer.

Cut off 4 bytes thanks to Shaggy.

```
rÈiYÑXjYÑA Íó)c}N
r              }N // Reduce the input with the initial value of the inputs array.
     Xj  A        // Get A = 10 items from the input
       YÑ         // at iterator index * 2 so we're always at even steps.
           Íó     // Sort and interleave to get the zig-zag pattern.
 Èi               // Insert the result back into the array
   YÑ             // at the same index,
             )c   // and flatten out all nested arrays.

```

Try it here.

A short manual example with a window size of 4:

```
[..., -5, -4, -3, -2, -1,  0,  1,  2, ...]
      ~~~~~~~~~~~~~~

[..., -5, -3, -4, -2, -1,  0,  1,  2, ...]
              ~~~~~~~~~~~~~~

[..., -5, -3, -4, -1, -2,  0,  1,  2, ...]
                      ~~~~~~~~~~~~~~

[..., -5, -3, -4, -1, -2,  1,  0,  2, ...]
                               ~~~~~~~~~~

```

---
Tags: code-golf, sequence
---


title: Quining, but with Windows files!

text:
# Question
Title: Quining, but with Windows files!
Write a quine, that when run, creates itself in the current directory, in a source file named itself. We will be using Windows in this, so the file name (and therefore quine) must have the following limitations:

* None of these characters `\ / : ? * < > |`
* Fewer than 211 255 characters

### Limitations and assumptions

* Your code must be a full program (It's going to be run after all).
* No copying from the source file.
* You can assume that there isn't another file with your Quine as its name (as it would produce *Quine* (1)).
* Errors are allowed (as long as they don't get into the source code

This is , shortest code in bytes wins!

### Edit

Maybe I wasn't clear, the file with the name of the quine has to actually contain the quine. My bad.

# Answer
> 6 votes
# Node.js, ~~56~~ 52 bytes

```
function f(){require('fs').writeFile(f+='f()',f)}f()

```

This prints the warning

> DeprecationWarning: Calling an asynchronous function without callback is deprecated.

If you want the all-green, it costs 4 bytes to change `writeFile` to `writeFileSync`.

# Answer
> 6 votes
# Vitsy, ~~10~~ 27 bytes

```
'rddd++&"rdd8++a[v}v1-D);].

```

If `:` was allowed, I could shorten this to 11 bytes. :(

Explanation:

```
'rddd++&"rdd8++a[v}v1-D);].
'                           Capture all instructions as a string until encountering
                              ' again, looping if necessary.
 r                          Reverse the current stack (output is top-down).
  ddd++                     Push char literal ' to the stack.
       &                    Push a new stack to the stack stack.
        "                   Same as ', but " specific.
         r                  Reverse the current stack.
          dd8++             Push char literal " to the stack.
               a            Push 10 to the stack.
                [        ]  Loop forever.
                 v          Capture the top value as a variable.
                  }         Take the bottom item of the stack and put it on the top.
                   v        Dump the variable to the stack.
                    1-      Subtract 1.
                      D     Duplicate the top item.
                       );   Pop n; if n is 0, exit the loop.
               a[v v1-D);]  This is a makeshift for loop with 10 iterations.
                          . Pop the top stack as n, and the second stack as o.
                              Write a file called "n" with the contents of "o".

```

The two stacks will be identical at the end. On some Java versions, this may throw a `FileNotFoundException` due to different implementations of the `FileInputStream` class.

### Previous answer before edit:

```
&'rddd++}.

```

Explanation:

```
&           Push a new stack to the stack stack.
 'rddd++    Modified standard quine.
        }   Move the ' to the right place.
         .  Pop the top stack as n, and the second stack as o. Write a file called
                 "n" with the contents of "o". (Quine name, no content)

```

Because I might as well, here's a diagram of the steps that occur within the stacks (each stack is represented by `[]`):

```
Initial state: [[]]

&              [[], []]
                  Push a new stack to the stack stack.

 '             [[], ["r", "d", "d", "d", "+", "+", "}", ".", "&"]]
                  This stack state occurs because ' will loop around the line
                    until finding the next '.

  r            [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r"]]
                  Reverses the top (last) stack.

   ddd         [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", 13, 13, 13]
                  Push thirteen thrice.

      ++       [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", "'"]
                  Because char ' is 39 = 13 + 13 + 13.

        }      [[], [".", "}", "+", "+", "d", "d", "d", "r", "'", "&"]]
                  Takes the bottom item, then puts it on the top.

         .     []
                  Writes a file with content from the second-to-top stack and the
                    name as the concatenation of all elements in the top stack,
                    with top member priority (backwards from my representation).

```

I'm actually not sure how this works right; minute changes cause this to break. For example, placing the `&` in various other locations should work just as well, but it causes `ClassCastException`s, `IOException`s, and `ArrayOutOfBoundsException`s depending on where you put it. I might need to do some bugfixing.

# Answer
> 2 votes
# Lua, 96 bytes.

```
s="s=%qs=string.format(s,s)f=io.open(s)f.write(f,s)"s=string.format(s,s)f=io.open(s)f.write(f,s)

```

Typed this on my phone, should work, but I'll test it when I get to a computer.

# Answer
> 2 votes
# C, 134 bytes

```
s[255];fd;char p[255]="s[255];fd;char p[255]=%c%s%c;main(){sprintf(s,p,34,p,34);creat(s,0);}";main(){sprintf(s,p,34,p,34);creat(s,0);}

```

# Answer
> 2 votes
# Python 3, 51 bytes

```
a="s='a=%r;exec(a)'%a;open(s,'w').write(s)";exec(a)

```

Try it online!

# Python 3, ~~87 79 71~~ 62 bytes

Since windows is not allowing double quote `"` anymore (more infos), I made an other solution verifying the new convention:

```
w='w=%r;open(w%%w,w[0]).write(w%%w)';open(w%w,w[0]).write(w%w)

```

Try it online!

---
Tags: code-golf, restricted-source, quine, file-system
---