# Question
Title: Branchless (MIPS) assembly code for median of 3
I was trying to write a short MIPS32 code for computing the median of three registers.

The rules:

* Assume that some values are pre-loaded into `$t0`, `$t1`, `$t2`.
* The median of the three values should be placed in `$t0`.
* No branches are allowed, but otherwise any instruction is okay.
* You may arbitrarily modify the values of all registers.

I was able to optimize it down to 15 instructions. Can you do better?

# Answer
> 8 votes
# 7 instructions

```
slt $t3, $t0, $t1
slt $t4, $t2, $t1
slt $t5, $t2, $t0

```

Compare all three pairs of values.

```
xor $t3, $t3, $t4
movn $t0, $t1, $t3

```

`$t1` is the median if it is greater than exactly one of the other values.

```
xor $t5, $t5, $t4
movn $t0, $t2, $t5

```

`$t2` is the median if it is less than exactly one of the other values.

(Otherwise, `$t0` is already the median.)

# Answer
> 5 votes
# 8 instructions

```
slt $t4, $t2, $t1
movn $t3, $t1, $t4
movn $t1, $t2, $t4
movn $t2, $t3, $t4

```

Rearrange `$t1` and `$t2` so that `$t1``$t2`.

```
slt $t3, $t2, $t0
slt $t4, $t0, $t1
movn $t0, $t2, $t3
movn $t0, $t1, $t4

```

If `$t0` falls between `$t1` and `$t2`, it is already the median. If it's outside that range, the one it lies beyond is the median.

---
Tags: integer, tips, sorting, atomic-code-golf, assembly
---


title: Fast Matrix Multiplicator Evaluator

text:
# Question
Title: Fast Matrix Multiplicator Evaluator
A triplet of real tensors \\$(A,B,C)\\$ of size \\$\gamma \times \gamma \times \sigma\\$ represents a matrix multiplication algorithm with \\$\sigma\\$ elementary multiplications iff the following function evaluates to zero:

$$ \text{error}(A,B,C) \equiv \sum\_{i,j,k,l,m,n=1}^\gamma\left(\sum\_{r=1}^{\sigma}{A\_{ij}^r B\_{kl}^r C\_{nm}^r} - \delta\_{ni} \delta\_{jk} \delta\_{lm}\right)^2,$$ where \\$\delta\_{ab} = 1\\$ if \\$a=b\\$ and 0 otherwise.

## Reference implementation

A reference implementation in C for the above formula is given below:

```
double error(size_t gamma, size_t sigma, double * A, double * B, double * C) {
    double E = 0.0;
    for (int i = 0; i < gamma; ++i) {
    for (int j = 0; j < gamma; ++j) {
    for (int k = 0; k < gamma; ++k) {
    for (int l = 0; l < gamma; ++l) {
    for (int m = 0; m < gamma; ++m) {
    for (int n = 0; n < gamma; ++n) {
    double s = 0.0, e = 0.0;
    for (int r = 0; r < sigma; ++r) {
        int rij = r*gamma*gamma + i*gamma + j;
        int rkl = r*gamma*gamma + k*gamma + l;
        int rnm = r*gamma*gamma + n*gamma + m;
        s += A[rij] * B[rkl] * C[rnm];
    }
    e = s - (n==i) * (j==k) * (l==m);
    E += e*e;
    }}}}}}
    return E;
}

```

## Sample input & output for \\$(\gamma=2,\sigma=7)\\$

```
double A[] = {1,-1,-1,0,1,-1,-1,1,0,-1,0,0,1,0,-1,0,1,-1,0,0,0,0,0,1,0,0,1,0};
double B[] = {-1,-1,-1,0,0,0,-1,0,1,1,1,1,1,0,1,0,-1,-1,0,0,0,0,0,1,0,-1,0,0};
double C[] = {1,-1,1,0,0,0,-1,0,0,-1,0,0,1,-1,0,0,-1,0,-1,0,0,0,0,1,1,-1,1,-1};
assert (0.0 == error(2, 7, A, B, C));

```

## Challenge

Write a faster version of the reference implementation. While measuring the speed of your code the elements of \\$(A,B,C)\\$ should be doubles sampled uniformly from the \\$\[-1,1\]\\$ interval.

## Competition categories

Your implementation can compete in one or more of the following categories:

1. \\$(\gamma=3,\sigma=22)\\$
2. \\$(\gamma=4,\sigma=48)\\$
3. \\$(\gamma=5,\sigma=97)\\$
4. \\$(\gamma=6,\sigma=159)\\$

## Rules

* The submission must state the \\$(\gamma,\sigma)\\$ category/categories in which your code is competing.
* The submission must contain easy-to-follow build instructions.
* Your code must display the speed of your code **relative to the reference implementation** (e.g. being 3.2x faster than the reference implementation).
* While measuring speed at least 10000 random evaluations must be made.
* For any given input \\$(A,B,C)\\$ the difference between the output of the reference implementation and your implementation must be smaller than \\$10^{-4}\\$.
* Any programming language and open source library (e.g. OpenBLAS) can be used.
* Reference platform: Intel i7-8559U / Linux 5.9.0, GCC 10.3.0. The reference implementation is compiled with the `-O3` flag.

## Scoring

* Submissions will be ordered based on their performance on my Intel i7-8559U.

# Answer
# C (gcc), score ≈ 6.7×, 8.5×, 13.6x, 19.5×

For the four categories (3, 22), (4, 48), (5, 97), (6, 159).

This algorithm runs in \\$O(γ^3σ + γ^2σ^2)\\$ rather than \\$O(γ^6σ)\\$, using the rearranged formula:

\begin{multline\*} \textrm{error}(A, B, C) = γ^3 - 2\sum\_{r=1}^σ \sum\_{i,j,l=1}^γ A\_{ij}^rB\_{jl}^rC\_{il}^r \\ \+ \sum\_{r,s=1}^σ\left(\sum\_{i,j=1}^γ A\_{ij}^rA\_{ij}^s\right)\left(\sum\_{k,l=1}^γ B\_{kl}^rB\_{kl}^s\right)\left(\sum\_{n,m=1}^γ C\_{nm}^rC\_{nm}^s\right). \end{multline\*}

```
double error(size_t gamma, size_t sigma, double *A, double *B, double *C) {
  double E = 0.0;
  for (int r = 0; r < sigma; ++r) {
    for (int i = 0; i < gamma; ++i) {
      for (int j = 0; j < gamma; ++j) {
        double x = 0.0;
        for (int l = 0; l < gamma; ++l) {
          int rkl = r * gamma * gamma + j * gamma + l;
          int rnm = r * gamma * gamma + i * gamma + l;
          x += B[rkl] * C[rnm];
        }
        int rij = r * gamma * gamma + i * gamma + j;
        E += A[rij] * x;
      }
    }
  }
  E = gamma * gamma * gamma - 2 * E;
  for (int r = 0; r < sigma; ++r) {
    for (int s = r; s < sigma; ++s) {
      double xa = 0.0, xb = 0.0, xc = 0.0;
      for (int ij = 0; ij < gamma * gamma; ++ij) {
        int rij = r * gamma * gamma + ij;
        int sij = s * gamma * gamma + ij;
        xa += A[rij] * A[sij];
        xb += B[rij] * B[sij];
        xc += C[rij] * C[sij];
      }
      E += (1 + (r != s)) * xa * xb * xc;
    }
  }
  return E;
}

```

Try it online!
> 7 votes

---
Tags: matrix, fastest-code
---


title: Fibonacci program lengths

text:
# Question
Title: Fibonacci program lengths
Write a program with length n that outputs another program whose length is the next Fibonacci number after n. The new program must do the same thing - output another program whose length is the next Fibonacci number, etc.
n itself (the original program's length) does not have to be a Fibonacci number, although it would be nice if it is.

Shortest code wins.

No external resources, ASCII only, free compiler/interpreter required.
If your output ends in a newline, it is also counted.

# Answer
# CJam, 26 23

I just had a try with your language.

```
7{9\@5mq)2/*')*\"_~"}_~

```

9 is `(22*0.618 + 0.5 - 1)/1.618 + 1`.

It computes its own length`*1.618` instead of repeatedly adding the two numbers. In the first version, it will fill the output before `{` like `1)))))))))`, which counts those characters themselves. Say the result `n`. The total length is `n+22`, and the new length before `{` should be `(n+22)*1.618-22`, rounded. Decrease it by one to count the number of `)`'s. Then it will be approximately equal to `(n+8)*1.618`.

Older version:

```
-3{1\@5mq)2/*E+')*\"_~"}_~

```

The number 14 is `24*0.618 + 0.5 - 1`.
> 5 votes

# Answer
# Python 2, 160 bytes

```
s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=1'
c=s
l=len(s%c)+4
a,b=1,1
while b<l:a,b=b,a+b
c+="1"*(b-l-1)
print s%`c`

```

This is a true quasi-quine; it doesn't read its own source, but it generates it. First output (has trailing newline):

```
s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=111111111111111111111111111111111111111111111111111111111111111111111';c=s;l=len(s%c)+4;a,b=1,1
while b<l:a,b=b,a+b
c+="1"*(b-l-1);print s%`c`;a=1

```

Second:

```
s='s=%s;c=s;l=len(s%%c)+4;a,b=1,1\nwhile b<l:a,b=b,a+b\nc+="1"*(b-l-1);print s%%`c`;a=1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';c=s;l=len(s%c)+4;a,b=1,1
while b<l:a,b=b,a+b
c+="1"*(b-l-1);print s%`c`;a=111111111111111111111111111111111111111111111111111111111111111111111

```

Edit: Oops. Forgot to change the string when I changed from `;`s to `1`s, so the second output was outputting extra semicolons (which Python doesn't support). Fixed
> 7 votes

# Answer
# CJam, ~~41~~ 31 bytes

```
{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~

```

Try it online.

### Output

```
$ cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'); echo
{1$+S@]_1=4+1$`,-S*"2$~"}34 21 2$~
$ cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~') | wc -c
34
$ cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~')); echo
{1$+S@]_1=4+1$`,-S*"2$~"}55 34                      2$~
$ cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~')) | wc -c
55
$ cjam (cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))); echo
bash: syntax error near unexpected token `cjam'
$ cjam <(cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))); echo
{1$+S@]_1=4+1$`,-S*"2$~"}89 55                                                        2$~
$ cjam <(cjam <(cjam <(echo '{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~'))) | wc -c
89

```

### How it works

```
{       "                                                   {…} 21 13                     ";
  1$+   " Duplicate the higher number and add.              {…} 21 34                     ";
  S@    " Push a space and rotate the lower number on top.  {…} 34 ' ' 21                 ";
  ]     " Wrap the stack into an array.                     [ {…} 34 ' ' 21 ]             ";
  _1=   " Push the second element of the array.             [ {…} 34 ' ' 21 ] 34          ";
  4+    " Add 4 to it.                                      [ {…} 34 ' ' 21 ] 38          ";
  1$`,  " Push the length of the stringified array.         [ {…} 34 ' ' 21 ] 38 37       ";
  -S*   " Subtract and push that many spaces.               [ {…} 34 ' ' 21 ] ' '         ";
  "2$~" " Push the string '2$~'.                            [ {…} 34 ' ' 21 ] ' ' '2$~'   ";
}       "                                                   {…}                           ";

21D     " Push 21 and 13.                                   {…} 21 13                     ";
2$~     " Copy the code block an evaluate.                  [ {…} 34 ' ' 21 ] ' ' '2$~'   ";

```
> 7 votes

# Answer
# Python - 89

```
g="%(s,b,a+b);print o.ljust(b-1)";s,a,b="s,a,b=%r,%i,%i;o=s%"+g,89,144;exec("o=s"+g)#####

```

My perfect character count is *gone*. ;\_; Thanks to TheRare for pointing out the newline thing and Quincunx for suggesting I use Python 2, shaving off 2 chars.

**EDIT**: Now just uses more `#`s instead of `1`s; 12 chars shorter.

**EDIT 2**: 94 chars! Eliminated some repetition. \>:3

**EDIT 3**: Shorter repr alternative for Python 2.

**EDIT 4**: Output is a character shorter now.

**EDIT 5**: The use of `%r` to shorten it was taken from an answer on another question by @primo.

**EDIT 6**: Shorter. :D

Here's a Python 3 version:

```
g="%(s,b,a+b);print(o.ljust(b-1))";s,a,b="s,a,b=%r,%i,%i;o=s%"+g,89,144;exec("o=s"+g)####

```

This answer is similar to the one by @Quincunx.
> 6 votes

# Answer
# JavaScript, 94

```
(function q(w,e){return ('('+q+')('+e+','+(s=w+e)+')'+Array(s).join('/')).substr(0,s)})(55,89)

```

Based on a well-known JavaScript Quine, this returns almost the same function, only followed by amount of slashes, such that it sums up to 144 which is the next Fibonacci number after N. And so on...

N is not a Fibonacci number, but it was only "nice to have".
> 2 votes

# Answer
# Python 3.8 (pre-release), 65 bytes

```
a,b=55,89;exec(s:="print((f'a,b={b,a+b};exec(s:=%r)#'%s*b)[:b])")

```

Try it online!
> 1 votes

# Answer
# Pari/GP, 63 bytes

```
(f(a,b)=print1(s=Str("(f="f")("b","a+b");")10^(b-#s-1)))(55,89)

```

Try it online!
> 1 votes

# Answer
## Mathematica

```
({0};
 With[{n = Ceiling[ InverseFunction[Fibonacci]@LeafCount@#0 ], l = Length[#0[[1, 1]]]},
    #0 /. {0..} -> ConstantArray[0, Fibonacci[n+1] - LeafCount[#0] + l]
 ]) &

```

This is a very straightforward implementation (i.e. no obfuscation here). It is an anonymous function that returns itself with a bit of padding to achieve the correct length. Mathematica is homoiconic: code and data are both represented as Mathematica expressions, which makes it realtively easy to modify/generate code on the fly. This also means that character counts are not a natural measure of code length. Epxression size ("leaf count") is. This version is based on leaf counts as code length measure.

If we assign this anonymous function to a variable `f` (so I can show what happens in a readable manner), and keep calling it 1, 2, 3, ... times, each time measuring the length of the return value, this is what we get:

```
In[]:= f // LeafCount
Out[]= 42

In[]:= f[] // LeafCount
Out[]= 89

In[]:= f[][] // LeafCount
Out[]= 144

In[]:= f[][][] // LeafCount
Out[]= 233

```

Regarding the free interpreter requirement: Mathematica is free for the Raspberry Pi. Otherwise this code should be straightforward to port to Mathics (open source). The only thing missing from Mathics is `InverseFunction`, which can be replaced as here (but I'm lazy :).
> 0 votes

# Answer
# Python 3.8 (pre-release), 78 bytes

```
p,c=55,89;exec(s:="print((a:=f'p,c={c},{p+c};exec(s:=%r)'%s)+'#'*(c-len(a)))")

```

Try it online!

---

# Python 2, 79 bytes

```
p,c,s=55,89,"a='p,c,s=%d,%d,%r;exec s'%(c,p+c,s);print a+'#'*(c-len(a))";exec s

```

Try it online!
> 0 votes

---
Tags: code-golf, quine, fibonacci, code-generation
---


title: A Chiral Puzzle

text:
# Question
Title: A Chiral Puzzle
A shape is chiral if no amount of rotation can make it look like it's mirror image. In this puzzle we will be writing chiral computer programs.

For this puzzle we will think of a program as a rectangular matrix of characters. As such all solutions to this challenge must be rectangular (that is all lines must be of the same length). We can rotate these programs in quarter turn increments. For example the program

```
The quickish fish
    lept deftly
  rightwards

```

When rotated a quarter turn clockwise looks like

```
  T
  h
r e
i
glq
heu
tpi
wtc
a k
rdi
des
sfh
 t
 lf
 yi
  s
  h

```

We can also reflect these programs. Here is the same program reflected over a vertical axis:

```
hsif hsikciuq ehT
  yltfed tpel
    sdrawthgir

```

A chiral program is a program that when rotated any number of times will always output "`left`". However when reflected produces a program that outputs "`right`" no matter how many times it is rotated.

Your task is to write a chiral program in as few bytes as possible.

### Additional Rules

* Output is not-case sensitive but should be consistent. (e.g. You may output "`LEFT`" and "`rIgHt`" but this casing must be consistent under rotations)
* Lines are to be split either on a newline or a newline and a linefeed.
* Your program must be a rectangle, you can pad it with spaces or comments but each line must have the same length.
* You may optionally have a trailing newline (or newline and linefeed) on all of your programs if you wish.

# Answer
# Pascal (FPC), ~~2161~~ ~~755~~ 349 bytes

```
///////bw(,,),(wb///////
///////er'''e''re///////
begin//girgtnflig//nigeb
write//itih'dteti//etirw
('le'//ne'' .''en//'ir'(
,'ft'//////////////'hg',
)end.////////////// 't',
,'t' //////////////.dne)
,'gh'//////////////'tf',
('ri'//ne''. ''en//'el'(
write//itetd'hiti//etirw
begin//gilfntgrig//nigeb
///////er''e'''re///////
///////bw(,),,(wb///////

```

Try left

Try right

@tsh motivated me to try again when I saw his program (in comment) and here it is!

---

Previous one with 755 bytes:

```
 begin write('left')end.//
/e .dne)'thgir'(etirw nigeb
/g                        e
.i                       .g
dn                       di
n                        nn
ew                       e
)r                       )w
'i                       'r
tt                       ti
fe                       ht
e(                       ge
l'                       i(
'r                       r'
(i                       'l
eg                       (e
th                       ef
it                       tt
r'                       i'
w)                       r)
 e                       we
nn                        n
id                       nd
g.                       i.
e                        g/
begin write('right')end. e/
 //.dne)'tfel'(etirw nigeb

```

Try left

Try right

If you saw my previous submission, just forget it :)

All rotations for both left and right programs are the same.
> 19 votes

# Answer
# Klein (000), ~~109~~ 87 bytes

```
."left"@\.
\"right"..
@"thgir">.
..@"tfel"\
\"left"@..
.>"right"@
.."thgir"\
.\@"tfel".

```

Try it online!

Should be possible to get a shorter version of this answer so good luck!

This answer is inspired by spirals. In particular the idea is two interlocked spirals, one for left and one for right. It has two fold symmetry, So we can check the following programs to know it works:

## Quarter turn

```
...\.@\.
\.>"."""
@""l@trl
"tre"hie
thiftggf
fggtfiht
eih"ert"
lrt@l""@
""".">.\
.\@.\...

```

Try it online!

## Mirrored

```
.\@.\...
""".">.\
lrt@l""@
eih"ert"
fggtfiht
thiftggf
"tre"hie
@""l@trl
\.>"."""
...\.@\.

```

Try it online!

## Mirrored and Quarter turn

```
.\@"tfel".
.."thgir"\
.>"right"@
\"left"@..
..@"tfel"\
@"thgir">.
\"right"..
."left"@\.

```

Try it online!
> 11 votes

# Answer
# Klein (000), ~~27~~ 25 bytes

```
\(("right"@/
\(("left"@!\

```

Try it online! Rotated once! Rotated twice! Rotated three times!

And flipped: Try it online! Rotated once! Rotated twice! Rotated thrice!

The only one that gave me a bit of trouble was the flipped and rotated once, which looks like:

```
\/
!@
@"
"t
th
fg
ei
lr
""
((
((
\\

```

This is the only reason for the two sets of `((`.
> 10 votes

# Answer
# JavaScript (Node.js), ~~1481~~ ~~599~~ ~~505~~ ~~461~~ ~~341~~ ~~305~~ 271 bytes

```
/g+///g/g"c.c"g/
g=//////=rolol=g
"left"///inone/+
console//gsgsf//
.log(g)//ho(ot//
console//tlgl"//
"right"//"e)e//g
g=//////////////
//////////////=g
g//e)e"//"thgir"
//"lglt//elosnoc
//to(oh//)g(gol.
//fsgsg//elosnoc
+/enoni///"tfel"
g=lolor=//////=g
/g"c.c"g/g///+g/

```

## Mirrored

```
/g"c.c"g/g///+g/
g=lolor=//////=g
+/enoni///"tfel"
//fsgsg//elosnoc
//to(oh//)g(gol.
//"lglt//elosnoc
g//e)e"//"thgir"
//////////////=g
g=//////////////
"right"//"e)e//g
console//tlgl"//
.log(g)//ho(ot//
console//gsgsf//
"left"///inone/+
g=//////=rolol=g
/g+///g/g"c.c"g/

```

Try it online!

### (Please see the TIO Link for all test cases, including mirrored version)

### Although further golfed, size `22x22 -> 21x21` on credit of @JoKing!

Size ~~38x38~~ ~~24x24~~ ~~22x22~~ ~~21x21~~ ~~18x18~~ ~~17x17~~ 16x16, 4-fold symmetry.

Here comes a question -- is it possible to have 15x15 or smaller for JS? It seems that what I need at least is the comment separator between two sub-blocks and at the edge, so at least 7+2+2+5=16 lines?
> 10 votes

# Answer
# Klein (211), 37 bytes

```
!\"left"@"thgir"\!
!/............../!

```

This has a different program for each rotation.

## Explanation

Note that each of these programs is padded to a square with no-ops before execution

### No change

```
!\"left"@"thgir"\!
!/............../!

```

Try it online!

`!` makes execution jump over the `\` and `"left"@` loads the string `"left"` into the stack and terminates the program printing the stack

### Quarter turn

```
!!...IP->
\/
".
r.
i.
g.
h.
t.
".
@.
".
t.
f.
e.
l.
".
\/
!!
^
|
P
I

```

Try it online!

Execution runs off the top right corner of the square, continues in the bottom left corner and once again `!\"left"@` prints `"left`.

### Half turn

```
                ^
                |
                P
                I
!/............../!
!\"right"@"tfel"\!
..................
..................
..................
..................
..................
..................
..................
..................
..................
..................
..................
..................
................^.
................|.
IP->............P.
................I.

```

Try it online!

Here, the execution path exits from the North side, re-enters through the West side, exits again from the East Before entering in the south. `\` bounces the path into `"left"@` to print it.

### Three-quarter turn

```
!!..IP->
/\
."
.l
.e
.f
.t
."
.@
."
.t
.h
.g
.i
.r
."
/\
!!
^
|
I
P

```

Try it online

Execution exits from the top right corner then re-enters in the bottom left. Once again the mirrors `/\` redirect the path into `"left"@` to print it.

### Reflection

```
!\"right"@"tfel"\!
!/............../!

```

This is essentialy the same as for left in all rotations.
> 9 votes

# Answer
# Canvas, ~~109~~ ~~89~~ 71 bytes

```
（tfel⁸（（
（h（right
⁸g   q（f
li    re
er    il
f（    g⁸
thgir（h（
（（⁸left（

```

Try it here | Try reversed! Those are the only two possible programs, as the program is rotationally symmetric.

Made in this.
> 8 votes

# Answer
# Gol\>\<\>, 23 bytes

```
\"thgir"H /
\"tfel"H.9\

```

Try it online!

This is the same format as my Klein answer, but 2 bytes shorter. Maybe there's another 2D language out there that can golf those last 2 bytes off... But for now, this is as short as it gets.
> 8 votes

# Answer
# Ruby, 131 bytes

```
#######:$:#
:right#l>r#
$><<###e<i#
:left##f<g#
####   t#h#
#t##   ##t#
#h#t   ####
#g<f##tfel:
#i<e###<<>$
#r>l#thgir:
#:$:#######

```

Try it online!
> 8 votes

# Answer
# Hexagony, 98 bytes

```
\.@.t;./r.
.)@.;...;.
ll..)gt.;$
;.i<;;;i);
e;@.)@e;.l
.;e;d.g|.|
rt/;t.;)g\
@f.#l.;..r
\.;\.;i\.i

```

Try it online! | Rotated 90° | Rotated 180° | Rotated 270°
Reversed | Rotated 90° & Reversed | Rotated 180° & Reversed | Rotated 270° & Reversed

Hexagony was kind of fun for this challenge, because a rotation or a reversal can drastically change the actual program. Each Rotation/Reversal is its own unique program. Some of the program execution paths are much more interesting than others.

I will admit that coming up with this took longer than it probably should have. I am pretty sure a shorter answer can be done in Hexagony, so good luck!
> 8 votes

# Answer
# APL (dzaima/APL), 181 bytes

The program has rotational symmetry so only two cases need to be checked

---

## Left

```
⍝⍝⍝⍝⍝⍝⍝  t⎕t⍝
t←'lef'⍝ ←←←⍝
⎕←t,     't'⍝
t←'righ'⍝r,l⍝
   ⍝     i e⍝
 ⍝ '     g f⍝
⍝' h     h '⍝
⍝f g     t ⍝
⍝e i     ⍝
⍝l,r⍝'hgir'←t
⍝'t'     ,t←⎕
⍝←←← ⍝'fel'←t
⍝t⎕t  ⍝⍝⍝⍝⍝⍝⍝

```

Try it online!

## Right

```
⍝t⎕t  ⍝⍝⍝⍝⍝⍝⍝
⍝←←← ⍝'fel'←t
⍝'t'     ,t←⎕
⍝l,r⍝'hgir'←t
⍝e i     ⍝
⍝f g     t ⍝
⍝' h     h '⍝
 ⍝ '     g f⍝
   ⍝     i e⍝
t←'righ'⍝r,l⍝
⎕←t,     't'⍝
t←'lef'⍝ ←←←⍝
⍝⍝⍝⍝⍝⍝⍝  t⎕t⍝

```

Try it online!

## Explanation

This is my first APL program so it is pretty simple. It only uses one trick that I think is interesting.

If we start by stripping away all the comments we get the following programs

**Left**

```
t←'lef'
⎕←t,     't'
t←'righ'

```

**Right**

```
t←'righ'
⎕←t,     't'
t←'lef'

```

Starting from the left program we do three things.

1. Assign `'lef'` to the variable `t`
2. Print the variable `t` and the letter `'t'`
3. Assign `'righ'` to the variable `t`

Now because it is the mirror the right program does these three steps but in the opposite order. This means that we print `'left'` for the left program and `'right'` for the right program.

The one trick here is that the `'t'` actually comes from a rotated copy of the code. If you look at the third colum of our code you will see that it is `'t'`. We reuse this `'t'` in the rotated versions to append the `t` that is needed.
> 8 votes

# Answer
# Alice, 25 bytes

```
}/"regttoo {
{/"lifh""@@{

```

Left: Normal, 1/4 turn clockwise, 1/2 turn, 1/4 turn counterclockwise

Right: reflect across horizontal axis, down-right diagonal, vertical axis, up-right diagonal

## Explanation

This program has three parts. The first part is the three `{`s and one `}` on the corners. The `{` turn the IP left until it reaches the `}`, at which point it turns right. In the reflected version, the IP goes along the top row in the original program. In the original version, turning right will immediately hit the adjacent `{`, pointing the IP along the bottom row in the original program.

Next are the two slashes in the second column. If the program is horizontally oriented, either type of slash would simply change to ordinal mode, sending the IP in the same left/right direction it was already going. If the program is vertically oriented, the IP bounces around quite a bit more, but making them both forward slashes gives the same end result. (Two backslashes would give the opposite result, and one of each would create an infinite loop.)

The rest of the program is straightforward. The IP in ordinal mode bounces diagonally, so either `"left"o@` or `"right"o@` will be run depending on how this section was entered.
> 7 votes

# Answer
# Haskell, ~~461~~ 379 bytes

*82 bytes saved by Ørjan Johansen*

```
--_----------mppr--
-- ----------a  l--
rl=p  p--   niam= _
p m="left"-- n==p--
p a="right"++ "" --
main  =putStr rl --
--n +r       =iep--
-- -+t       pgf---
-- -"S       uht---
-- "tt       tt" --
---thu       S"- --
---fgp       t+- --
--pei=       r+ n--
-- lr rtStup=  niam
-- "" ++"thgir"=a p
--p==n --"tfel"=m p
_ =main   --p  p=lr
--l  a---------- --
--rppm----------_--

```

Try it online!

Since this one has 4-fold symmetry you only need to test the mirror:

```
--rppm----------_--
--l  a---------- --
_ =main   --p  p=lr
--p==n --"tfel"=m p
-- "" ++"thgir"=a p
-- lr rtStup=  niam
--pei=       r+ n--
---fgp       t+- --
---thu       S"- --
-- "tt       tt" --
-- -"S       uht---
-- -+t       pgf---
--n +r       =iep--
main  =putStr rl --
p a="right"++ "" --
p m="left"-- n==p--
rl=p  p--   niam= _
-- ----------a  l--
--_----------mppr--

```

Try it online!

This is a start. It is far from ideal, but there are a few interesting things going on here. Haskell is a certainly an interesting language for this challenge. I look forward to an answer that beats this be it mine or someone else's.
> 6 votes

# Answer
# Python 2, 209 bytes (14 x 14)

Normal (left):

```
##########sps#
s="left"##=r=#
print s###"i"#
s="right"#rnl#
####      ite#
###"      g f#
#"#t      hst#
#tsh      t#"#
#f g      "###
#eti      ####
#lnr#"thgir"=s
#"i"###s tnirp
#=r=##"tfel"=s
#sps##########

```

Try it online!

Reflected (right):

```
#sps##########
#=r=##"tfel"=s
#"i"###s tnirp
#lnr#"thgir"=s
#eti      ####
#f g      "###
#tsh      t#"#
#"#t      hst#
###"      g f#
####      ite#
s="right"#rnl#
print s###"i"#
s="left"##=r=#
##########sps#

```

Try it online!
> 6 votes

# Answer
# Vyxal, 55 bytes

```
####‛‛#
‛⟑ǒ#¬⟑#
‛¬ẋ#ẋǒ#
#######
#ǒẋ#ẋ¬‛
#⟑¬#ǒ⟑‛
#‛‛####

```

Try it Online! | Try it flipped

The code is rotationally symetrical.
> 5 votes

# Answer
# Prolog (SWI), ~~649~~ 188 bytes

### Unflipped, Unrotated

```
:-%    l :%r     %-:
write(%e%-(i %(etirw
left).%f.weg%.)right
%      t)rth.      %
%      )tiit)      %
%      .htr)t      %
right).%gew.f%.)left
write(% i(-%e%(etirw
:-%     r%: l    %-:

```

Try it online!

### Unflipped, Rotated

```
:wr%%%lw:
-ri   er-
%ig   fi%
 th   tt
 et   )e
 ()   .(
 %.   %%
  %.)tfel
right).%
%(etirw-:
:-write(%
 %.)thgir
left).%
 %%   .%
 (.   )(
 e)   re
 tl   it
%ie   gi%
-rf   hr-
:wt%%%tw:

```

Try it online!

### Flipped, Unrotated

```
:-%     r%: l    %-:
write(% i(-%e%(etirw
right).%gew.f%.)left
%      .htr)t      %
%      )tiit)      %
%      t)rth.      %
left).%f.weg%.)right
write(%e%-(i %(etirw
:-%    l :%r     %-:

```

Try it online!

## Flipped, Rotated

```
:wl%%%rw:
-re   ir-
%if   gi%
 tt   ht
 e)   te
 (.   )(
 %%   .%
left).%
 %.)thgir
:-write(%
%(etirw-:
right).%
  %.)tfel
 %.   %%
 ()   .(
 er   )e
 ti   lt
%ig   ei%
-rh   fr-
:wt%%%tw:

```

Try it online!
> 4 votes

# Answer
# Prolog (SWI), ~~239~~ ~~223~~ ~~209~~ 181 bytes

```
%%%%%%%  l:r%
right).% e-i%
:-write(%fwg%
left).%  trh%
  %      )it%
 %(      .t)%
%.e%     %e.%
%)t.      (%
%ti)      %
%hrt  %.)tfel
%gwf%(etirw-:
%i-e %.)thgir
%r:l  %%%%%%%

```

Try it online!

Since the program has 4 fold symmetry you only need to check the mirror:

```
%r:l  %%%%%%%
%i-e %.)thgir
%gwf%(etirw-:
%hrt  %.)tfel
%ti)      %
%)t.      (%
%.e%     %e.%
 %(      .t)%
  %      )it%
left).%  trh%
:-write(%fwg%
right).% e-i%
%%%%%%%  l:r%

```

Try it online!
> 4 votes

# Answer
# Clean, ~~1331~~ 1055 bytes

*-276 bytes thanks to Ørjan Johansen*

```
// ////////////;/;/////////// //
// ////////////S/S/////////// //
  module m////mtmt////m eludom
//o///////////=a=a///////////o//
//d///////////"r"r///////////d//
//u///////////tttt///////////u//
//l///////////f#h#///////////l//
//e///////////emgm///////////e//
// ///////////loio/////////// //
//m///////////"drd///////////m//
//////////////=u"u//////////////
//////////////ml=l//////////////
//////////////#eme//////////////
////////////// =#=//////////////
;Start#module= 0   #m="left"=m//
//m="thgir"=m#   0=eludom#tratS;
;Start#module=0   #m="right"=m//
//m="tfel"=m#   0 =eludom#tratS;
//////////////=#= //////////////
//////////////eme#//////////////
//////////////l=lm//////////////
//////////////u"u=//////////////
//m///////////drd"///////////m//
// ///////////oiol/////////// //
//e///////////mgme///////////e//
//l///////////#h#f///////////l//
//u///////////tttt///////////u//
//d///////////r"r"///////////d//
//o///////////a=a=///////////o//
  module m////tmtm////m eludom
// ///////////S/S//////////// //
// ///////////;/;//////////// //

```

Try "left" online!

Try "right" online!

This was difficult for many reasons:

* Clean *requires* a file header `module <filename>` be present at the start, *and only the start* of the file. Unfortunately, this means that for the rotations of the mirrored program to be valid it also has to appear at the bottom of the file. To make this worse, `module ..` is invalid for global, `let .. in`, `where ..` and `with ..` definitions; and the token `module` appearing if it hasn't been defined causes an error.
* Both block comments and line comments nest: `/* /* */` leaves one level of comment open, and so does `/* // */` (as well as commenting the rest of the line out).
* The same function can be defined multiple times, but only directly after itself.

Fortunately, we *can* define `module` as something in a `#..` (let-before) expression, which is all we need. Because Clean doesn't type-check alternatives that are never used (and a variety of other equally unused things), the requisite second definition of `Start` can be complete garbage. This allows us to use the second `Start` to consume the module header at the bottom of the file because Clean treats `m module m` as calling the function `m` on `module` and `m` (which since we've defined `module` and `m`, doesn't cause an error). It doesn't matter that `m` is a string and not a function, because the `Start` alternative never gets type-checked.

This is easier to see if you look at it through the compiler's eyes:

```
module m;
Start#module=0#m="left"=m;
Start#module=0#m="right"=m module m

```
> 4 votes

# Answer
# Brachylog, 341 bytes

```
Ẹw"thgir"∧"left"wẸ
w"              "w
"                "
t                t
f                h
e                g
l                i
"                r
∧                "
"                ∧
r                "
i                l
g                e
h                f
t                t
"                "
w"              "w
Ẹw"tfel"∧"right"wẸ

```

Try it online!

!enilno ti yrT

Takes advantage of Brachylog taking the main predicate to be the one on the first line and not much caring about the other lines beyond requiring that they can compile. Unreflected, it prints an empty string followed by "left" on the same line, and reflected it prints an empty string followed by "right" on the same line. I'm tempted to think there might be a way to make a (usefully) non-square version using , but that might be plenty tricky without trying to make it work differently under reflection.
> 4 votes

# Answer
# Ruby, 181 bytes

```
#########tpt#
t=:left##=u=#
puts t###:t:#
t=:right#rsl#
####     i e#
###t     gtf#
#t#h     h#t#
#ftg     t###
#e i     ####
#lsr#thgir:=t
#:t:###t stup
#=u=##tfel:=t
#tpt#########

```

Try it online!

This is a port of Curtis Bechtel's Python answer to Ruby, golfed a little more.

Actually, his Python program is a polyglot and runs on Ruby too, so my first answer was a copy-paste of it, but it seemed unfair. So I wrote a script that generates a new answer starting from a base script. You can try it here:

Build your own
> 3 votes

# Answer
# 05AB1E (legacy), ~~89~~ 55 bytes

```
'…¸q©ƒ'
ƒ     …
©     ¸
q     q
¸     ©
…     ƒ
'ƒ©q¸…'

```

Very basic approach. Outputs in full lowercase.

Try it online or try it online reflected (each rotation is the same).

**Explanation:**

```
'…¸   '# Push the dictionary string "left" to the stack
   q   # Stop the program (and output the top of the stack implicitly)
       # Everything else after it is ignored

```

Reversed:

```
'ƒ©   '# Push the dictionary string "right" to the stack
   q   # Stop the program (and output the top of the stack implicitly)
       # Everything else after it is ignored

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'…¸` is `"left"` and `'ƒ©` is `"right"`.
> 3 votes

# Answer
# Stax, 131 bytes

```
 .Cq"tfel"
""`KT?`qC".
lC       `C
eq       Kq
f`       T"
t?       ?t
"T       `f
qK       qe
C`       Cl
."Cq`?TK`""
 "left"qC.

```

Run and debug it

This is the "right" variant.
> 3 votes

# Answer
## Batch, ~~438~~ 321 bytes

```
:::::::::::::@@@:
@echo left&: eee:
@exit/b&:    cxc:
@echo right&:hih:
:  :         oto:
:: &          / :
:& t         rbl:
:t h         i&e:
:f:g         g:f:
:e&i         h t:
:lbr         t &:
: /          & ::
:oto         :  :
:hih:&thgir ohce@
:cxc    :&b/tixe@
:eee :&tfel ohce@
:@@@:::::::::::::

```

Explanation: A `:` is used to indicate a label, which is as good as a comment, so as the program has rotational symmetry the only difference between the two versions is which of the `@` lines is first, in which case either `left` or `right` is output before the script exits.

I did try creatively overlapping the rotated lines with each other but my attempt actually ended up with a larger grid.

Edit: Saved 117 bytes thanks to @ØrjanJohansen.
> 2 votes

# Answer
# Runic Enchantments, 116 bytes

```
> \ !U\L
 ...@..
 \.R"""
 @""trl
 "lrhie
 teiggf
 ffgiht
 ethrt"
 l"t""@
 " "R.\
 .\@.@.
DR\!!/R
     !!

```

Try it online!

And reversed

Not exactly a port, but utilized Post Left Garf Hunter's Klein 000 answer as a starting point, given the typical near-compatibility of the two languages (most commands are the same and the edge wrapping in Runic is identical to Klein 000). The only issue was that Klein IPs always start from the top left and Runic's do not. As such the `.` are all part of the original code and still treated as NOP by Runic, while the  are NOPs I had to add as part of controlling the flow.

Prints `"left"` in all 4 rotations and `"right"` when mirrored (and in all four rotations thereof). Two middle columns were completely unused after my modifications, so I was able to remove them.

In theory a rotation with lots of trailing whitespace could be used for a lower byte count (eg. this variant), however the spaces are needed to correctly rotate the structure using external tools and so I included them.

Below variants contain the unused chunks that were removed, but are otherwise identical:

All four lefts. Outputs `leftleftleftleft` (the fact that all four can be run like this is coincidence).

Right 1, Right 2, Right 3, Right 4
> 2 votes

# Answer
# Gol\>\<\>, 342 bytes

```
 8A_          _A8
9       ""       9
A       LR       A
_       EI       _
        FG
        TH
        "T
         "
 "TFEL" HH"RIGHT"
 "THGIR"HH "LEFT"
        "
        T"
        HT
        GF
_       IE       _
A       RL       A
9       ""       9
 8A_          _A8

```

Wow! That took longer than I expected, halfway through I realized the reflection was *vertically*, not horizontally like I had been coding for! I'm pretty sure that this works, but if I made a mistake please let me know. This can most likely be golfed a ridiculous amount more, I just took an extreme brute force method to do so. The shape itself is actually a square, it is technically symmetric, except on across the x-axis, so when it flips, it returns "RIGHT" instead!!!

The character that made this program possible is the 'A', which allows for teleportation to the beginning of a certain line!

Try it online!
> 1 votes

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


# Question
Title: Find all the Anagrams, and the Subanagrams too!
This question is heavily based off this question, but should pose a number of additional difficulties.

## Your Task

You must write a program or function that, when receiving a string, prints out all possible anagrams of it. For the purpose of this question, an anagram is a string that contains the same character as the original string, but is not the original string. A subanagram is an anagram of a substring of an inputted string. Anagrams and subanagrams do not have to be or contain actual words.

## Input

You may accept a string, which may be of any length \> 0, by any standard input method. It may contain any ASCII characters.

## Output

You may output all of the possible anagrams and subanagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input.

## Other Rules

Standard Loopholes are disallowed

## Scoring

This is , least bytes wins.

# Answer
# 05AB1E, 7 bytes

```
Œ€œ˜Ù¹K

```

A function that accepts a string from input and leaves a list of strings on the stack. As a full program a representation of the list is printed.

**Try it online!**

### How?

```
        - push input
Œ       - all substrings
 €œ     - for €ach: all permutations
   ˜    - flatten
    Ù   - de-duplicate
     ¹  - push 1st input onto top of stack
      K - pop a,b; push a without any b's (remove the copy of the input from the list)
        - as a full program: implicit print of the top of the stack

```
> 9 votes

# Answer
# Brachylog (2), 7 bytes

```
{sp}ᶠdb

```

Try it online!

## Explanation

```
{sp}ᶠdb
{  }ᶠ    Find all
  p        permutations of
 s         a substring of {the input}
     d   Remove duplicates (leaving the list otherwise in the same order)
      b  Remove the first (the input itself)

```
> 9 votes

# Answer
# Jelly, 9 bytes

```
ẆŒ!€;/QḟW

```

A monadic link accepting a list and returning a list of all distinct sub-anagrams except the input itself.

**Try it online!** (the footer pretty-prints the resulting list by joining with newlines.)

### How?

```
ẆŒ!€;/QḟW - Link: list of characters, s
Ẇ         - all contiguous sublists of s
 Œ!€      - all permutations for €ach sublist now a list of lists of lists)
     /    - reduce by:
    ;     -   concatenation (flattens the list by one level)
      Q   - de-duplicate (gets the unique entries)
        W - wrap s in a list (otherwise filtering will attempt to remove characters)
       ḟ  - filter discard from left if in right (remove the one equal to the input)

```
> 7 votes

# Answer
# Pyth, 12

```
-{.n.pM.:Q)]

```

Online test.

```
         Q       # input
       .: )      # all substrings
    .pM          # all permutations of all substrings
  .n             # flatten
 {               # deduplicate
-          ]Q    # subtract (list of) (implicit) input

```
> 4 votes

# Answer
# Japt, 10 bytes

```
à má c â Å

```

Try it online!

I got to use `à`, `á`, and `â` all in one answer, in order too. What a coincidence...

### Explanation

```
 à má c â Å
Uà má c â s1  // Ungolfed
              // Implicit: U = input string
Uà            // Take all combinations of characters in the input string.
   má         // Map each combination to all of its permutations.
      c       // Flatten into a single array.
        â     // Uniquify; remove all duplicates.
          s1  // Remove the first item (the input) from the resulting array.
              // Implicit: output resulting array, separated by commas

```
> 3 votes

# Answer
## Mathematica, 60 bytes

```
DeleteCases[""<>#&/@Permutations[c=Characters@#,Tr[1^c]],#]&

```

`Permutations` takes an optional numerical argument which tells it how many of the input values to use for the permutations. If we give it the length of the input, it will generate the permutations for all subsets of the input without duplicates. All we need to do is remove the input.
> 1 votes

# Answer
# Java 8, ~~313~~ ~~312~~ ~~306~~ 297 bytes

```
import java.util.*;s->{Set l=new HashSet();for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;)p("",s.substring(i,++j),l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);for(;i<n;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l));}

```

Modified version of my answer here, where `p("",s,l);` has been replaced with `for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;p("",s.substring(i,j+++1),l));`

-6 bytes thanks to *@OlivierGrégoire* in my linked answer
-9 bytes thanks to *@ceilingcat*

Try it online.

**Explanation of this part:**

```
for(int z=s.length(),i=0,j;i<z;i++) // Loop `i` in the range [0,length):
  for(j=i;j<z;)                     //  Inner loop `j` in the range [i,length):
    p("",                           //   Call the permutation-method,
      s.substring(i,++j),l));       //   with a substring at index-range [i,j]

```
> 1 votes

# Answer
# Vyxal, 9 bytes

```
ǎƛṖ;fU'⁰≠

```

## Explanation

```
<implicit input>
ǎ                 - Get substrings
 ƛṖ;              - Map over substrings: Get permutations
    f             - Flatten it
     U            - Uniquify, remove all duplicates
      '⁰≠         - Filter lambda: Keep all elements that don't equal input
<implicit output>

```

Try it Online!
> 1 votes

# Answer
# Perl 6, 75 bytes

```
{unique(flat $_,.comb.combinations.skip».permutations.map(*».join)).skip}

```

Try it

## Expanded:

```
{                    # bare block lambda with implicit parameter ｢$_｣

  unique(            # return each (sub)anagram once

    flat             # unstructure the following (List of Lists into flat List)
      $_,            # the input (so we can skip it at the end)

      .comb          # split the input into graphemes
      .combinations  # get all the combinations
      .skip\         # skip the first empty combination
      ».permutations # get all the permutations of each combination
      .map(*».join)  # join the inner permutations

  ).skip             # skip the first value (the input)
}

```
> 0 votes

---
Tags: code-golf, string, permutations
---


title: Checkered grid with X mark

text:
# Question
Title: Checkered grid with X mark
## Challenge

Given two integer values \\$a \ge 2\\$ and \\$0 \le b \ 0\\$, overwrite the checkerboard with 2s in the X shape at the center, each leg being of length \\$b\\$ (not counting the center).

This pattern is directly modeled from Art Puzzle event grids (where \\$a\\$ is fixed at 3, \\$b=0,1,2\\$ represent easy/normal/hard grids, and the 0, 1, 2s in the output represent easy/normal/hard minipuzzles respectively). Blame it if you don't like the edge case of \\$b=0\\$ :P

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
a = 2, b = 0
[[0, 1, 0],
 [1, 0, 1],
 [0, 1, 0]]

a = 2, b = 1
[[2, 1, 2],
 [1, 2, 1],
 [2, 1, 2]]

a = 3, b = 0
[[0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0]]

a = 3, b = 1
[[0, 1, 0, 1, 0],
 [1, 2, 1, 2, 1],
 [0, 1, 2, 1, 0],
 [1, 2, 1, 2, 1],
 [0, 1, 0, 1, 0]]

a = 3, b = 2
[[2, 1, 0, 1, 2],
 [1, 2, 1, 2, 1],
 [0, 1, 2, 1, 0],
 [1, 2, 1, 2, 1],
 [2, 1, 0, 1, 2]]

a = 4, b = 0
[[0, 1, 0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0, 1, 0]]

a = 4, b = 1
[[0, 1, 0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1, 0, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 0, 1, 2, 1, 0, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 0, 1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0, 1, 0]]

a = 4, b = 2
[[0, 1, 0, 1, 0, 1, 0],
 [1, 2, 1, 0, 1, 2, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 0, 1, 2, 1, 0, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 2, 1, 0, 1, 2, 1],
 [0, 1, 0, 1, 0, 1, 0]]

a = 4, b = 3
[[2, 1, 0, 1, 0, 1, 2],
 [1, 2, 1, 0, 1, 2, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 0, 1, 2, 1, 0, 1],
 [0, 1, 2, 1, 2, 1, 0],
 [1, 2, 1, 0, 1, 2, 1],
 [2, 1, 0, 1, 0, 1, 2]]

```

# Answer
> 6 votes
# , ~~72~~ 68 bytes

```
function(a,b)`[<-`(diag(2*a-1)*0+0:1,cbind(c(x<--b:b,-x),x)+a,2*!!b)

```

Try it online!

Thanks to Robin Ryder for -4 bytes.

# Answer
> 5 votes
# Charcoal, ~~22~~ 21 bytes

```
ＵＯ±Ｎ01¶10‖Ｏ⌈¿ＩηＰX×2⊕η

```

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

```
ＵＯ±Ｎ01¶10

```

Draw a chequerboard of size `a` with `0`s on its major diagonals above and to the left of the current position.

```
‖Ｏ⌈

```

Reflect it to produce a chequerboard of size `2a-1`, leaving the current position in the middle of the chequerboard. (Note that while drawing the chequerboard below and right would save a byte, there is no single byte to reflect up and left, and Charcoal's up reflect is buggy and moves the current position incorrectly anyway.)

```
¿Ｉη

```

Test whether `b` is zero.

```
ＰX×2⊕η

```

If not then draw arms of `2`s of length `b+1` (including the centre).

# Answer
> 4 votes
# Python 3.8 (pre-release), 82, 80 bytes (@ovs)

```
lambda a,b:(R:=range(1-a,a))and[[1&x+y|(x*x==y*y<=b*b>0)*2for x in R]for y in R]

```

Try it online!

Old version

Nothing too fancy, still learning the ropes. Should run on older python3s, too.

# Answer
> 4 votes
# 05AB1E, ~~25~~ 24 bytes

```
Dи2.ý01ŽNœSΛĀ+Y87S.Λ.º.∊

```

Can probably be shortened with a different approach, but I wanted to try and use the Canvas builtin for this challenge.

-1 byte thanks to *@ovs*.

Try it online.

**Explanation:**

```
D            # Duplicate the first (implicit) input-integer `a`
 и           # Create a list with `a` amount of `a`s
  2.ý        # Intersperse it with 2: [a,2,a,2,a,2,...,a]
     01      # Push "01"
       ŽNœ   # Push compressed integer 6020
          S  # Convert it to a list of digits: [6,0,2,0]
           Λ # Use the Canvas builtin with these three options:
             #  Length: [a,2,a,2,a,2,...,a]
             #  Characters to draw: "01"
             #  Directions: [6,0,2,0]
Ā            # Check if the (implicit) second input-integer `b` is NOT 0
 +           # Add this check to the (implicit) second input-integer `b`
             # (b=0 will remain 0; b≥1 is now b+1)
  Y          # Push "2"
   87S       # Push list [8,7]
      .Λ     # Use the modifiable Canvas builtin with these three options:
             #  Length: b+1 (or 0 if b=0)
             #  Characters to draw: "2"
             #  Directions: [8,7]
.º           # Intersected mirror the result towards the left
  .∊         # Intersected mirror the result downwards
             # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ŽNœ` is `6020`.

The Canvas Builtin uses three arguments to draw a shape:

* Length of the lines we want to draw
* Character/string to draw
* The direction to draw in, where each digit represents a certain direction:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

Here a step-by-step explanation of how it draws for example inputs \\$a=5,b=2\\$ with these steps:

Preparation: `Dи2.ý` makes the list `[5,2,5,2,5,2,5,2,5]`.

`Dи2.ý01ŽNœSΛ` for this input will have the following Canvas arguments:

* Length: `[5,2,5,2,5,2,5,2,5]`
* Characters: `"01"`
* Directions: `[6,0,6,2]`, which translate to \\$\[←,↑,→,↑\]\\$

Step 1: Draw 5 characters (`"01010"`) in direction `6←`:

```
01010

```

Step 2: Draw 2-1 characters (`"1"`) in direction `0↑`:

```
1
01010

```

Step 3: Draw 5-1 characters (`"0101"`) in direction `2→`:

```
10101
01010

```

Step 4: Draw 2-1 characters (`"0"`) in direction `0↑`:

```
    0
10101
01010

```

Step 5: Draw 5-1 characters (`"1010"`) in direction `6←`:

```
01010
10101
01010

```

Step 6: Draw 2-1 characters (`"1"`) in direction `0↑`:

```
1
01010
10101
01010

```

Step 7: Draw 5-1 characters (`"0101"`) in direction `2→`:

```
10101
01010
10101
01010

```

Step 8: Draw 2-1 characters (`"0"`) in direction `0↑`:

```
    0
10101
01010
10101
01010

```

Step 9: Draw 5-1 characters (`"1010"`) in direction `6←`:

```
01010
10101
01010
10101
01010

```

We then use the Canvas builtin again with three new arguments: `Ā+Y87S.Λ`

* Length: \\$b+1\\$ (or \\$0\\$ if \\$b=0\\$, because with length `1`, direction `8` will draw a `"2"` at the position it was at before the reset unfortunately)
* Characters to draw: `"2"`
* Direction: `[8,7]`, where the `8` is a special direction that resets the starting position (to the bottom-left we started at) and `7` translates to \\$↖\\$

Draw \\$3\\$ (\\$b=2\\$) characters (`"222"`) in direction `7↖`:

```
01010
10101
01210
10121
01012

```

After which we mirror this multi-line string both horizontally and vertically, after which it is output implicitly as our result.

See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.

# Answer
> 3 votes
# Jelly, 19 bytes

```
^þ
ÇḂ+UṚŒḄŒBɓa‘{Ç¬Ḥ

```

Try it online!

With some inspiration from hyper-neutrino's Vyxal solution.

```
^þ     Monadic helper link:
 þ     Table the (range from 1 to the) argument with itself by
^      XOR.
  Ḃ    The parities of the cells form a checkerboard,
  ¬    and the diagonal consists of zeroes while the rest is truthy.

ÇḂ+UṚŒḄŒBɓa‘{Ç¬Ḥ    Dyadic main link:
             Ç¬     Generate an identity matrix of size
         ɓ          b
           ‘        + 1
          a {       or 0 if b is 0,
               Ḥ    then double it.
  +                 Add that to (the top left corner of)
ÇḂ                  an a by a checkerboard,
   UṚ               rotate the result 180 degrees,
     ŒḄŒB           and palindromize it in both dimensions.

```

# Jelly, ~~25~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes

```
^þ
ÇḂ+ŒḄŒBðÇUoḶ>¥*¬ḤU

```

Try it online!

That feels better. \\$a\\$ on the left, \\$b\\$ on the right.

```
^þ     Monadic helper link:
 þ     Table the (range from 1 to the) argument with itself by
^      XOR.
  Ḃ    The parities of the cells form a checkerboard,
  ¬    and the diagonal consists of zeroes while the rest is truthy.

ÇḂ+ŒḄŒBðÇUoḶ>¥*¬ḤU    Dyadic main link:
        Ç             Generate an a by a matrix of zeroes on the diagonal and nonzeroes elsewhere.
         U            Mirror it,
          o           and replace zeroes with corresponding elements from:
           Ḷ ¥        for each 0 .. a-1,
            >         is it greater than b?
              *       Raise each to the bth power,
               ¬      logically negate,
                Ḥ     double,
                 U    and mirror back.
  +    ð              Add that to
ÇḂ                    an a by a checkerboard,
   ŒḄŒB               then palindromize in both dimensions.

```

# Answer
> 3 votes
# MATL, ~~22~~ 21 bytes

```
_Zvt&+oy&=bitg+>&+>E+

```

Inputs are `a`, then `b`.

**Try it online!**

### Explanation

This uses inputs `3`, `1` as an example. The stack contents are shown in each step. The stack is shown upside down, with the top (i.e. most recent) element down.

```
_Zvt % Implicit input: a. Symmetric range [a a-1 ... 2 1 2 ... a-1 a]. Duplicate
     % STACK: [3 2 1 2 3],
              [3 2 1 2 3]
&+   % Duplicate. Add to itself transposed, elementwise with broadcast
     % STACK  [3 2 1 2 3],
              [6 5 4 5 6
               5 4 3 4 5
               4 3 2 3 4
               5 4 3 4 5
               6 5 4 5 6]
o    % Modulo 2, elementwise. Gives checkered matrix
     % STACK: [3 2 1 2 3],
              [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
y    % Duplicate second-top element
     % STACK: [3 2 1 2 3],
              [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [3 2 1 2 3]
&=   % Equal? to itself transposed, elementwise with broadcast. Gives "X" matrix
     % STACK: [3 2 1 2 3],
              [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1]
b    % Bubble up third-top element
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1],
              [3 2 1 2 3]
i    % Input: b
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1],
              [3 2 1 2 3],
               1
tg+  % Duplicate, convert to logical, add. This converts positive b into b+1
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1],
              [3 2 1 2 3],
               2
>    % Greater than?, elementwise
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1],
              [1 0 0 0 1]
&+   % Add to itself transposed, elementwise with broadcast
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [1 0 0 0 1]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               1 0 0 0 1],
              [2 1 1 1 2
               1 0 0 0 1
               1 0 0 0 1
               1 0 0 0 1
               2 1 1 1 2]
>    % Greater than?, elementwise. Equivalent to "and not". This trims the "X" matrix
     % STACK: [0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0
               1 0 1 0 1
               0 1 0 1 0],
              [0 0 0 0 0]
               0 1 0 1 0
               0 0 1 0 0
               0 1 0 1 0
               0 0 0 0 0],
E+   % Multiply by 2, element-wise. Add, element-wise. Implicit display
     % STACK: [0 1 0 1 0
               1 2 1 2 1
               0 1 2 1 0
               1 2 1 2 1
               0 1 0 1 0]

```

# Answer
> 3 votes
# , 40 bytes

```
((2|+/~)@]+2**@[*=/~@]*(>:]*=/~))|@i:@<:

```

Try it online!

# Answer
> 3 votes
# Jelly, 18 bytes

```
_þµṂ>Ɠa~¤×¬Ḥ+ḂŒBŒḄ

```

Try it online!

-1 from caird, who noted that I could get rid of a backtick by reading `b` from stdin.

```
                For inputs (a, b):
_þµ              Make a subtraction table over [1..a], and operate on that.
    Ṃ             Get the minimum row: this is always [1-a, 2-a ... 0].
     >Ɠa~¤        Which elements are greater than (b and ~b)?
                  For example for (5, 2): Ṃ    → [-4, -3, -2, -1,  0]
                                          Ṃ>-3 → [ 0,  0,  1,  1,  1]
          ×¬      Multiply this vector by the a×a identity matrix "¬table"
            Ḥ     and double the result (generating the 2s)
             +Ḃ   then add to an a×a checkerboard of 1s "table % 2":

                    0 0 0 0 0   0 1 0 1 0   0 1 0 1 0
                    0 0 0 0 0   1 0 1 0 1   1 0 1 0 1
                    0 0 2 0 0 + 0 1 0 1 0 → 0 1 2 1 0
                    0 0 0 2 0   1 0 1 0 1   1 0 1 2 1
                    0 0 0 0 2   0 1 0 1 0   0 1 0 1 2

ŒBŒḄ              Finally, palindromize both ways to make the full output.

```

# Answer
> 2 votes
# Zsh, ~~127~~ ~~116~~ 112 bytes

```
R=({1..$[c=2*$1-1]})
for i ($R)(for j ($R)S+=$[(i==j)|(j+i==c+1)?$2==0?0:${$((i-$1))/\-/}>$2?0:2:(i+j)%2]
<<<$S)

```

Attempt this Online! ~~116 bytes~~ ~~127 bytes~~

I used bits of the X without Y problem.
@pxeger saved 4 bytes!

**Description**

```
Using `a = $1` and `b = $2` as defined in the question...

R=({1..X})               define array R as a sequence from 1 to expression X
c=$2*$1-1                size of matrix
for i.. for j..          iterate rows, columns
S+=$[...]                add a digit to S, per the logic in [...]
(i==j)|(j+i==c+1)?...    are we on a diagonal? if so, do ...
:(i+j)%2                 otherwise, fill the matrix with 1s and 0s
$2==0?0                  if b is 0, then default to 0 on the diagonal
:${$((i-$1))/\-/}>$2?0:2 if abs(i-a) > b then put 0 on the diagonal, otherwise 2

```

# Answer
> 2 votes
# Ruby, 70 bytes

```
->a,b{(r=1-a...a).map{|x|r.map{|y|x*x==y*y&&x*x<=b*b&&b>0?2:(x+y)%2}}}

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~118~~ \\$\cdots\\$ ~~106~~ 103 bytes

```
i;f(a,b){for(a*=2,i=--a*a;i--;)printf("%d%c",!b|b<abs(a/2-i/a)||i/a-i%a&&i/a+1+i%a-a?i%2:2,i%a?32:10);}

```

Try it online!

*Saved 3 bytes thanks to ceilingcat!!!*

# Answer
> 2 votes
# Vyxal, 24 bytes

```
:±+ʁ:±†vǔd$ʁ:v+∷+2(ṘømÞT

```

Try It Online!

-3 bytes thanks to lyxal
-1 byte thanks to Unrelated String

```
:±+ʁ:±†vǔd$ʁ:v+∷+2(ṘømÞT     Full Program; take in order b, a
:                            duplicate b
 ±                           sign
  +                          add (0 if b is 0, otherwise b+1)
   ʁ                         range (0..x-1)
    :                        duplicate
     ±                       sign ([0, 1, 1, ..., 1] of length 0 / b+1)
      †                      logical NOT - [1, 0, 0, ..., 0]
       vǔ                    vectorized rotate; identity matrix of size 0 / b+1
         d                   double; [2, 0, 0], [0, 2, 0], [0, 0, 2]
          $                  swap a to TOS
           ʁ                 range; 0..a-1
            :                duplicate
             v+              add each; addition table; [2, 3, 4], [3, 4, 5], [4, 5, 6]
               ∷             parity; checkerboard of size a with 0 in top-left
                +            add the two matrices together
                  2(....)    repeat twice
                    Ṙ        reverse (flip vertical)
                     øm      palindromize (reflect vertical; do not copy middle)
                       ÞT    transpose

```

# Answer
> 2 votes
# Excel, 97 bytes

```
=LET(x,SEQUENCE(A1*2-1)-A1,y,TRANSPOSE(x),IF(MOD(x+y,2),1,IF((x-y)*(x+y)+(B1=0)+(ABS(x)>B1),,2)))

```

Link to Spreadsheet

## Explanation

```
=LET(x,SEQUENCE(A1*2-1)-A1, # [-a..a] vertical
y,TRANSPOSE(x),             # [-a..a] horizontal
IF(MOD(x+y,2),1,            # if x+y mod 2 <> 0 then 1
  IF((x-y)*(x+y)+(B1=0)+(ABS(x)>B1),,2)))
                   # else if (x<>y and x<>-y) or b = 0 or abs(x) > b then 0 else 2

```

# Answer
> 2 votes
# Julia, ~~336~~ ~~271~~ ~~195~~ 187 Bytes

v4, and thanks for the help!

```
function x(a,b)
s=(2*a-1)
h = zeros(Int8,(s,s))
h[2:2:s^2].=1
if b!=0;h[a,a]=2end
for i in range(1,stop=min(b,a-1))
h[a+i,a+i]=2
h[a-i,a-i]=2
h[a-i,a+i]=2
h[a+i,a-i]=2
end
return(h)
end

```

old:

```
function cross(a,b)
    h = zeros(Int8,((2*a-1),(2*a-1)))
    h[2:2:(2*a-1)^2] .= 1
    c = (Int8((2*a-1)/2+0.5), Int8((2*a-1)/2+0.5))
    h[c[1],c[2]] = 2
    for i in range(1,stop=min(b,a-1))
        h[c[1]+i,c[2]+i] = 2
        h[c[1]-i,c[2]-i] = 2
        h[c[1]-i,c[2]+i] = 2
        h[c[1]+i,c[2]-i] = 2
    end
    return(h)
end

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~87~~  84 bytes

Expects `(a)(b)`.

```
a=>b=>[...Array(a+--a)].map((_,y,A)=>A.map(_=>x+y&1|(x*x/b<=b&x*x--==y*y)*2,y-=x=a))

```

Try it online!

### Note

We do `x*x/b<=b` rather than `x*x<=b*b` so that `x*x/b` evaluates to `NaN` when both \\$x\\$ and \\$b\\$ are \\$0\\$. This makes the condition fail as expected for this edge case without the need for an explicit test on \\$b\\$.

# Answer
> 1 votes
# TI-Basic, 80 bytes

```
Prompt A,B
identity(2A-1→[A]
For(I,1,2A-1
For(J,1,2A-1
remainder(I+J,2)+2max(abs({I,J}-A)≤B and B)max(I={J,2A-J→[A](I,J
End
End

```

+1 byte if not ran on a TI-84+/SE with the 2.53 MP OS or above by replacing `remainder(I+J,2)` with `2fPart(.5(I+J))`.

Output is stored in `[A]`.

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

Prompts for a then b:

```
(s⊖(s←.5×b-a)⌽z↑(b≠1)×2×m∨⌽m←n∘.=(n←⍳b←(2×b←⎕)+1))+(z←a,(a←(2×⎕)-1))⍴0 1

```

Explanation:

```
(z←a,(a←(2×⎕)-1))⍴0 1 create the 0 1 checkerboard matrix defined by a

2×m∨⌽m←n∘.=(n←⍳b←(2×b←⎕)+1)) create the 2s diagonals defined by b

(b≠1)× filter the case where b=0

z↑ pad the diagonals matrix to the same size as the checkerboard matrix

s⊖(s←.5×b-a)⌽ centre the diagonals in the padded diagonals matrix.

The two matrices are then summed together.

```

Try it online! Thanks to Dyalog Classic

# Answer
> 0 votes
# C (clang), 92 bytes

```
z,i;f(a,b){for(i*=z=i=2*a-1;i;)printf("\n%d"+!!(i--%z),i%~z&&i%~-z||(i/z-~-a)/~b|!b?i%2:2);}

```

Try it online!

Function printing to stdout.
Leading line can be removed at the cost of 1 Byte.

```
z : side length
i : characters counter(backwards)
f(a,b){
for(i*=z=i=2*a-1;i;)    - initialize variables and itetate backwards until 0
printf("\n%d"+!!(i--%z) - prints:
         > a newline if i%z == 0
           > the number obtained by expression below at each iteration (decrements i)

i%~z&&i%~-z        - false on diagonals
||(i/z-~-a)/~b|!b  -  false on horizontal window
     * for example f(3,1)

  01110    11111   11111
  10101    00000   10101
  11011 || 00000 = 11011
  10101    00000   10101
  01110    11111   11111

?i%2:2    - draw board on 1's
                 2's on zeros

```

# Answer
> 0 votes
# Matlab, 79 bytes

```
m=zeros(2*a-1);
m(2:2:end)=1;
for i=a-b:a+b
m(i,i)=2*(b>0);end
max(m,flipud(m))

```

Only make one diagonal of twos and generate the antidiagonal by maxing with the flipped matrix. The `2*(b>0)` was my shortest way to take care of the `b=0` edge case.

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


# Question
Title: Write a program to output the nth fibonacci number in quinary
Quinary is like binary, except that 1 is represented by the text of the program, and 0 is represented as the backwards text of the program.

The Fibonacci Sequence is the well known sequence

F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2)

Write a program that takes some input n and outputs the nth fibonacci number in quinary.

Standard code golf rules apply.

# Answer
# CJam, 30 bytes

```
{s"_~"+UXri{_@+}*;2bWfe|\f%}_~

```

Try it online!

### How it works

```
{                          }_~  Define a code block, and push and execute a copy.
 s                              Convert the original code block to a string.
  "_~"+                         Append "_~" to the string.
       UXri                     Push 0, 1 and an integer N from STDIN.
           {   }*               Do N times:
            _                     Push a copy of the topmost integer.
             @                    Rotate the bottom-most integer on top of it.
              +                   Push the sum of the copy and the rotated integer.
                 ;              Discard the topmost stack item, i.e., F(N+1).
                  2b            Convert the remaining stack item to base 2.
                    Wfe|        Logical OR all binary digits with -1.
                                This turns 0's into -1's.
                        \f%     For each binary digits A, take each Ath item of the
                                generated string.
                                This pushes the string itself for A = 1, and the
                                reversed string for A = -1.

```
> 2 votes

# Answer
# Python, 226 bytes

```
s='s=%r;a,b=0,1;exec"a,b=b,a+b;"*input();print"".join(map(lambda i:(s%%s)*int(i)+(s%%s)[::-1]*(1-int(i)),bin(a)[2:]))';a,b=0,1;exec"a,b=b,a+b;"*input();print"".join(map(lambda i:(s%s)*int(i)+(s%s)[::-1]*(1-int(i)),bin(a)[2:]))

```

It's quite a heavy modification to the standard Python Quine. It uses `a,b=0,1;exec"a,b=b,a+b;"` to generate Fibonacci numbers.
> 2 votes

# Answer
# , 24 chars / 44 bytes

```
⟮Мȫïⓑⓢⓜ+$?(a=ɕṡ+ᶈ0):aᴙ)⨝

```

`Try it here (Firefox only).`

# Explanation

Standard quine framework: `⟮ɕṡ+ᶈ0`

```
⟮Мȫïⓑⓢⓜ+$?(a=ɕṡ+ᶈ0):aᴙ)⨝ // implicit: ï=input
⟮                           // copy block start
 Мȫï                       // get nth Fibonacci number
    ⓑⓢⓜ                  // convert to binary, split along chars, map
         +$?               // is mapitem truthy?
            (a=ɕṡ+ᶈ0)      // if so, replace w/ quine as is
                     :aᴙ)  // else replace w/ reverse quine
                         ⨝ // join
                           // implicit output

```
> 0 votes

# Answer
# Javascript ES6, 121 bytes

```
$=_=>[...(a=`$=${$};$()`,f=x=>x>1?f(x-1)+f(x-2):x)(prompt()).toString(2)].map(x=>+x?a:[...a].reverse().join``).join``;$()

```

I'm looking for ways to shorten the Fibonacci function...
> 0 votes

# Answer
# Python 3.8 (pre-release), 113 bytes

```
exec(s:="f=lambda x:x<2or f(x-1)+f(x-2)\nfor i in f'{f(int(input())):b}':print(('exec(s:=%r)'%s)[::2*int(i)-1])")

```

Try it online!
> 0 votes

---
Tags: code-golf, quine, fibonacci
---


title: Inverse n-bonacci sequence

text:
# Question
Title: Inverse n-bonacci sequence
We all know about the Fibonacci sequence. We start with two 1s and keep getting the next element with the sum of previous two elements.

n-bonacci sequence can be defined in similar way, we start with `n` 1s and take the sum of previous `n` elements to get the next element.

**Challenge**

Given a positive integer `m` \> 1, output the smallest `n` of the n-bonacci sequence that contains `m`, and the index of `m` in that sequence (either 0 or 1 indexed).

There should be two integers in output, one will be which n-bonacci sequence the number is in, and another for the 0 or 1-indexed index in it.

I/O is flexible, you may choose to output either list, string or two numbers with optional trailing whitespace.

**Test cases**

First integer is which n-bonacci sequence and second is 0-indexed position:

```
2 -> 2,2
3 -> 2,3
4 -> 4,4
5 -> 2,4
6 -> 6,6
7 -> 4,5
8 -> 2,5
9 -> 3,5
10 -> 10,10
11 -> 6,7
12 -> 12,12
13 -> 2,6
14 -> 14,14
15 -> 8,9
16 -> 16,16
17 -> 3,6
18 -> 18,18
19 -> 10,11
20 -> 20,20
21 -> 2,7
22 -> 22,22
23 -> 12,13
24 -> 24,24
25 -> 4,7
26 -> 26,26
27 -> 14,15
28 -> 28,28
29 -> 8,10
30 -> 30,30
31 -> 3,7
32 -> 32,32
33 -> 5,8
34 -> 2,8
35 -> 18,19
36 -> 36,36
37 -> 10,12
38 -> 38,38
39 -> 20,21
40 -> 40,40
41 -> 6,9
42 -> 42,42
43 -> 22,23
44 -> 44,44
45 -> 12,14
46 -> 46,46
47 -> 24,25
48 -> 48,48
49 -> 4,8
50 -> 50,50
51 -> 26,27
52 -> 52,52
53 -> 14,16
54 -> 54,54
55 -> 2,9
56 -> 56,56
57 -> 3,8
58 -> 58,58
59 -> 30,31
60 -> 60,60
61 -> 16,18
62 -> 62,62
63 -> 32,33
64 -> 64,64
65 -> 5,9
66 -> 66,66
67 -> 34,35
68 -> 68,68
69 -> 18,20

```

This is so shortest answer wins.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 64 bytes

```
LinearRecurrence[o=1~Table~n,o,#+1]~Table~{n,#}~FirstPosition~#&

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 17 bytes

```
Lã.ΔR`©Å1λè®L₆O}Q

```

Try it online! or Try all cases!

```
L                   # range from 1 to the input
 ã                  # all pairs [n,k] where n and k are from the range
                    # this is sorted by the first element
  .Δ                # find the first such pair which satisfies:
    R`              #   reverse and splat, such that n is above k on the stack
      ©             #   store n in the register
       Å1           #   a list of n 1's as a start for the n-bonacci sequence
         λè    }    #   get the kth element of the recursively defined sequence
           ®L       #     push the range [1..n]
             ₆      #     for each of those numbers i, get the ith previous value
              O     #     sum those values
                Q   #   is this equal to the input

```

# Answer
> 5 votes
# Charcoal, ~~50~~ 42 bytes

```
Ｎθ≔Ｅ⊕θＥι¹ηＦθＵＭη∧κ⊞ＯκΣ…⮌κλ≔§Φη№ιθ⁰ζＩ⟦⌕ηζ⌕ζθ

```

Try it online! Link is to verbose version of code. Edit: Saved 8 bytes by using @Bubbler's idea of calculating the first `n+i` elements of each `i`-bonacci series. Explanation:

```
Ｎθ

```

Input `n`.

```
≔Ｅ⊕θＥι¹η

```

Create a list of `n+1` lists of `1`s.

```
Ｆθ

```

Repeat `n` times...

```
ＵＭη∧κ⊞ＯκΣ…⮌κλ

```

... append the sum of the latest `k` terms to each list.

```
≔§Φη№ιθ⁰ζ

```

Find the first list which contains `n`.

```
Ｉ⟦⌕ηζ⌕ζθ

```

Output its index and the index of `n` in the list.

# Answer
> 5 votes
# Jelly, 12 bytes

```
b©1ḋ®;Ɗ¡)Uœi

```

Try it online!

Multidimensional first index rocks again. Outputs `(which n-bonacci sequence, 1-based index in it)`.

### How it works

```
b©1ḋ®;Ɗ¡)Uœi    Full program; Input = n, the number to search for
        )       For each of i=1..n,
b©1ḋ®;Ɗ¡        Generate i-bonacci sequence up to n+i terms:
b©1               i copies of 1; save it to register
       ¡          Repeat n times:
   ḋ®;Ɗ             Prepend the sum of first 3 terms to the current list
         U      Reverse each list
          œi    Find the multi-dimensional index of the first occurrence of n

```

# Answer
> 4 votes
# JavaScript (V8), 105 bytes

```
a=>{for(i=1;i++;)for(j=Array(i).fill(1);(k=eval(j.slice(-i).join`+`))<=a;h=j.push(k))if(k==a)return[i,h]}

```

Try it online!

## Explanation

```
a => {                            // Defining a function that takes a single argument
  for (i = 1; i++; )              // With the variable i (sequence #) infinitely increasing
    for (                         // Iterate...
      j = Array(i).fill(1);       // Initialise j to array of 1s
      (k =                        // Assigning k to...
        eval(j.slice(-i).join`+`) // Sum of last i elements of j
      ) <= a;                     // Continue with this as long as we haven't passed a number greater than the input
      h = j.push(k)               // Push k to j, and assign h to index in sequence
    ) if( k == a)return[i,h]      // If we've found it, return
}

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 82 bytes

returns 1-indexed

```
(k=2;While[(l=LinearRecurrence[s=1~Table~k,s,#+1])~FreeQ~#,k++];{k,l~Position~#})&

```

Try it online!

# Answer
> 3 votes
# Python 3, 105 bytes

```
f=lambda n,b=2,p=1,l=[1,1]:l[-1]==n and(b,p)or f(*[n]+[[b,p+1,l+[sum(l[-b:])]],[b+1,b,[1]*-~b]][l[-1]>n])

```

Try it online!

may reach recursion limit, 0-indexed

**Explanation**

Simple recursive search algorithm

* `f` is the recursive function which takes an integer `n`
* Three variables are defined at start

+ `b` is the current number of n-bonacci sequence we are trying, which is initially Fibonacci aka 2
    + `p` is the 0-indexed position of current value we are trying which is also set to 1
    + `l` is the list from which will contain the `b`-bonacci numbers, which is for Fibonacci is `[1,1]`
* If the tail/last element of `l` is equal to `n` (tail of `l` is the last computed `b-bonacci` number)

+ We found our element so we return `b` and `p`
* Else

+ (We hold the possible values for the new recursive call as 2 lists in a list and index them with condition, get it and unpack on `f` to make recursive call)
    + If the tail of `l` is greater than `n`

    - Which means we have exceeded the limit and `n` is not in the current `b`-bonacci sequence, so
        - Make a recursive call with

        * `n` without any changes
            * `b` incremented by 1 to get to the next b-bonacci sequence
            * `p` as the old value of `b` because the search skips the 1s at the beginning so we need to offset by `b`
            * `l` as list of one more 1s (`b` minus 1 times)
    + If less than

    - We need to continue the search in current `b`-bonacci sequence
        - Make a recursive call with

        * `n` without any changes
            * `b` without any changes to continue the search
            * `p` increment by 1 to get to new index
            * Take `b` values from the tail of old `l` with negative indexing, sum them and append to old `l` to pass as new `l`

# Answer
> 3 votes
Lua's a terrible language for code-golfing by any standard, but it was still a ton of fun.

# Lua, 250 bytes

```
T=table.unpack function S(t,a)return#t==0 and a or S({T(t,2,#t)},a+t[1])end function f(n,s)a={}for c=1,s do a[c]=1 end::B::l=S({T(a,#a-s+1,#a)},0)if l==n then return s,#a end a[#a+1]=l if l<n then goto B end return f(n,s+1) endprint(f(io.read"*n",2))

```

# Lua, 280 bytes

```
function S(t,a)if #t==0 then return a end return S({table.unpack(t,2,#t)},a+t[1]) end function f(n,s)a={} for c=1,s do a[c]=1 end ::B:: l = S({table.unpack(a,(#a-s)+1,#a)},0)if l==n then return s,#a end a[#a+1]=l if l<n then goto B end return f(n,s+1)end print(f(io.read("*n"),2))

```

# Answer
> 2 votes
# Ruby, ~~81~~ 74 bytes

```
g=->x,y=2{s,n=[1]*y,0
s<<n=s[-y,y].sum while x>n
x<n ?g[x,y+1]:[y,s.size]}

```

Try it online!

* Saved 7Bytes thanks to @Dingus suggestions
* 1 indexed

```
g=-> x,y=2{  # recursive lambda testing each y-fib
               returning the first valid result
s,n=[1]*y,0  # s = current serie initialized to 1's
               n = next term

while x> n   # add terms up to x
=s[-y..-1].sum # which is sum of last y terms
s<<n end     # add it
x==n ?       # if last term is x
[y,s.size]   # return y and length
:g[x,y+1]}   # else try next y-fib

```

# Answer
> 2 votes
# JavaScript (Node.js), 77 bytes

```
m=>(h=i=>(g=(i,k=n)=>i<k||k&&g(--i)+g(i,k-1))(i)-m?h(i<m?++i:++n):[n,i])(n=2)

```

Try it online!

Very slow but a bit shorter.

---

# JavaScript (Node.js), 79 bytes

```
m=>(h=i=>(g=(i,k=n)=>t=i<k||k&&g(--i)+g(i,k-1))(i)-m?h(t<m?++i:++n):[n,i])(n=2)

```

Try it online!

A bit faster...

# Answer
> 1 votes
# C (gcc), <sup>~~139~~</sup> 130 bytes

```
t;*b;j;s;i;*f(n){b=calloc(n,8);for(t=*b=s=1;t;)for(b[i=s++]=1;t&&n/++i;t=b[i]-n)for(b[j=i]=0;j-->i-s;)b[i]+=b[j];*b++=s;*b=i;--b;}

```

Try it online!

Inputs integer \\$n\>1\\$.
Returns a pointer to an array \\$a\\$ where \\$a\[0\]=s\\$ (the sequence number) and \\$a\[1\]=i\\$ (the \\$0\\$-based index) of the first occurrence of \\$n\\$ in an \\$n\\$-bonacci sequence.

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

```
f=(n,i=k=2)=>(g=(i,h=j=>j&&g(--i)+h(j-1))=>v=i<k||h(k))(i)-n?f(n,v<n?i+1:!k++):[k,i]

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Classic), 62 bytes

```
{l←1+⍵⋄⊃(,∘.,⍨⍳l)/⍨⍵=,1⌽↑l{⍺{d←⍵⋄({⍵,+/⍵↑⍨-d}⍣(⍺-⍵))d⍴1}¨⍵}⍳l}

```

Try it online!

# Answer
> 0 votes
# , 92 bytes

```
function(m)while(F<-F+1)for(i in 0:m+1)if((T[i]=`if`(i>F,sum(T[i-1:F]),1))==m)return(c(F,i))

```

Try it online!

Returns 1-based indices.

---
Tags: code-golf, math, sequence, fibonacci
---


title: The ultimate inequality challenge

text:
# Question
Title: The ultimate inequality challenge
## Task

Given two positive integers `a`, `b` and a Unicode mathematical inequality symbol `c`, determine if `a c b` is true.

You many take the character or its Unicode codepoint for the input `c`. You may output your language's truthy/falsy values, or two distinct values for true and false respectively.

Standard rules apply. The shortest code in bytes wins.

## List of symbols to support

```
Symbol  |  Hex   |  Dec   |  Name
--------+--------+--------+-------------
<       |  003C  |  60    |  Less than
=       |  003D  |  61    |  Equal to
>       |  003E  |  62    |  Greater than
≠       |  2260  |  8800  |  Not equal to
≤       |  2264  |  8804  |  Less than or equal to
≥       |  2265  |  8805  |  Greater than or equal to
≮       |  226E  |  8814  |  Not less than
≯       |  226F  |  8815  |  Not greater than
≰       |  2270  |  8816  |  Neither less than nor equal to
≱       |  2271  |  8817  |  Neither greater than nor equal to

```

The last four symbols may look broken in Chrome. They are four symbols `<>≤≥` with slash overstrike, indicating negation.

## Truthy test cases

```
1 < 2
1 = 1
2 > 1
1 ≠ 2
2 ≠ 1
1 ≤ 1
1 ≤ 2
2 ≥ 1
1 ≥ 1
2 ≮ 1
1 ≮ 1
1 ≯ 1
1 ≯ 2
2 ≰ 1
1 ≱ 2

```

## Falsy test cases

```
1 < 1
2 < 1
1 = 2
2 = 1
1 > 1
1 > 2
1 ≠ 1
2 ≤ 1
1 ≥ 2
1 ≮ 2
2 ≯ 1
1 ≰ 1
1 ≰ 2
2 ≱ 1
1 ≱ 1

```

# Answer
> 19 votes
# JavaScript (ES6),  ~~58 45~~  42 bytes

*Saved 3 bytes thanks to @Neil*

Expects the Unicode code point for \\$c\\$. Returns \\$0\\$ or \\$1\\$.

```
(a,c,b)=>'14353426'[c%61%9]>>(a>b?2:b>a)&1

```

Try it online!

### How?

Each comparison character is assigned a 3-bit mask describing if it should be truthy for `a > b`, `a < b` or `a == b`.

```
 char. | code | meaning                           | > | < | = | mask
-------+------+-----------------------------------+---+---+---+------
   <   |   60 | Less than                         | 0 | 1 | 0 |  2
   =   |   61 | Equal to                          | 0 | 0 | 1 |  1
   >   |   62 | Greater than                      | 1 | 0 | 0 |  4
   ≠   | 8800 | Not equal to                      | 1 | 1 | 0 |  6
   ≤   | 8804 | Less than or equal to             | 0 | 1 | 1 |  3
   ≥   | 8805 | Greater than or equal to          | 1 | 0 | 1 |  5
   ≮   | 8814 | Not less than                     | 1 | 0 | 1 |  5
   ≯   | 8815 | Not greater than                  | 0 | 1 | 1 |  3
   ≰   | 8816 | Neither less than nor equal to    | 1 | 0 | 0 |  4
   ≱   | 8817 | Neither greater than nor equal to | 0 | 1 | 0 |  2

```

We store these masks in a 8-character lookup string whose index is computed by applying two consecutive modulos to the code point:

```
 code | mod 61 | mod 9 | mask
------+--------+-------+------
   60 |   60   |   6   |  2
   61 |    0   |   0   |  1
   62 |    1   |   1   |  4
 8800 |   16   |   7   |  6
 8804 |   20   |   2   |  3
 8805 |   21   |   3   |  5
 8814 |   30   |   3   |  5
 8815 |   31   |   4   |  3
 8816 |   32   |   5   |  4
 8817 |   33   |   6   |  2

```

# Answer
> 9 votes
# Python 2, 45 bytes

```
lambda a,o,b:o%83*45%555%16%6+1>>cmp(a,b)+1&1

```

Try it online!

Improved based on @Arnauld's answer, make sure to upvote him!

The bitmask here is a different from @Arnauld's answer because bit `0` and `1` are swapped. *As usual*, the lookup table is replaced by some cool magic numbers.

# Python 3, ~~51 48~~ 47 bytes

```
lambda a,o,b:o%83*45%555%16%6+1>>(a>b)+(a>=b)&1

```

Try it online!

---

# Python 2, ~~47~~ 46 bytes

```
lambda a,o,b:(cmp(a,b)==1-o*6%43%7%3)^o*3%58%3

```

Try it online!

Every operation can be expressed by `(cmp(a,b)==a)^b`. For example, `a<b` iff `(cmp(a,b)==-1)^0`. We then use some dirty magic numbers to compress a and b.

# Python 3, ~~51 49~~ 48 bytes

```
lambda a,o,b:((a<b)+(a<=b)==o*6%43%7%3)^o*3%58%3

```

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~34~~ ~~33~~ ~~24~~ ~~23~~ 18 bytes

```
•1P42•b3ôs61%èŠ.Sè

```

-9 bytes by porting *@ovs*' Python 3 answer, so make sure to upvote him!
-6 bytes thanks to *@Grimmy*.

Input of the character as codepoint integer. Input-order as `c,b,a`.

Try it online or verify all test cases.

**Explanation:**

```
•1P42•             # Push compressed integer 18208022
      b            # Convert it to binary 1000101011101010100010110
       3ô          # Split it in parts of size 3:
                   #  [100,"010",101,110,101,"010","001","011",0]
         s         # Take the first codepoint input
          61%      # Take modulo-61
             è     # Index it into the binary list (0-based and with wraparound)
              Š    # Triple-swap to take the next two inputs
               .S  # Compare them (-1 if a<b; 0 if a==b; 1 if a>b)
                 è # And use that to index into the triplet (where -1 is the last item)
                   # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?*) to understand why `•1P42•` is `18208022`.

# Answer
> 5 votes
# Python 3, ~~99~~ 82 bytes

*17 bytes saved thanks to @ovs!*

Uses the operator similarities `a<b <=> a≱b`, etc.

```
lambda a,o,b:[a<b,a>b,a<=b,a>=b,a==b,a!=b]['<≱>≰≤≯≥≮= ≠'.find(o)//2]

```

Try it online!

# Answer
> 5 votes
# Python 2, ~~42~~ ~~41~~ 38 bytes

Takes in as input two operands \\$ a \\$ and \\$ b \\$, and the operator \\$ c \\$ in codepoint form. Test cases *nicely borrowed* from @newbie.

```
lambda a,c,b:(cmp(a,b)+63)*c%1895%57&1

```

Try it online!

---

The idea is the same as @newbie's, generating pseudorandom numbers until they match the output. The `cmp` function returns `-1`, `0`, or `1` if the left argument is less, equal to, or greater than the right argument, respectively. And also because MathJax looks nice, here is the formula in MathJax:

$$ ((((\text{cmp}(a,b) + 63) * c) \bmod 1895) \bmod 57) \bmod 2 $$

# Answer
> 4 votes
# Python 3, ~~68~~ 59 bytes

Takes the unicode code point of the operator as input.

```
lambda a,o,b:[a==b,a>b,a<=b,a>=b,a<=b,a>b,a<b,a!=b][o%61%9]

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 50 bytes

```
{⍎('≥≤><',⍵)[⍵⍳⍨'≮≯≰≱',⍵]}

```

Try it online! (the test cases)

Dyalog APL supports many of those operators and a simple "eval()"  will handle them as given. This answer swaps the last four which are not supported `'≮≯≰≱'` with replacements that are supported, e.g. "not less than" becomes "greater than or equal to", then "eval()"'s the resulting string. Output is 1 for true, 0 for false.

(NB. on the score: It's only 26 characters which would be competitive, however because it has `≮≯≰≱` characters in it, it does not fit in a pre-existing 8-bit APL character set so must be scored with the UTF-8 byte count instead of the number of characters).

# Answer
> 3 votes
# QuadR, 34 bytes

```
⍎⍵
≮
≯
≰
≱
≥
≤
>
<

```

Try it online!

Simply replaces the redundant symbols with their simpler equivalents, and then evaluates as APL.

# Answer
> 3 votes
## Dyalog APL, 23 bytes.

```
⎕(⍎'=>≤≥≤><≠'[9|61|⎕])⎕

```

With Adám's assistance. Try it online! (the test cases)

Explained: The  are prompts for numeric input, it takes the numbers on the outsides, and the codepoint of the comparison operator in the middle. Codepoint modulo `|` 61 then 9 produces indices into the string `''[]` which pick the comparison operator to run. This maps the unsupported ones (≮ ≯ ≰ ≱) to their supported equivalents ("not less than" maps to "greater than or equal to", etc).

Code demonstrates an unusual APL feature: `1 (⍎'<') 2` where the string `'<'` evaluates  to a function which can be called in-place like any other `1 f 2` dyadic APL function call.

NB. I'm submitting this as a separate answer both because it's a different approach to my other APL answer, and because it does not contain the unsupported comparison characters in it, which means it fits in a pre-existing 8-bit APL character set, and can be scored as 1-byte-per-character instead of UTF-8 byte count, for a much lower score.

# Answer
> 2 votes
# Sledgehammer, 17 bytes

16.75, to be overly specific

```
⣕⢌⢲⢼⠴⢺⢟⢼⣑⣮⣊⠞⠀⢄⡕⡝⢥

```

There's no point in trying to read that, so here's the corresponding Mathematica code with a reasonable explanation:

```
ToExpression@StringReplace[ToString@FullForm@ToExpression@Input[],"ot"->"ot@"]

```

The code evaluates the expression first. Unfortunately, the  operator (and a few other similar ones) is not supported, and is kept verbatim. The code then rewrites the expression into a prefix-ish form (`NotGreaterEqual[1, 1]`), and replaces `ot` with `ot@`, turning `NotGreaterEqual[1, 1]` into `Not@GreaterEqual[1, 1]`, a call of the function `Not` on the result of `GreaterEqual`. Of course, since that was a string replacement, the result is then evaluated once again.

# Answer
> 1 votes
# Io, 90 bytes

Port of the Python answer.

```
method(a,o,b,list(a<b,a>b,a<=b,a>=b,a==b,a!=b)at("<≱>≰≤≯≥≮= ≠"findSeq(o)/2))

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 80 bytes

```
\d+
$*
≠
<>
≤|≯
<=
≥|≮
=>
≰
>
≱
<
^(1+)(<.?1\1|.?>(?!\1)|<?=>?\1$)

```

Try it online! Link includes test suite. Takes input as `acb`, but the test suite deletes spaces to make the input more readable. Explanation:

```
\d+
$*

```

Convert to unary.

```
≠
<>
≤|≯
<=
≥|≮
=>
≰
>
≱
<

```

Replace the Unicode operators with ASCII-based logical operators. The `=>` is reversed to make the final condition golfier.

```
^(1+)(<.?1\1|.?>(?!\1)|<?=>?\1$)

```

Match the first number, then check whether one of the relations can be fulfilled.

* If the character after the first number is a `<`, then after an optional `>` or `=`, then to fulfil this relation the second number needs to equal 1 or more than the first number.
* If after an optional `<` or `=`, there is a `>` before the second number, then to fulfil this relation the second number must not be at least equal to the first number.
* If after an optional `<` there is an `=` before an optional `>`, then to fulfil this relation the second number must be equal to the first number.

# Answer
> 1 votes
# C (gcc), 46 bytes

```
f(a,c,b){a="14353426"[c%61%9]>>(a>b?2:b>a)&1;}

```

Try it online!

Port of Arnauld's JavaScript answer.

# Answer
> 1 votes
# Vyxal `D`, 16 bytes

```
4ɾ8813+C`≥≤><`ĿĖ

```

Try it Online!

Luckily, Vyxal supports all but the last four characters as operations.

```
               Ė # Evaluate...
              Ŀ  # The input, with characters in...
       C         # The charcodes of
4ɾ               # 1...4
  8813+          # + 8813
              Ŀ  # Replaced...
        `≥≤><`   # with the cooresponding character

```

# Answer
> 0 votes
# Charcoal, 38 bytes

```
Ｎθ≔Ｉ§”←⧴LH⎚G₂ⅉυ”℅ＳηＮζ⁼§⟦‹θζ⁼θζ›θζ⟧η÷η³

```

Try it online! Link is to verbose version of code. Takes input as `a c b` and outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:

```
Ｎθ

```

Input `a`.

```
≔Ｉ§”←⧴LH⎚G₂ⅉυ”℅Ｓη

```

Input `c` and cyclically look up its ordinal in the compressed string `__20__345___02531_` (the `_`s are arbitrary; the linked code uses spaces) and save its value.

```
Ｎζ

```

Input `b`.

```
⁼§⟦‹θζ⁼θζ›θζ⟧η÷η³

```

Make a list of the comparisons `a<b`, `a=b`, `a>b`, cyclically index using the `c` value, and negate the result if the `c` value is less than `3`.

---
Tags: code-golf, math, decision-problem
---