title: Draw the Swiss Flag

text:
# Question
Title: Draw the Swiss Flag
**Task:** Output the Swiss flag.

Happy Swiss National Day / Schweizer Bundesfeiertag / Fête nationale suisse / Festa nazionale svizzera / Fiasta naziunala svizra!

**Details:** The flag consists of a white (`#FFFFFF`) cross on a red (`#FF0000`) background. The cross consists of a 6x6 square with arms of size 6x7 glued to each side. The cross is in the center of the 32x32 square background having a distance of 6 units to each side. (Source)

The output size can be chosen by the participant, but the image must exactly match these proportions, this means its size must be a multiple of 32.

A minimal version would look like so:

# Answer
## SVG (HTML5), ~~94~~ ~~83~~ ~~82~~ 64 bytes

```
<svg><path d=M0,0V32H32V0M6,13h7V6h6v7h7v6H19v6H13V19H6 fill=red
```

Saved 2 bytes thanks to @ThePirateBay. Saved 1 byte thanks to @ATaco. Saved 18 bytes thanks to @CraigAyre pointing out that a 32×32 image was acceptable. As pointed out by @Shaggy, this assumes your default background is white; add 22 bytes for a flag that works on any background:

```
<svg><path d=M0,0V32H32V0 fill=red /><path d=M6,13h7V6h6v7h7v6H19v6H13V19H6 fill=#FFF
```
> 40 votes

# Answer
# x86-16 Machine Code for DOS, 43 bytes

```
               ; Draw 32x32 red square
B8 0C 28          mov  ax, 0x0C28   ; AL == color red, AH == set pixel function
B9 00 1F          mov  cx, 31
               DrawBox:
BA 00 1F          mov  dx, 31
               DrawRow:
CD 10             int  0x10
4A                dec  dx
75 FB             jnz  DrawRow
E2 F6             loop DrawBox

               ; Draw the interior white cross
B0 0F             mov  al, 0x0F    ; high byte already set
B1 06             mov  cl, 6       ; high byte already 0
               DrawCross:
B2 0D             mov  dl, 13      ; high byte already 0
               DrawCrossInner:
CD 10             int  0x10        ; plot CX, DX
87 D1             xchg dx, cx
CD 10             int  0x10        ; plot DX, CX
87 D1             xchg dx, cx
42                inc  dx
80 FA 12          cmp  dl, 13+6
75 F2             jne  DrawCrossInner
41                inc  cx
80 F9 19          cmp  cl, 6+(32-6-6)
75 EA             jne  DrawCross

C3                ret

```

The above code is designed to be assembled as a COM file and then run under DOS. It invokes the ROM BIOS video services to plot the individual pixels of the flag, forming a 32×32 representation of the Swiss flag in the upper-left corner of the screen.

The code assumes that the video mode is already set to mode 0x13, which also means that it requires a VGA display. Other video modes could be used, but requiring VGA gives you two things: (1) square pixels, and (2) a default palette that includes a true 100% red (`0xFF0000`) (meaning you don't have to waste bytes changing the palette colors). Before running this program, you will therefore need to switch your display to mode 0x13; the following code is all you need to do that:

```
mov  ax, 0x13
int  0x10

```

The code makes no other assumptions, and should run on any x86-compatible hardware under a DOS-compatible operating system.

However, the program terminates immediately after drawing the flag, so the DOS prompt will normally be re-printed at the top-left corner of the screen, covering up the top few lines of the flag. Therefore, if you want to marvel at the true output, you need to hang/pause the system before it `RET`urns. Here's a screenshot of what that looks like, running in a FreeDOS virtual machine:

It might be possible to golf this down further by writing pixel data directly to the video buffer, especially since I'm already assuming mode 0x13. I haven't tried that yet. `INT 0x10` is already a pretty short instruction, *but* if I can use the one-byte string instructions to write pixel data directly to memory, then that could result in a significant code savings.
> 34 votes

# Answer
# MATL, 29 bytes

```
2Y66t&Y"OJQht3$)6thYaQK7hBoYG

```

Try it at **MATL Online!**

### Explanation

```
2Y6     % Push predefined literal: 3×3 matrix [0 1 0; 1 1 1; 0 1 0]
6t&Y"   % Repeat each entry 6 times in the two dimensions. Gives an 18×18 matrix
OJQh    % Push [0 1j+1]. Used as an index, this means [0 1 ... end+1]. Indexing
        % is 1-based and modular, so 0 is the same as end
t3$)    % Apply that index in the two dimensions. This extends by 1 entry in
        % each dimension, so that the arms have length 7. Gives a 20×20 matrix
6thYa   % Pad with 6 zeros in the two dimensions. Gives a 32×32 matrix
Q       % Add 1. The matrix now contains values 1 (will become red) and 2 (white)
K7hBo   % Convert array [4 7] to binary. Gives [1 0 0; 1 1 1], to be used as
        % colormap. First row is red, second is white
YG      % Show image using colormap

```
> 21 votes

# Answer
# Java 8, 246 + 42 = 288 bytes

*Thanks to @Aaron for -64 bytes.*
*-4 bytes by outputting to file `a` without extension.*

```
import java.awt.*;import java.awt.image.*;
x->{BufferedImage i=new BufferedImage(32,32,1);Graphics g=i.getGraphics();g.setColor(Color.RED);g.fillRect(0,0,32,32);g.setColor(Color.WHITE);g.fillRect(13,6,6,20);g.fillRect(6,13,20,6);javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));}

```

A lamba expression that can be assigned to a functional interface method that throws an exception. Creates an image file named `a` (an image file) in the directory running this file.

Surrounding code used to run it: Try it online!

## Ungolfed

```
x->{
    BufferedImage i=new BufferedImage(32,32,1);
    Graphics g=i.getGraphics();
    g.setColor(Color.RED);
    g.fillRect(0,0,32,32);
    g.setColor(Color.WHITE);
    g.fillRect(13,6,6,20);
    g.fillRect(6,13,20,6);
    javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));
}

```

## Result

Grid provided by the IntelliJ IDEA image preview (apparently).
> 17 votes

# Answer
# Excel VBA, ~~86~~ ~~85~~ 79 Bytes

## Code

Anonymous VBE immediate window function that takes no input and outputs the Swiss flag onto the range `[A1:F32]` of the `ActiveSheet` object. This works by first making the cells square, then drawing the red region and finally drawing in the white cross.

```
Cells.RowHeight=48:[A1:AF32].Interior.Color=255:[G14:Z19,N7:S26].Interior.Color=-1

```

*Note that arrangements which that remove the step of coloring the "cross" of the Swiss flag after putting in the red background are actually longer than the above configuration, as they require at least 16 cell addresses, which coordinate to the 8 distinct regions of the flag*

-1 Byte thanks to @Greedo's for `RowHeight=48` over `ColumnWidth=2`

-6 Bytes thanks to @Greedo's for `-1` instead `rgbWhite`

## Output
> 17 votes

# Answer
## C++, SFML, ~~406~~ ~~399~~ 394 bytes

-2 bytes thanks to pdpi
-10 bytes thanks to Zacharý

SFML ( Simple and Fast Multimedia Library ) is a C++ library written to ease the developpement of video games and multimedia programs

The code :

```
#include<SFML\Graphics.hpp>
using namespace sf;int main(){for(RenderWindow t(VideoMode(128,128),"");t.isOpen();){t.clear();RectangleShape r({128.f,128.f});r.setFillColor(Color::Red);t.draw(r);r.setFillColor(Color::White);r.setPosition({24.f,52.f});r.setSize({80.f,24.f});t.draw(r);r.rotate(90);r.setPosition({76.f,24.f});t.draw(r);t.display();for(Event e;t.pollEvent(e);)if(!e.type)t.close();}}

```

The flag get displayed in a 128x128 window. Your OS have to be able to display a 128x128 window ( my Win8.1 can't display with smaller width )

**WARNING** : you may want to add these 2 lines of code : `t.setFramerateLimit(60);t.setVerticalSyncEnabled(true);`, so your CPU won't heat when you run the code. I did not put them in the original code for golfing reasons.
> 13 votes

# Answer
# Braindraw, 227 bytes (Non-competing) (Updated to actually work)

Ungolfed version (241 bytes)

```
r<<^++++++++[-^++++v]^[->>[>]>++++++++[-<++++>]<[<]<]>>[[-vv[v]-[^]^]>]vv<[<]>>>>>>>>>>>>>>vvvvvvg<<^^++++++[->>[>]>+++++[-<++++>]<[<]<]>>[[-vv[v]b-g-[^]^]>]<vv[<]><<<<<<<vvvvvvv<<^^++++++[-vv[v]++++++++++++++[^]^]vv[[->>[>]b[+]-g[+]-[<]<]v]

```

Lightly golfed version (227 bytes)

```
r<<^++++++++[-^++++v]^[->>[>]>++++++++[-<++++>]<[<]<]>>[[-vv[v]-[^]^]>]vv<[<]g>>>>>>>>>>>>vvvv++++++[->>[>]>+++++[-<++++>]<[<]<]>>[[-vv[v]b-g-[^]^]>]<vv[<]<<<<<<vvvvv<<++++++[-vv[v]++++++++++++++[^]^]vv[[->>[>]b[+]-g[+]-[<]<]v]

```

Braindraw is a programming language of my own design. As of 3:08 pm today, I do have a working interpreter and have checked that the program runs properly. However, the interpreter did not exist before this competition began, so I am not competing.

Braindraw is the same as Brainf\***, except that it operates on three two-dimensional arrays, rather than one one-dimensional array. These arrays are called r, g, and b, and act as the red green and blue color channels. The operator r moves the pointer to the red channel, etc etc. Up is ^, down is v.
> 13 votes

# Answer
# Mathematica, 83 bytes

```
R=Rectangle;Graphics[{Red,{0,0}~R~{32,32},White,{6,13}~R~{26,19},{13,6}~R~{19,26}}]

```

next one is from @ASCII-only (I thought it was a joke but it works!)

# Mathematica, 23 bytes

```
"CH"~CountryData~"Flag"

```

-10 bytes from @Jonathan Frech
> 11 votes

# Answer
# TI-BASIC (TI-84 Plus C(S)E only), 58 bytes

```
:For(A,0,31
:For(B,0,31
:Pxl-On(A,B,RED
:End
:End
:For(A,6,25
:For(B,13,18
:Pxl-Off(A,B
:Pxl-Off(B,A
:End
:End

```
> 10 votes

# Answer
# HTML + CSS, 15 + 117 bytes = 132 bytes

Using a flexbox wrapper with an `inset` `box-shadow`.

```
b{display:flex;box-shadow:red 0 0 0 6px inset;padding:2px;width:28px;flex-wrap:wrap}a{border:solid red 4px;margin:3px
```

```
<b><a><a><a><a>
```

---

# HTML + CSS, 18 + ~~139~~ ~~137~~ 122 bytes = 140 bytes

Previous answer using `border` and an intermediate flexbox wrapper with negative `margin`.

```
i,b,a{display:inline-flex}i{border:solid red 6px}b{margin:-4px;width:28px;flex-wrap:wrap}a{border:solid red 4px;margin:3px
```

```
<i><b><a><a><a><a>
```
> 9 votes

# Answer
# JavaScript + HTML, 99 + 13 = 112 bytes

*Saved 2 bytes thanks to user2428118*
*Saved 2 bytes thanks to Matheus Avellar*

JSFiddle

```
with(c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),clearRect(6,13,20,6),clearRect(13,6,6,20)
```

```
<canvas id=c>
```

---

# Pure JavaScript, ~~194~~ 129 bytes

JSFiddle

```
with(document.write`<canvas id=c>`,c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),clearRect(6,13,20,6),clearRect(13,6,6,20)
```
> 8 votes

# Answer
# GraphicsMagick (?), 96 bytes

```
gm convert -size 32x32 xc:red -fill #fff -draw "rectangle 13,6 18,25 rectangle 6,13 25,18" 1.bmp

```

Not sure how to golf with GM (should this be considered as a language?). Also not sure how to count bytes here...

With GM installed, type the given code in windows cmd, you will get an image with name `1.bmp`. You may want change double quote to single quote if you are using bash (it should work, but i had not tested this).

Thanks to Digital Trauma. use only one `-draw` save 8 bytes
> 7 votes

# Answer
# GFA BASIC (Atari ST),  ~~62~~  55 bytes

A manually edited listing in .LST format. All lines end with `CR`, including the last one.

```
DEFF 2
PB 0,0,31,31
DEFF 0
PB 13,6,18,25
PB 6,13,25,18

```

Expanded and commented:

```
DEFFILL 2         ! set fill color: default system color #2 is red (&H700)
PBOX 0,0,31,31    ! draw the red square
DEFFILL 0         ! set fill color: default system color #0 is white (&H777)
PBOX 13,6,18,25   ! draw a vertical white rectangle
PBOX 6,13,25,18   ! draw a horizontal white rectangle

```

###Output

The output is 32x32.

*NB: This is indeed using the 'white' color, although it's gray-looking on the emulator (and on the real thing as well, unless you turn the brightness quite high).*
> 7 votes

# Answer
# JavaScript (ES6) in HTML4(?), ~~178~~ 176 bytes

```
document.write('<table cellspacing=0>'+[...Array(32)].map((_,y,p)=>p.map((_,x)=>`<td bgcolor=${x>5&&x<26&&y>12&&y<19||y>5&&y<26&&x>12&&x<19?'#fff':'red'}>`).join``).join`<tr>`)
```

Yes! We do not need `<canvas>` nor `<svg>` or even `<img>`!

Thanks to Justin Mariner, save 2 bytes.
> 6 votes

# Answer
# Löve2D, ~~139~~ 138 Bytes

```
l=love g=l.graphics c=g.setColor r=g.rectangle f="fill"w=255 l.draw=loadstring"c(w,0,0)r(f,0,0,32,32)c(w,w,w)r(f,13,6,6,20)r(f,6,13,20,6)"

```

Saved one byte thanks to ThePirateBay

## Ungolfed

```
function love.draw()
    love.graphics.setColor(255,0,0)
    love.graphics.rectangle("fill",0,0,32,32)
    love.graphics.setColor(255,255,255)
    love.graphics.rectangle("fill",13,6,6,20)
    love.graphics.rectangle("fill",6,13,20,6)
end

```
> 5 votes

# Answer
# GIF, 97 Bytes

```
GIF87a    ð  ÿ  ÿÿÿ,         @„©Ëí£œ´Ú;ƒÞXmÞ!ŸŠcyŒj¨,àZê<Cô
:8nïtï‹é‚BJ1tì$1ËKSvb=_ÔªõŠe  ;

```

Cheap and byte-heavy, but worth it.

EDIT: Some characters aren't in the code above, here's a pastebin for the GIF's hexdump.

EDIT: compressed down to 97 bytes with online tool.
> 5 votes

# Answer
# Octave, ~~105 bytes~~ 73 bytes

*Note: line feeds added for clarity, not included in byte count*

```
x(32,32,3)=0;
x(:,:,1)=1;
x(7:26,14:19,:)=1;
x(14:19,7:26,:)=1;
imshow(x*255)

```

EDIT: thanks to flawr for saving quite a lot of bytes!

Here is the result on octave-online.net, thanks to sanchises
> 5 votes

# Answer
# Python 3, 190 bytes

Save output as `image.xpm` and open with your favorite text editor.

```
r=range;print('! XPM2\n32 32 2 1\nr c #FF0000\nw c #FFFFFF\n');d=[bytearray(b'r'*32)for _ in r(32)]
for i in r(20):
 for j in r(6):d[i+6][j+13]=d[j+13][i+6]=119
print(b'\n'.join(d).decode())

```

Try it online!

Output:

```
! XPM2
32 32 2 1
r c #FF0000
w c #FFFFFF

rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

```
> 5 votes

# Answer
# Perl 5 \+ `-p0513`, 80 bytes

```
print"P6 32 32 1",$_=($}="A..")x192,$\=($}x13 .1x18 .$}x13)x7,($}x6,1x60,$}x6)x6
```

Try it online!

Outputs a PBM file.

---

# Perl 5 \+ `-p0513 -M5.10.0`, 82 bytes

```
say"P6 32 32 1",map{($|--||"A..")x$_}205,@a=((18,26)x6,18),20,(54,14)x6,0,6,@a,205
```

Try it online!

Also outputs a PBM file. This is a slightly more interesting approach, but I can't get it to beat the above.

---

# Perl 5 \+ `-Mutf8 -p0513 -M5.10.0`, 149 bytes

```
say"",$\=($l=$"x32 ."
")x3,$_=(($s=$"x13).($}='█')x6 ."$s
")x3,$l=($"x=6).($a='▄'x7).$}x6 .$a.$",("
",$",$}x20,$")x2,"
",$l=~y;▄;▀;r

```

Try it online!

Output is to the terminal via ANSI escape codes and looks like this:

Proportions should be to scale based on one character space being two vertical 'pixels'.

You can preview the output by copying from TIO and pasting in here (this shows the control characters when hovered over the element).
> 5 votes

# Answer
## R, 171 140 bytes.

```
x = rep(c(6,13,19,26,19,13),e=2)
l=c(0,32)
par(bg="red",mar=0*1:4)
plot(0,0,'n',l,l,xaxs="i",yaxs="i")
polygon(x,c(x,x)[4:15],c="white",b=0)

```

(somewhat) ungolfed:

```
x <- rep(c(6,13,19,26,19,13),each=2)
y <- c(x,x)[4:15] # index by 3 positions
par(bg="red",mar=c(0,0,0,0)) # prepare the plot space
plot(0,type='n', xaxs="i",yaxs="i",xlim=c(0,32),ylim=c(0,32))
polygon(x,y,col="white",border=0)

```

Thanks to @gregor for saving some bytes

Run it!
> 5 votes

# Answer
# HTML + JavaScript (ES6), 13 + 112 = 125 bytes

```
C=c.getContext`2d`
C[s='fillStyle']='red'
C[r='fillRect'](0,0,32,32)
C[s]='#fff'
C[r](6,13,20,6)
C[r](13,6,6,20)
```

```
<canvas id=c>
```

# HTML + JavaScript (ES6), 13 + 114 = 127 bytes

```
with(c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),fillStyle='#fff',fillRect(6,13,20,6),fillRect(13,6,6,20)
```

```
<canvas id=c>
```
> 4 votes

# Answer
# Postscript, ~~301 286~~ 187 bytes

```
/m{moveto}def
/s{setrgbcolor}def
/r{rlineto}def
/c{closepath fill}def
1 0 0 s
0 0 m
0 320 r
320 0 r
0 -320 r
c
1 1 1 s
130 60 m
60 0 r
0 200 r
-60 0 r
c
60 130 m
0 60 r
200 0 r
0 -60 r c

```

Thanks to the anonymous editor who suggested a *99 byte reduction!*
> 4 votes

# Answer
# C# ~~265/266~~ 209 bytes

```
 using System;using c=System.Console;class P{static void Main(){for(int i=0,j;i<32;i++){for(j=0;j<32;j++){if((6<i&&i<26&&j>13&&j<19)||(6<j&&j<26&&i>13&&i<19))c.BackgroundColor=ConsoleColor.White;else c.BackgroundColor=ConsoleColor.Red;c.Write(" ");}c.WriteLine();}}}

```

I wrote "space" characters into console while changing Background Color. But if you think it is too tall and you count single character as 8 x 16 pixels, you simply double values near "j" like this (+ 1 byte and + `c.ReadKey();` so it stops):

```
  using System;using c=System.Console;class P{static void Main(){for(int i=0,j;i<32;i++){for(j=0;j<64;j++){if((6<i&&i<26&&j>26&&j<38)||(12<j&&j<52&&i>13&&i<19))c.BackgroundColor=ConsoleColor.White;else c.BackgroundColor=ConsoleColor.Red;c.Write(" ");}c.WriteLine();} c.ReadKey(); }}

```

56 bytes saved thanks to TheLethalCoder

```
 namespace System{using static Console;class P{static void Main(){for(int i=0,j;i<32;i++,WriteLine())for(j=0;j<32;Write(""))BackgroundColor=(ConsoleColor)((6<i&i<26&j>13&j<19)|(j++<26&i>13&i<19&6<j)?15:12);}}}

```
> 4 votes

# Answer
# Tikz, ~~145~~ 143 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz{\def~{)rectangle(}\fill[red](,~33,33);\fill[white](7,14~27,20)(14,7~20,27)}\end{document}

```

Here it is "ungolfed"

```
\documentclass[tikz]{standalone}
\begin{document}
\tikz{
\def~{)rectangle(}
  \fill[red](,~33,33);
  \fill[white](7,14~27,20)(14,7~20,27)
}\end{document}

```

Here it is ungolfed a little more

```
\documentclass[tikz]{standalone}
\begin{document}
\tikz{
  \fill[red](1,1)rectangle(33,33);
  \fill[white](7,14)rectangle(27,20)(14,7)rectangle(20,27)
}\end{document}

```

This makes 3 rectangles a big red one and two smaller white ones for the plus.

Here's what it looks like. It doesn't really look any different than the others.
> 4 votes

# Answer
# R, 112 bytes

```
par(bg=2,mar=0*1:4)
plot(0:32,0:32,'n',xaxs="i",yaxs="i")
rect(c(6,13),c(13,6),c(26,19),c(19,26),c="white",b=NA)

```

Though, to guarantee the aspect ratio, we need 5 more bytes for a total of 117:

```
par(bg=2,mar=0*1:4)
plot(0:32,0:32,'n',xaxs="i",yaxs="i",as=1)
rect(c(6,13),c(13,6),c(26,19),c(19,26),c="white",b=NA)

```

With lots of inspiration from Alex Axthelm's answer, and thanks to Rift for saving a few more bytes.
> 4 votes

# Answer
# R, 109 bytes

```
par(mar=0*1:4,bg=2,xaxs="i",yaxs="i")
frame()
rect(a<-c(6,13)/32,rev(a),b<-c(26,19)/32,rev(b),c="white",b=NA)

```

Uses `frame` to avoid presetting a plot, but default plotting region is on interval \[0,1\] instead of \[0,32\]. Also uses the fact that `rect` is vectorized. The default size of the plotting window is 7in x 7in. It outputs the following:

# R, 125 bytes

```
png()
par(mar=0*1:4,bg=2,xaxs="i",yaxs="i")
frame()
rect(a<-c(6,13)/32,rev(a),b<-c(26,19)/32,rev(b),c="white",b=NA)
dev.off()

```

Default for `png` is a square of 480x480 pixels. Output is the following png file:
> 4 votes

# Answer
## Bitmap, 160 bytes

Here's a bitmap with 1-bit colour depth, using a 24-bit colour definition. The last six bytes of the second line is the palette and following that is the pixel array. Every four bytes contains a whole row of pixels.

```
42 4D A0 00 00 00 00 00 00 00 20 00 00 00 0C 00
00 00 20 00 20 00 01 00 01 00 00 00 FF FF FF FF
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 03 FF FF C0 03 FF FF C0 03 FF FF C0
03 FF FF C0 03 FF FF C0 03 FF FF C0 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

```

I tried to truncate the trailing zeroes, but image viewers require there are enough pixels defined for the entire canvas.
> 3 votes

# Answer
# Tcl/Tk, 94

If it runs on the interactive shell, one can abbreviate `canvas` to `can` and `grid` to `gri`

```
gri [can .c -bg red -w 32 -he 32]
lmap R {{8 15 28 21} {15 8 21 28}} {.c cr r $R -f #FFF -w 0}

```
~~Tcl/Tk, 98 If it runs on the interactive shell, one can abbreviate `canvas` to `can`
```
grid [can .c -bg red -w 32 -he 32]
.c cr r 8 15 28 21 -f #FFF -w 0
.c cr r 15 8 21 28 -f #FFF -w 0

```~~ ~~Tcl/Tk, 101
```
pack [canvas .c -bg red -w 32 -he 32]
.c cr r 8 15 28 21 -f #FFF -w 0
.c cr r 15 8 21 28 -f #FFF -w 0

```~~
> 3 votes

# Answer
# Red, 79 Bytes

## Code:

```
view[base 32x32 red draw[fill-pen white pen off box 6x13 26x19 box 13x6 19x26]]

```

## Result:

## Explanation:

```
view [              ; activate view engine
base 32x32 red      ; draw a 32 by 32 red box as base
 draw [             ; draw on top of the base
  fill-pen white    ; fill color is white
  pen off           ; turn off outline, alternatively could use white
  box 6x13 26x19    ; draw a horizontal rectangle, specified as 2 corners XxY
  box 13x6 19x26    ; draw vertical rectangle
]]

```
> 3 votes

# Answer
# Python 2, ~~92~~ ~~91~~ 89 bytes

```
r,w=' \0\0',' '*3
A,B=192*r,(13*r+6*w+13*r)*7
print"P6 "+"32 "*3+A+B+(6*r+20*w+6*r)*6+B+A

```

Output as binary ppm, usage:

```
python golf_swiss.py > swiss.ppm

```

Increasing the color depth allowed me to use space for maximum value
> 3 votes

# Answer
# Ruby \+ ruby2d, 106+8 = 114 bytes

Uses the `-rruby2d` flag.

```
[[32,32],[6,20,13,6],[20,6,6,13]].map{|w,h,x,y|Rectangle.new width:w,height:h,x:x,y:y}[0].color='red'
show

```

Image output:
> 2 votes

# Answer
# LibreLogo, 58 bytes

**Code:**

```
pc [3]fc [5]square 25 fc [3]rectangle[4,15]rectangle[15,4]

```

**Result:**

**Explanation:**

```
pc [3]                   ; Pen Color  = #FFFFFF
fc [5]                   ; Fill Color = #FF0000
square 25                ; Square     = 25 pt
fc [3]                   ; Fill Color = #FFFFFF
rectangle [4, 15]        ; Rectangle  = 4 x 15 pt
rectangle [15, 4]        ; Rectangle  = 15 x 4 pt

```
> 2 votes

# Answer
# Processing, 85 bytes

```
size(32,32);background(#FF0000);fill(255);noStroke();rect(6,13,20,6);rect(13,6,6,20);

```

A very straightforward implementation. Open the window to the minimum size, draw a red background, set the fill to white and shapes to not have borders, and draw two rectangles.
> 2 votes

# Answer
## Haskell, 112 bytes

```
import Graphics.Gloss
(#)=rectangleSolid
main=display(InWindow""(32,32)(0,0))red$color white$pictures[6#20,20#6]

```

A full program that uses the `Gloss` library and opens a window of size 32x32 with red background and two white rectangles (size 6x20 and size 20x6) placed at the center of the window.
> 2 votes

# Answer
# HTML + CSS 215+80 bytes

**Try Online**

**CSS**

```
table{ all:unset } th{ background:red }
   #a{ height: 6 } #b{ height: 7 }
   #c{  width: 6 } #d{  width: 7 }

```

**HTML**

```
<table>
    <tr id=a> <th                                    colspan=5>
    <tr id=b> <th id=c> <th id=d> <td id=c> <th id=d> <th id=c>
    <tr id=a> <th id=c> <td id=d> <td id=c> <td id=d> <th id=c>
    <tr id=b> <th id=c> <th id=d> <td id=c> <th id=d> <th id=c>
    <tr id=a> <th                                    colspan=5>

```

# Inaccurate Version ~~223+40~~ ~~179+40~~ 139+40 bytes

* saved 44 bytes, thanks to @manatwork
* saved 40 bytes, thanks to @SteveBennett

**Try Online**

**CSS**

```
table{ all:unset } th{ background:red }

```

**HTML**

```
<table>
    <tr> <th                     colspan=5>
    <tr> <th colspan=2> <td> <th colspan=2>
    <tr> <th>   <td>    <td>    <td>   <th>
    <tr> <th colspan=2> <td> <th colspan=2>
    <tr> <th                     colspan=5>

```
> 2 votes

# Answer
# Excel VBA, ~~315~~ 313 bytes

2 bytes saved thanks to Taylor Scott!

Golfed

```
Sub m
Set r=[A1:AF32]
r.RowHeight=48
r.NumberFormat=";"
Set p=r.FormatConditions.AddColorScale(2).ColorScaleCriteria
s 1,255,p
s 2,-1,p
r.Formula=Replace("=IFS(OR(ROW()<6,ROW()>26,|<6,|>26),0,OR(AND(ROW()>13,ROW()<19),AND(|>13,|<19)),1,1,0)", "|", "COLUMN()")
End Sub
Sub s(n,v,p)
p(n).FormatColor.Color=v
End Sub

```

And commented

```
Sub m
Set r=[A1:AF32]          'Evaluates range reference to return 32 square range object
r.RowHeight=48           'set row height to make grid cells square - assumes default font
r.NumberFormat=";"       'make text in cells invisible
Set p=r.FormatConditions.AddColorScale(2).ColorScaleCriteria
                         'add 2-colour scale conditional formatting
s 1,255,p                'where lowest value is red
s 2,-1,p                 'highest is white
r.Formula=Replace("=IFS(OR(ROW()<6,ROW()>26,|<6,|>26),0,OR(AND(ROW()>13,ROW()<19),AND(|>13,|<19)),1,1,0)", "|", "COLUMN()") ''#apply grid of 1s and 0s is flag shape
End Sub
Sub s(n,v,p)             'exploits ByRef default (thanks Gaffi)
p(n).FormatColor.Color=v 'set colour for 2-colour scale conditional formatting
End Sub

```

I wanted to do something that didn't involve looping

Assumes font is the default Calibri size 11
> 2 votes

# Answer
# C#, 195 bytes

Try it online(Rextester)!

Hi, this is my first code golf and I'm a C# programmer, so I thought I might submit this entry that I quickly made. It correctly outputs a 32 x 32 bitmap image called "s" in the directory of the executable.

```
var b=new Bitmap(32,32);var g=Graphics.FromImage(b);g.Clear(Color.Red);g.FillRectangle(Brushes.White,new Rectangle(13,0,6,32));g.FillRectangle(Brushes.White,new Rectangle(0,13,32,6));b.Save("s");

```

**Explanation:**

C# offers an extensive GDI+ image manipulation APIs built into the default .NET framework. The System.Drawing namespace contains two such very powerful wrapper classes: Bitmap and Graphics. I merely used those two classes to generate a Swiss flag bitmap.

**Ungolfed:**

```
// Creates a new 32 x 32 bitmap object.
var b = new Bitmap(32, 32);
// Creates a new graphics object from the bitmap image.
var g = Graphics.FromImage(b);
// Clears the bitmap with a red(ARGB: FFFF0000) fill color.
g.Clear(Color.Red);
// Draws the vertical rectangle with a white(ARGB: FFFFFFFF) color.
g.FillRectangle(Brushes.White, new Rectangle(13, 0, 6, 32));
// Draws the horizontal rectangle with a white(ARGB: FFFFFFFF) color.
g.FillRectangle(Brushes.White, new Rectangle(0, 13, 32, 6));
// Save the bitmap to a file named: "s."
b.Save("s");

```
> 2 votes

# Answer
# C++ with OpenGL, 373 Bytes.

This is my first time really working with C++ and OpenGL on a challenge, so let me know what I can improve.

```
#include<GL/glut.h>
#define v glVertex2d
#define r(w,x,y,z) v(w,x);v(w,z);v(y,z);v(y,x);
void d(){glScaled(1/16.0f,1/16.0f,1);glBegin(GL_QUADS);glColor3f(1,0,0);r(-16,-16,16,16)glColor3f(1,1,1);r(-3,-10,3,10)r(-10,-3,10,3)glEnd();glFlush();}int main(int c,char**a){glutInit(&c,a);glutInitWindowSize(320,320);glutCreateWindow("");glutDisplayFunc(d);glutMainLoop();return 0;}

```

Compiled with the MinGW version of g++ on Windows with FreeGlut.

Creates a 320 x 320 screen displaying the Flag.

Whenever a redraw happens, it spawns a smaller flag inside itself. This is because I never clear the screen, nor reset the matrix.

However, a redraw does not happen automatically.

## Ungolfed Code

```
#include <GL/glut.h>
#define rect(w,x,y,z) glVertex2d(w,x);glVertex2d(w,z);glVertex2d(y,z);glVertex2d(y,x);
void display(){
    glClear();
    glScaled(1/16.0f,1/16.0f,1);
    glBegin(GL_QUADS);
        glColor3f(1,0,0);
        rect(-16,-16,16,16)
        glColor3f(1,1,1);
        rect(-3,-10,3,10)
        rect(-10,-3,10,3)
    glEnd();
    glFlush();
}

int main(int argc, char **argv){
    glutInit(&argc, argv);
    glutInitWindowSize(320,320);
    glutCreateWindow("Swiss Flag");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

```

Link to the Compiled Executable
> 2 votes

# Answer
# GW-Basic, 68 bytes (tokenised)

```
0 SCREEN 9:PALETTE 9,36:FOR I=0 TO 3:LINE(X,Y)-(31-X,31-Y),Y+9,BF
  ↪ :Y=I*7 MOD 14+6:SWAP X,Y:NEXT:LOCATE 4

```

To get it down to 68 bytes you have to manually edit the file GW-Basic saves to remove all spaces and the trailing end of file and null characters. The `PALETTE` statement is necessary because GW-Basic has no VGA support and the reds in the default EGA palette are too dark (4) and too washed out (12). The final `LOCATE` statement ensures that GW-Basic's `Ok` isn't printed on top of the flag.
> 2 votes

# Answer
# BBC BASIC, 70 bytes

```
V.19;16,255|25,97,64;64;25,4,12;26;25,99,40;12;25,4,26;12;25,99,12;40;

```

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

Program runs in default mode for this interpreter (white background, black foreground.) 2x2 units = 1 pixel. Flag is 64x64 units = 32 x 32 pixels.

The `VDU` or `V.` command sends characters to the screen controller. These include a number of machine specific control characters for graphics. Number followed by `,` sends 1 byte, by `;` sends 2 bytes. Number followed by `|` sends "sufficient" bytes to finish a multibyte command.

**Ungolfed**

```
  VDU 19,0,16,255|   :REM Reprogram colour 0 (foreground) to #0000FF red (BBC BASIC is little endian.)
  VDU 25,97,64;64;   :REM Cursor is already at 0,0. Move to 64,64 and draw a rectangle in foreground colour (red.)
  VDU 25,4,12;26;    :REM Move to 12,26
  VDU 25,99,40;12;   :REM and draw a rectangle in backgorund colour (white) 40 units wide x 12 units high,
  VDU 25,4,26;12;    :REM Then move to 26,12
  VDU 25,99,12;40;   :REM and draw a vertical rectangle of simiar dimensions.

```
> 1 votes

# Answer
## PostScript, ~~85~~ 80 bytes

## Code:

```
1 0 0 setrgbcolor
0 0 32 32 rectfill
1 setgray
[13 6 6 20 6 13 20 6] rectfill

```

## Result:
> 1 votes

# Answer
# Processing, 74 bytes

```
size(32,32);background(-65536);noStroke();rect(13,6,6,20);rect(6,13,20,6);

```

I have honestly no idea if that's legal here but here it is.

Outputs:

Explanation:

```
size(32,32);            //Set the window size to 32x32
background(-65536);     //Draw the background as red. This is a hack that works because the color datatype uses an int but does not use it as a number. The int equivalent to #FF0000 is -65536 apparently. and it saves me a byte.
noStroke();             //Disable the stroke when drawing shapes like rect
rect(13,6,6,20);        //Draws a rectangle of size 6x20, starting the top-left corner at position (13, 6)
rect(6,13,20,6);        //Draws a rectangle of size 20x6, starting the top-left corner at position (6, 13)

```
> 1 votes

# Answer
## R , 75 bytes

```
x=matrix(2,32,32);x[7:26,14:19]=NA;x[14:19,7:26]=NA;image(x,c=2,ax=F,as=1)

```

**Results in:**

With aspect ratio 1:1 and no axes are drawn.
> 1 votes

# Answer
# SmileBASIC, 42 bytes

```
GCLS #RED
GFILL 6,13,25,18GFILL 13,6,18,25

```

Alternatively `-1<<16` or `-8<<16` can be used instead of `#RED` for the same length.
> 1 votes

# Answer
# PowerShell, 108 bytes

```
$1=($r='2 0 0 ')*192
$2=($r*13+($w='2 '*3)*6+$r*13)*7
$3=($r*6+$w*20+$r*6)*6
"P3 32 32 2 $1$2$3$2$1"|sc .ppm

```

Outputs a PPM file called `.ppm` (checked with IrfanView). It sets '2' as the maximum value for each channel, so `$r` is `2 0 0` for red, `$w` is `2 2 2` for white, and the rest is string multiplication and a file header; `$1` is a horizontal red line for the very top and bottom of the flag, `$2` is wide red, narrow white, wide red for the top and bottom parts of the cross, `3` is the centre narrow red, wide white, narrow red. `sc` is `set-content` and used because `>` makes a 2-byte+BOM Unicode file which doesn't work.
> 1 votes

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

```
P5.size←2⌿32
g←P5.G
a←13 6 19 26
P5.draw←{r←g.rect
g.bg'f00'
g.stroke←⍬
r a
r 2⌽⌽a}

```

32x32 canvas:
> 1 votes

# Answer
# Desmos, ~~90~~ 69 bytes

```
c=hsv(0,[1,0,0],1)
[0,6,13]<=x<=[32,26,19]\{[0,13,6]<=y<=[32,19,26]\}

```

Try it on Desmos!

*-21 bytes thanks to Aiden Chow*
> 1 votes

# Answer
## Applesoft BASIC, 144 bytes

```
0GR
1COLOR=1
2X=0
3VLIN0,31ATX
4X=X+1
5IFX<32GOTO3
6COLOR=15
7X=12
8VLIN6,25ATX
9X=X+1
10IFX<19GOTO8
11Y=12
12HLIN6,25ATY
13Y=Y+1
14IFY<19GOTO12

```
> 1 votes

# Answer
# Batch File, ~~584~~ 497 bytes

**EDIT:** -87 bytes! Replaced `rem` with `hh` as it is a no-op when no arguments are passed, removed a bunch of quotation marks and some other stuff.

I'm sure this can be compressed some more, but for the moment it's the best I got.

```
@!! 2>nul||cmd/q/v/c%0&&exit/b
for /f "tokens=1,2delims=#" %%a in ('"prompt #$H#&for %%b in (1)do hh"')do set K=%%a
set s=aaaaaa
set g=%s%%s%b
:d
set/ai+=1
set t=%i%
if %t%==5 set t=1
if %t%==4 set t=2
if %t%==1 for /l %%a in (1,1,6)do call:c 44 %g%%g%%s%&echo(
if %t%==2 for /l %%a in (1,1,7)do call:c 44 %g%&call:c ff %s%&call:c 44 %g%&echo(
if %t%==3 for /l %%a in (1,1,6)do call:c 44 %s%&call:c ff %g%%s%c&call:c 44 %s%&echo(
if %t%==6 exit
goto d
:c
<nul set/p.=%K%>%~2&findstr/a:%1 . %~2 nul

```

This code produces the following output (tested on Windows version 10.0.15063):

As a negative side-effect, it creates 4 different files on the same directory with some weird names and gibberish in them. You're free to delete them.

Also, in order for this to look right, CMD's properties must be changed (if not already set correctly):

This code requires that the font chosen has a 1:1 width to height ratio.
> 0 votes

# Answer
# Bash + core utils, 147 bytes

```
echo H4sICBkuh1kAA2ZsYWcueHBtAFNUiAjwNeIyNlIAIiMFQ64ihWQFZTc3AyDgKoewQYCLq4gAGIIKysFg+CooxwKGngI6BNQgUoAFDA0FXABVWXDvSwQAAA|base64 -d|gunzip>1.xpm

```

Decodes base64-encoded GZipped image data, unGZips it and writes into `1.xpm`.
> 0 votes

# Answer
# Python 2, 170 bytes

Uses `Pillow 2.8.0` with `PIL 1.1.7` for the old (and deprecated) `offset` method.

```
from PIL.ImageDraw import*
i=Image.new('RGB',(20,20),-1)
Draw(i).rectangle((3,3,18,18),'red',-1)
k=Image.new('RGB',(32,32),'red')
k.paste(i.offset(9),(6,6))
k.show()

```
> 0 votes

# Answer
# C (GCC), ~~133~~ ~~130~~ 125 bytes

```
#define a(x)labs(i x 32-15.5)<
i;main(c){for(puts("P6 32 32 1");i<1024;++i)printf("\1%c%c",c=a(%)10&a(/)10&(a(%)3|a(/)3),c);}

```

Attempt This Online!

Outputs a PPM image.
> 0 votes

# Answer
# Pure bash with utf-8, 262

```
printf -vv %32s;w=${v:19} d=${w:6} e=${d:1} r=$'\e[31;47m' m=$'\e[0m\n' c=${e:3}
c=${c// /${r} $m} b=${c:14} g=${c// /${v// /█}} h=${c// /${w// /█}$e${w// /█}}
i=$r${e// /█}${d// /▀}$e${d// /▀}${e// /█}$m
echo "$g$h$i${b// /${e// /█}$w$d${e// /█}}${i//▀/▄}$h$g"

```

# Pure bash, without utf-8, 283

```
printf -vf %14s;f=("$f" "${f:2}") w=$'\e[47m' r=${w/7/1}
for v in 6:rrr 7:rwr 6:www 7:rwr 6:rrr;do l=$r$f c=r s=${v%:*} m=${v#*:}
for((h=0;h<3;h++)){ [ $c != ${m:h:1} ]&&c=${m:h:1}&&l+=${!c};l+=${f[h&1]};}
[ $c = r ]||l+=$r;l+=$f;printf -vo %${s}s;printf "${o// /$l$'\e[0m\n'}";done

```

Will render:
> 0 votes

# Answer
## PNG - 101 bytes :p

```
âPNG

IHDR  I¥Ë∑PLTEˇˇˇˇA4IDAT◊c`¿ÿ"òˇˇ?Äõ ¬º)’   «√IENDÆB`Ç

```

## Explanation :

Ctrl+C -\> Ctrl+V
> -1 votes

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


title: Longest Zero Sum Sub-array

text:
# Question
Title: Longest Zero Sum Sub-array
Given an array of integers. Find out its longest sub-array (contiguous subsequence) whose sum is 0.

The sub-array for output *may* be an empty array.

## Input

Input an array of integers.

## Output

Output the longest zero sum sub-array. If there are multiple such arrays, output any one of them.

## Output Format

You may output in one of following acceptable format:

1. Output an array of integers;
2. Output the index of first (inclusive) and last (inclusive) element of sub-array;
    * Output (last = first - 1) for empty sub-array
3. Output the index of first (inclusive) and last (exclusive) element of sub-array;
4. Output the index of first (inclusive) element and length of sub-array;

You may choose 0-indexed or 1-indexed value for 2~4 options. But your choices should be consistent for both first and last element.

## Rules

* This is code golf, shortest codes win.
* As usual, standard loopholes are forbidden.
* Your program *may* fail due to integer overflow (as long as this not trivialize this challenge, which is a standard loophole).
* This is code golf. We don't care the performance of your algorithm / implementation.

## Testcases

```
Input -> Output
[] -> []
[0] -> [0]
[1] -> []
[-1,1] -> [-1,1]
[-1,1,2] -> [-1,1]
[-2,-1,1,2] -> [-2,-1,1,2]
[1,2,3,4,5] -> []
[1,0,2,0,3,0] -> [0]
[1,2,-2,3,-4,5] -> [1,2,-2,3,-4]
[1,2,3,4,5,-4,-3,-2,-1,0] -> [4,5,-4,-3,-2]
[0,1,0,0,0,1] -> [0,0,0]
[0,0,0,1,0,0,1] -> [0,0,0]
[0,0,0,1,0,0,-1] -> [0,0,0,1,0,0,-1]
[-86,14,-36,21,26,-2,-51,-11,38,28] -> [26,-2,-51,-11,38]
[0,70,65,-47,-98,-61,-14,85,-85,92] -> [0,70,65,-47,-98,-61,-14,85]
[4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4,2,-1,-4,0,2,-5,-5,2,1,-4,0,-1,4,3,3,-5,-4,-5,3,-3,-1,-5,1,-2,3,0,3,-4,1,-5,-1,4,-5,2,1,-3,4,4,1,-1,-5,-5,-2,4,0,-3,4,1,-3,0,-3] -> [4,-4,2,0,4,-2,-2,1,0,1,-4,0,-2,2,2,-4,0,-1,2,1,-4,-2,3,4,3,0,3,2,-4,2,3,3,1,2,3,-3,-4,3,-4,4,0,-3,-1,-5,-4,1,-3,4,-4]

```

# Answer
# Python 3, 47 bytes

```
f=lambda x,*a:f(*a,x[1:],x[:-1])if sum(x)else x

```

Try it online!

It's simple breadth-first search, implemented recursively. The `if...else` is slightly bothering me; it feels like there is an improvement somewhere...
> 17 votes

# Answer
# 05AB1E, 7 bytes

```
ŒéʒO_}θ

```

Try it online!

```
Œ        # sublists of the input
 é       # sort by length
  ʒ  }   # keep those where:
   O_    #   the sum equals 0
      θ  # take the last one

```

The output of `Œ` doesn't contain the empty list, but if the result of the filter is empty, `θ` fails and leaves the empty list on the stack.
> 7 votes

# Answer
# K (ngn/k), ~~24~~ ~~22~~ 21 bytes

```
{t@'*<-/t:&x=/:x}0,+\

```

Try it online!

*-1 byte thanks to coltim and Traws*

Unfortunately(?), I found a 2-byte golf that bumps the time complexity to \\$\mathcal{O}(n^2 \log n)\\$ (and space complexity to \\$\mathcal{O}(n^2)\\$). This one utilizes "equality table" `=/:` and "deep where" `&` to extract *all* pairs of indices that represent zero-sum subarrays. Finding the pair that represents the longest such subarray is algorithmically the same.

---

# K (ngn/k), 24 bytes

```
*<!/1-/'\(*'1|:\)'.=0,+\

```

Try it online!

Runs in \\$\mathcal{O}(n \log n)\\$ time and \\$\mathcal{O}(n)\\$ space. A monadic function train that takes a list of integers and returns `[start index (inclusive), end index (exclusive)]`. (For reading test case output, `!0` and `()` are notations for empty lists, and `,0` is a notation for the singleton list `[0]`.)

```
*<!/1-/'\(*'1|:\)'.=0,+\   monadic train; x: integer list
                    0,+\   prepend 0 to the cumulative sum of x
                   =       group; gives a dict of {value:indices}
                  .        extract values of the dict
                      any ordered pair inside each row forms a valid
                      (start,end) pair with subarray sum of zero
         (*'1|:\)'    for each list, extract (first,last)
 <!/1-/'\             sort this list by ascending order of (first-last)
*                     extract the first pair

```

It is actually shorter than a function that generates all contiguous subsequences and operates on them (which is \\$\mathcal{O}(n^3)\\$ time and space):

# K (ngn/k), 26 bytes

```
{*(0=+/)#,/x{y'x}/:|!1+#x}

```

Try it online!
> 7 votes

# Answer
# Jelly, 7 bytes

```
ẆSÐḟṪȯ$

```

Try It Online!

Converted from a full program to a link for the same byte-count thanks to Jonathan Allan.

```
ẆSÐḟṪȯ$    Main Link
Ẇ          Get all sublists (unfortunately excludes the empty sublist)
  Ðḟ       Filter to remove elements with a non-falsy/non-zero
 S           sum
      $    Apply monadically to the resulting list of sublists:
    Ṫ      - take the last one (returns zero if the list is empty)
     ȯ     - logical OR; if 0 was returned, instead return the list
             of sublists, which is the empty list

```
> 6 votes

# Answer
# Japt `-h`, 5 bytes

```
ã k_x

```

Try it or run all test cases

```
ã k_x     :Implicit input of array
ã         :Sub-arrays
  k       :Remove elements that return truthy (not 0)
   _      :When passed through the following function
    x     :  Reduce by addition
          :Implicit output of last element of resulting array (or undefined if empty)

```
> 6 votes

# Answer
# JavaScript (ES6), 60 bytes

```
f=(b,...a)=>eval(b.join`+`)?f(...a,b.slice(1),b.pop()?b:b):b

```

Try it online!

### Commented

```
f = (                 // f is a recursive function taking:
  b,                  //   b[] = next array
  ...a                //   a[] = list of all other arrays
) =>                  //
  eval(b.join`+`) ?   // if the sum of b[] is not zero:
    f(                //   do a recursive call:
      ...a,           //     first try with the other arrays that were
                      //     already passed to this iteration
      b.slice(1),     //     then try with b[] without the leading term
      b.pop() ? b : b //     and finally with b[] without the trailing term
                      //     NB: we don't mind modifying b[] at this point,
                      //         and this is shorter than b.slice(0, -1)
    )                 //   end of recursive call
  :                   // else:
    b                 //   success: return b[]

```
> 6 votes

# Answer
# Risky, 12 bytes

```
{_*_1?+?:_0{_-+_0+_0+_0

```

Try it online!

### Explanation

Here's a rough tree diagram of how the program parses:

```
           {
     ?           +
  *     :     +     +
{  _  +  _  _  _  _  _
 _  1  ?  0  -  0  0  0

```

The left half generates a list of all sublists that sum to zero:

```
{_                       List of sublists of the input (ordered shortest to longest)
  *_1                    Repeat 1 time (no-op)
     ?                   Filter by this function:
      +?                  The sum of the input
        :                 Equals
         _0               Zero

```

The right half, using a ton of no-ops to balance the parse tree, evaluates to -1. Finally, `{` gets the element of (left half's result) at index (right half's result): i.e. the last and therefore longest sublist.
> 5 votes

# Answer
# Vyxal, 7 bytes

```
ÞS'∑¬;t  # main program

```

```
ÞS       # sublists
  '∑¬;   # filter
   ∑¬    # by the negated sum
      t  # take the tail

```

Similar to @hyper-neutrino's answer.

Try it Online!
> 4 votes

# Answer
# , 28 bytes

```
<\\.;@{.@(\:#&>)@#~&,0=+/\\.

```

Try it online!

* `<\\....#~&,0=+/\\.` All boxed sublists `<\\.` filtered by those with 0 sum `#~ 0=+/\\.` after flattening both `&,`.
* `(\:#&>)@` Sort down by length
* `;@{.@` And open the first element.
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~37~~ 36 bytes

```
Last@*Select[Tr@#==0&]@*Subsequences

```

-1 byte from att using function composition

Try it online!

`Subsequences` generates all contiguous subsequences, sorted by length; `Select[Tr@#==0&]` selects those whose trace (total) is 0; `Last` selects the last, and thus longest, of these subsequences.

att also shows, in the comments, a different approach from mine that is 35 bytes:

```
Last@Pick[#,Tr/@#,0]&@*Subsequences

```
> 4 votes

# Answer
# Factor \+ `math.unicode`, 64 bytes

```
[ [ "1"] when-empty all-subseqs [ Σ 0 = ] filter ?last >array ]

```

Try it online!

* `[ "1"] when-empty` Unfortunately necessary to handle the empty sequence. `all-subseqs` blows up otherwise. `"1"` is simply the shortest thing you can stick in there that ultimately produces the empty sequence.
* `all-subseqs` Get every subsequence of a sequence.
* `[ Σ 0 = ] filter` Select the ones that sum to 0.
* `?last >array` Take the last (also longest) element (or `f` if the sequence is empty) and then convert it to a sequence. Necessary because the `filter` can return an empty sequence.
> 4 votes

# Answer
# Python 3, 85 bytes

```
lambda a:[(s,l)for l in range(len(a))for s in range(len(a)-l)if 0==sum(a[s:s+l])][-1]

```

Try it online!

-5 bytes thanks to totallyhuman
> 2 votes

# Answer
# Haskell, ~~75~~ 73 bytes

*-2 bytes thanks to Joseph Sible.*

```
f i|e<-length i=last[(s,l)|l<-[0..e],s<-[0..e-l],0==sum(take l$drop s i)]

```

Try it online!
> 2 votes

# Answer
# Brachylog, ~~13~~ 9 bytes

*-4 bytes thanks to a clever trick from Unrelated String*

```
⊇.+0&s.∨Ė

```

Try it online! (Note that negative numbers in the input must be indicated with underscores rather than minus signs.)

### Explanation

It would have been nice to use this 6-byte solution:

```
s.+0∨Ė
s.       A contiguous sublist of the input is the output
  +0     and its sum is zero
    ∨   Or, if it is impossible to satisfy those conditions...
     Ė   the output is the empty list

```

Unfortunately, the order in which the `s` predicate tries sublists is ordered by start index, not by length. However, the  predicate, which gives not-necessarily-contiguous sublists, *is* ordered by length. So we can start by getting the longest sublist and then afterwards check that it's contiguous:

```
⊇.+0&s.∨Ė
⊇.          A sublist of the input is the output
  +0        and its sum is zero
    &       and furthermore
     s.     the output is a contiguous sublist of the input
       ∨   Or, if it is impossible to satisfy those conditions...
        Ė   the output is the empty list

```
> 2 votes

# Answer
# Haskell, 64 bytes

```
k=length
f l|sum l==0=l|h:t<-l=f t#(f.init)l
a#b|k a>k b=a|1>0=b

```

Try it online!

* `f` return longest sublist by checking if list sum is 0 or choosing the best result coming from recursively inspecting tail and init
* a`#` b used by `f` to choose longest result
> 2 votes

# Answer
## Clojure, 98 bytes

```
#(or(first(for[n[(count %)]i(range n)j(range n i -1):when(=(apply +(subvec % i j))0)][i j]))[1 0])

```

Returns an exclusive range, or `[1 0]` if no such range is found. For example:

```
[1,2,3,4,5,-4,-3,-2,-1,0] -> [3 8]

```
> 1 votes

# Answer
# Perl 5, 73 bytes

```
sub{(sort{@$b-@$a}grep!sum(@$_),map[@_?@_[$_/@_..$_%@_]:()],0..@_**2)[0]}

```

Try it online!
> 1 votes

# Answer
# PHP, 101, 99, 90

```
for(;$argc>$j=++$i;)for(;$j;)array_sum(array_slice($argv,$j--,$l=$argc-$i))||die("$j,$l");

```

Try It Online

Input is array elements as the command line argument list. Outputs the zero based start position and length of sub array. Does not output anything for the null case.
> 1 votes

# Answer
# Desmos, ~~154~~ ~~139~~ 137 bytes

*Thanks @fireflame241 for helping me golf a couple of bytes (on Discord)*

```
A=length(l)
B=[1...A-f]
Z=[0...A]
h(a,b)=\{\sum_{C=a}^bl[C]=0,0\}
f=\max((Z+1)\sign(\sum_{n=1+Z}^Ah(n-Z,n)))
g(l)=[f,\max(Bh(B,[f...A]))]

```

Uses Output Format #4. The first element in the outputted list is the length of the subarray, while the second element is the starting index of the subarray in respect to the inputted array.

Try It On Desmos!

Try It On Desmos! - Prettified(and a more verbose version)
> 1 votes

# Answer
# jq, 53 bytes

```
[.[keys[]:keys[]+1]|select(add==0)]|max_by(length)//.

```

Try it online!

**Explanation:**

```
[
  .[keys[]:keys[]+1]   #calculates all subarrays
  |select(add==0)      #selects these which add up to 0
]
|max_by(length)        #picks the longest one
//.                    #if there is no such subarray returns an empty array

```
> 1 votes

# Answer
# Vyxal 3 `G`, 3 bytes

```
Ṣᶻ∑

```

Try it Online!

filter by falsy my beloved
> 1 votes

# Answer
# Charcoal, 26 bytes

```
Ｆ⊕ＬθＦ⊕⁻Ｌθι⊞υ✂θκ⁺κι¹Ｉ⊟Φυ¬Σι

```

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

```
Ｆ⊕ＬθＦ⊕⁻Ｌθι⊞υ✂θκ⁺κι¹

```

Carefully list the subsequences of the input in ascending order of length.

```
Ｉ⊟Φυ¬Σι

```

Get those with a zero sum (or no sum at all, in the case of the empty subsequences) and output the last i.e. the longest.
> 0 votes

# Answer
# Haskell, 88 bytes

```
f=head.filter((0==).sum).concat.iterate(concat.zipWith map[tail,init].replicate 2).(:[])

```

Try it online!
> 0 votes

---
Tags: code-golf, array, integer, subsequence
---


# Question
Title: Could you please stop shuffling the deck and play already?
## Challenge:

**Input:** A list of distinct positive integers within the range \\$\[1, \text{list-size}\]\\$.

**Output:** An integer: the amount of times the list is riffle-shuffled. For a list, this means the list is split in two halves, and these halves are interleaved (i.e. riffle-shuffling the list `[1,2,3,4,5,6,7,8,9,10]` once would result in `[1,6,2,7,3,8,4,9,5,10]`, so for this challenge the input `[1,6,2,7,3,8,4,9,5,10]` would result in `1`).

## Challenge rules:

* You can assume the list will only contain positive integers in the range \\$\[1, \text{list-size}\]\\$ (or \\$\[0, \text{list-size}-1\]\\$ if you choose to have 0-indexed input-lists).
* You can assume all input-lists will either be a valid riffle-shuffled list, or a sorted list which isn't shuffled (in which case the output is `0`).
* You can assume the input-list will contain at least three values.

## Step-by-step example:

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

Unshuffling it once becomes: `[1,5,9,4,8,3,7,2,6]`, because every even 0-indexed item comes first `[1, ,5, ,9, ,4, ,8]`, and then all odd 0-indexed items after that `[ ,3, ,7, ,2, ,6, ]`.
The list isn't ordered yet, so we continue:

Unshuffling the list again becomes: `[1,9,8,7,6,5,4,3,2]`
Again becomes: `[1,8,6,4,2,9,7,5,3]`
Then: `[1,6,2,7,3,8,4,9,5]`
And finally: `[1,2,3,4,5,6,7,8,9]`, which is an ordered list, so we're done unshuffling.

We unshuffled the original `[1,3,5,7,9,2,4,6,8]` five times to get to `[1,2,3,4,5,6,7,8,9]`, so the output is `5` in this case.

## General rules:

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

## Test cases:

```
Input                                                   Output

[1,2,3]                                                 0
[1,2,3,4,5]                                             0
[1,3,2]                                                 1
[1,6,2,7,3,8,4,9,5,10]                                  1
[1,3,5,7,2,4,6]                                         2
[1,8,6,4,2,9,7,5,3,10]                                  2
[1,9,8,7,6,5,4,3,2,10]                                  3
[1,5,9,4,8,3,7,2,6,10]                                  4
[1,3,5,7,9,2,4,6,8]                                     5
[1,6,11,5,10,4,9,3,8,2,7]                               6
[1,10,19,9,18,8,17,7,16,6,15,5,14,4,13,3,12,2,11,20]    10
[1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20]    17
[1,141,32,172,63,203,94,234,125,16,156,47,187,78,218,109,249,140,31,171,62,202,93,233,124,15,155,46,186,77,217,108,248,139,30,170,61,201,92,232,123,14,154,45,185,76,216,107,247,138,29,169,60,200,91,231,122,13,153,44,184,75,215,106,246,137,28,168,59,199,90,230,121,12,152,43,183,74,214,105,245,136,27,167,58,198,89,229,120,11,151,42,182,73,213,104,244,135,26,166,57,197,88,228,119,10,150,41,181,72,212,103,243,134,25,165,56,196,87,227,118,9,149,40,180,71,211,102,242,133,24,164,55,195,86,226,117,8,148,39,179,70,210,101,241,132,23,163,54,194,85,225,116,7,147,38,178,69,209,100,240,131,22,162,53,193,84,224,115,6,146,37,177,68,208,99,239,130,21,161,52,192,83,223,114,5,145,36,176,67,207,98,238,129,20,160,51,191,82,222,113,4,144,35,175,66,206,97,237,128,19,159,50,190,81,221,112,3,143,34,174,65,205,96,236,127,18,158,49,189,80,220,111,2,142,33,173,64,204,95,235,126,17,157,48,188,79,219,110,250]
                                                        45

```

# Answer
# Jelly, 8 bytes

```
ŒœẎ$ƬiṢ’

```

**Try it online!**

### How?

```
ŒœẎ$ƬiṢ’ - Link: list of integers A
    Ƭ    - collect up until results are no longer unique...
   $     -   last two links as a monad:
Œœ       -     odds & evens i.e. [a,b,c,d,...] -> [[a,c,...],[b,d,...]]
  Ẏ      -     tighten                         -> [a,c,...,b,d,...]
     Ṣ   - sort A
    i    - first (1-indexed) index of sorted A in collected shuffles
      ’  - decrement

```
> 7 votes

# Answer
# JavaScript (ES6), 44 bytes

*Shorter version suggested by @nwellnhof*

Expects a deck with 1-indexed cards as input.

```
f=(a,x=1)=>a[x]-2&&1+f(a,x*2%(a.length-1|1))

```

Try it online!

Given a deck \\$\[c\_0,\ldots,c\_{L-1}\]\\$ of length \\$L\\$, we define:

$$x\_n=\begin{cases} 2^n\bmod L&\text{if }L\text{ is odd}\\ 2^n\bmod (L-1)&\text{if }L\text{ is even}\\ \end{cases}$$

And we look for \\$n\\$ such that \\$c\_{x\_n}=2\\$.

---

# JavaScript (ES6),  ~~57 52~~  50 bytes

Expects a deck with 0-indexed cards as input.

```
f=(a,x=1,k=a.length-1|1)=>a[1]-x%k&&1+f(a,x*-~k/2)

```

Try it online!

### How?

Since JS is lacking native support for extracting array slices with a custom stepping, simulating the entire riffle-shuffle would probably be rather costly (but to be honest, I didn't even try). However, the solution can also be found by just looking at the 2nd card and the total number of cards in the deck.

Given a deck of length \\$L\\$, this code looks for \\$n\\$ such that:

$$c\_2\equiv\left(\frac{k+1}{2}\right)^n\pmod k$$

where \\$c\_2\\$ is the second card and \\$k\\$ is defined as:

$$k=\begin{cases} L&\text{if }L\text{ is odd}\\ L-1&\text{if }L\text{ is even}\\ \end{cases}$$
> 25 votes

# Answer
# Python 2, 39 bytes

```
f=lambda x:x[1]-2and-~f(x[::2]+x[1::2])

```

Try it online!

-4 thanks to Jonathan Allan.
> 12 votes

# Answer
# APL (Dyalog Unicode), ~~35~~ ~~26~~ ~~23~~ 22 bytesSBCS

```
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}

```

Try it online!

Thanks to Adám for the help, Erik the Outgolfer for -3 and ngn for -1.

The TIO link contains two test cases.

Explanation:

```
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]} ⍝ function takes one argument: ⍵, the array
 ⍵≡⍳≢⍵                 ⍝ if the array is sorted:
 ⍵≡⍳≢⍵                 ⍝ array = 1..length(array)
      :0               ⍝ then return 0
        ⋄              ⍝ otherwise
         1+            ⍝ increment
           ∇           ⍝ the value of the recursive call with this argument:
            ⍵[      ]  ⍝ index into the argument with these indexes:
                 ⍳⍴⍵   ⍝ - generate a range from 1 up to the size of ⍵
               2|      ⍝ - %2: generate a binary mask like [1 0 1 0 1 0]
              ⍒        ⍝ - grade (sorts but returns indexes instead of values), so we have the indexes of all the 1s first, then the 0s.

```
> 6 votes

# Answer
# Perl 6, ~~34~~ 32 bytes

*-2 bytes thanks to Jo King*

```
{(.[(2 X**^$_)X%$_-1+|1]...2)-1}

```

Try it online!

Similar to Arnauld's approach. The index of the second card after n shuffles is `2**n % k` with k defined as in Arnauld's answer.
> 5 votes

# Answer
# , ~~58~~ ~~55~~ 45 bytes

```
a=scan();while(a[2]>2)a=matrix(a,,2,F<-F+1);F

```

Try it online!

Simulates the sorting process. Input is 1-indexed, returns `FALSE` for 0.
> 5 votes

# Answer
# Perl 6, ~~36 34~~ 32 bytes

*-2 bytes thanks to nwellnhof*

```
$!={.[1]-2&&$!(.sort:{$++%2})+1}

```

Try it online!

Reverse riffle shuffles by sorting by the index modulo 2 until the list is sorted, then returns the length of the sequence.

It's funny, I don't usually try the recursive approach for Perl 6, but this time it ended up shorter than the original.

### Explanation:

```
$!={.[1]-2&&$!(.sort:{$++%2})+1}
$!={                           }   # Assign the anonymous code block to $!
    .[1]-2&&                       # While the list is not sorted
            $!(             )      # Recursively call the function on
               .sort:{$++%2}       # It sorted by the parity of each index
                             +1    # And return the number of shuffles

```
> 4 votes

# Answer
# Java (JDK), 59 bytes

```
a->{int c=0;for(;a[(1<<c)%(a.length-1|1)]>2;)c++;return c;}

```

Try it online!

Works reliably only for arrays with a size less than 31 or solutions with less than 31 iterations. For a more general solution, see the following solution with 63 bytes:

```
a->{int i=1,c=0;for(;a[i]>2;c++)i=i*2%(a.length-1|1);return c;}

```

Try it online!

## Explanation

In a riffle, the next position is the previous one times two modulo either length if it's odd or length - 1 if it's even.

So I'm iterating over all indices using this formula until I find the value 2 in the array.

## Credits
> 4 votes

# Answer
# 05AB1E (legacy), 9 bytes

```
[DāQ#ι˜]N

```

Try it online!

**Explanation**

```
[   #  ]     # loop until
  ā          # the 1-indexed enumeration of the current list
 D Q         # equals a copy of the current list
     ι˜      # while false, uninterleave the current list and flatten
        N    # push the iteration index N as output

```
> 3 votes

# Answer
# , ~~28~~ 26 bytes

-2 bytes thanks to Jonah!

```
 1#@}.(\:2|#\)^:(2<1{])^:a:

```

Try it online!

Inspired be Ven's APL solution.

## Explanation:

```
               ^:       ^:a:   while
                 (2<1{])       the 1-st (zero-indexed) element is greater than 2
     (        )                do the following and keep the intermediate results
          i.@#                 make a list form 0 to len-1
        2|                     find modulo 2 of each element
      /:                       sort the argument according the list of 0's and 1's
1  }.                          drop the first row of the result
 #@                            and take the length (how many rows -> steps)

```

# K (ngn/k), 25 bytes

Thanks to ngn for the advice and for his K interpreter!

```
{#1_{~2=x@1}{x@<2!!#x}\x}

```

Try it online!
> 3 votes

# Answer
# Husk, 11 bytes

```
L↑S≠ŀ¡ȯΣTC2

```

Try it online!
> 3 votes

# Answer
# APL(NARS), chars 49, bytes 98

```
{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}

```

why use in the deepest loop, one algo that should be nlog(n), when we can use one linear n? just for few bytes more? \[⍵≡⍵\[⍋⍵\] O(nlog n) and the confront each element for see are in order using ∧/¯1↓⍵≤1⌽⍵ O(n)\]test:

```
  f←{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}
  f ,1
0
  f 1 2 3
0
  f 1,9,8,7,6,5,4,3,2,10
3
  f 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20
17

```
> 2 votes

# Answer
# C (GCC) ~~64~~ 63 bytes

-1 byte from nwellnhof

```
i,r;f(c,v)int*v;{for(i=r=1;v[i]>2;++r)i=i*2%(c-1|1);return~-r;}

```

This is a drastically shorter answer based on Arnauld's and Olivier Grégoire's answers. I'll leave my old solution below since it solves the slightly more general problem of decks with cards that are not contiguous.

Try it online

---

# C (GCC) 162 bytes

```
a[999],b[999],i,r,o;f(c,v)int*v;{for(r=0;o=1;++r){for(i=c;i--;(i&1?b:a)[i/2]=v[i])o=(v[i]>v[i-1]|!i)&o;if(o)return r;for(i+=o=c+1;i--;)v[i]=i<o/2?a[i]:b[i-o/2];}}

```

Try it online

```
a[999],b[999],i,r,o; //pre-declare variables
f(c,v)int*v;{ //argument list
    for(r=0;o=1;++r){ //major loop, reset o (ordered) to true at beginning, increment number of shuffles at end
        for(i=c;i--;(i&1?b:a)[i/2]=v[i]) //loop through v, split into halves a/b as we go
            o=(v[i]>v[i-1]|!i)&o; //if out of order set o (ordered) to false
        if(o) //if ordered
            return r; //return number of shuffles
        //note that i==-1 at this point
        for(i+=o=c+1;i--;)//set i=c and o=c+1, loop through v
            v[i]=i<o/2?a[i]:b[i-o/2];//set first half of v to a, second half to b
    }
}

```
> 2 votes

# Answer
# Perl 5 `-pa`, ~~77~~ 68 bytes

```
map{push@{$_%2},$_}0..$#F;++$\,@F=@F[@0,@1]while"@F"ne"@{[1..@F]}"}{

```

Try it online!
> 2 votes

# Answer
# , ~~70~~ 72 bytes

```
x=scan();i=0;while(any(x>sort(x))){x=c(x[y<-seq(x)%%2>0],x[!y]);i=i+1};i

```

Try it online!

Now handles the zero shuffle case.
> 2 votes

# Answer
# Ruby, 42 bytes

```
f=->d,r=1{d[r]<3?0:1+f[d,r*2%(1|~-d.max)]}

```

Try it online!

### How:

Search for number 2 inside the array: if it's in second position, the deck hasn't been shuffled, otherwise check the positions where successive shuffles would put it.
> 2 votes

# Answer
# R, 85 bytes

```
s=scan();u=sort(s);k=0;while(any(u[seq(s)]!=s)){k=k+1;u=as.vector(t(matrix(u,,2)))};k

```

Try it online.

**Explanation**

Stupid (brute force) method, much less elegant than following the card #2.

Instead of unshuffling the input `s` we start with a sorted vector `u` that we progressively shuffle until it is identical with `s`. This gives warnings (but shuffle counts are still correct) for odd lengths of input due to folding an odd-length vector into a 2-column matrix; in that case, in R, missing data point is filled by recycling of the first element of input.

The loop will never terminate if we provide a vector that cannot be unshuffled.

Addendum: you save one byte if unshuffling instead. Unlike the answer above, there is no need to transpose with `t()`, however, ordering is `byrow=TRUE` which is why `T` appears in `matrix()`.

# , 84 bytes

```
s=scan();u=sort(s);k=0;while(any(s[seq(u)]!=u)){k=k+1;s=as.vector(matrix(s,,2,T))};k

```

Try it online!
> 2 votes

# Answer
# PowerShell, ~~116 114 108 84~~ 78 bytes

-24 bytes thanks to Erik the Outgolfer's solution.

-6 bytes thanks to mazzy.

```
param($a)for(;$a[1]-2){$n++;$t=@{};$a|%{$t[$j++%2]+=,$_};$a=$t.0+$t.1;$j=0}+$n

```

Try it online!
> 2 votes

# Answer
# Lua (LuaJIT), ~~119~~ ~~96~~ 79 bytes

```
n=t;while 2~=n[2]do n={}for a=1,#t*2,2 do x=a-#t n[#n+1]=t[a]or t[x+x%2]end;t=n

```

Try it online!
> 2 votes

# Answer
# MATLAB, 70 bytes

```
function s(l),x=max(l);find(find(l==2)==1+mod(2.^(1:x),x-1))*(l(2)~=2)

```

explanation:

every nth shuffle, 2 will be pushed n^2 indices down from its previous position, wrapping around when it reaches the last position. That means that the function for index(n) is

1+mod(2^n,list-size-1)

for a list-size of 10, then, the indices are:

* index(1) = 3 -\> \[1 6 **2** 7 3 8 4 9 5 10\]
* index(2) = 5 -\> \[1 8 6 4 **2** 9 7 5 3 10\]
* index(3) = 9 -\> \[1 9 8 7 6 5 4 3 **2** 10\]
* index(4) = 17 =\> 8 -\> \[1 5 9 4 8 3 7 **2** 6 10\]

etc.

Using this, I find the index where 2 is, and find which power of 2 that is along the array. That power corresponds the the number of shuffles. To account for 0 shuffles, the whole thing is multiplied by the boolean value of l(2)~=2 to make sure that it returns 0 when 2 is in the right place, which only happens for an unshuffled array.
> 2 votes

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

Taking my shiny, new~~, **very**-work-in-progress~~ interpreter for a test drive.

```
ÅÎÍ©ÒßUñÏu

```

Try it or run all test cases

```
ÅÎÍ©ÒßUñÏu     :Implicit input of integer array U
Å              :Slice the first element off U
 Î             :Get the first element
  Í            :Subtract from 2
   ©           :Logical AND with
    Ò          :  Negation of bitwise NOT of
     ß         :  A recursive call to the programme with input
      Uñ       :    U sorted
        Ï      :    By 0-based indices
         u     :    Modulo 2

```
> 1 votes

# Answer
# Red, ~~87~~ ~~79~~ 78 bytes

```
func[b][c: 0 while[b/2 > 2][c: c + 1 b: append extract b 2 extract next b 2]c]

```

Try it online!
> 1 votes

# Answer
# Pyth, 18 bytes

```
L?SIb0hys%L2>Bb1
y

```

Try it online!

-2 thanks to @Erik the Outgolfer.

The script has two line: the first one defines a function `y`, the second line calls `y` with the implicit `Q` (evaluated stdin) argument.

```
L?SIb0hys%L2>Bb1
L                function y(b)
 ?               if...
  SIb            the Invariant b == sort(b) holds
     0           return 0
      h          otherwise increment...
       y         ...the return of a recursive call with:
             B   the current argument "bifurcated", an array of:
              b   - the original argument
            >  1  - same with the head popped off
          L      map...
         % 2     ...take only every 2nd value in each array
        s         and concat them back together

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 62 bytes

```
c=0;While[Sort[a]!=a,a=a[[1;;-1;;2]]~Join~a[[2;;-1;;2]];c++];c

```

Try it online!

# Explanation

The input list is `a` . It is unriffled and compared with the sorted list until they match.
> 1 votes

# Answer
# PowerShell, ~~62~~ ~~71~~ ~~70~~ 66 bytes

*+9 bytes when Test cases with an even number of elements added.*

*-1 byte with splatting.*

*-4 bytes: wrap the expression with `$i`,`$j` to a new scope.*

```
for($a=$args;$a[1]-2;$a=&{($a|?{++$j%2})+($a|?{$i++%2})}){$n++}+$n

```

Try it online!
> 1 votes

# Answer
# Stax, 14 bytes

```
ü≈:☻‼Xí┌ùß♦▲▬á

```

Run and debug it
> 1 votes

# Answer
# Vyxal 3, 7 bytes

```
ϩUJiᶤᵞS

```

Try it Online!

```
ϩUJiᶤᵞS
ϩ  i     # Apply and collect until value is no longer unique, including initial value
 UJ      # Uninterleave and append
    ᶤᵞS  # first index where the list is sorted (invariant after sort)

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Python 3, 40 bytes

```
f=lambda x:x[1]-2and 1+f(x[::2]+x[1::2])  # 1-based
f=lambda x:x[1]-1and 1+f(x[::2]+x[1::2])  # 0-based

```

Try it online!

I need to refresh the page more frequently: missed Erik the Outgolfer's edit doing a similar trick =)
> 0 votes

---
Tags: code-golf, number, array, integer
---


title: Is the king in check?

text:
# Question
Title: Is the king in check?
**Challenge:**
Given a 2D array (8x8) of characters, is the enemy king in check?
The program should return true **if and only if** the king is **currently** in check.
Standard chess rules apply.

**Specifications**:
The game is provided using a 2D array,
where blank space means there is not a piece on that square.
You may assume that the only characters that will appear
in the array are one of: `[SPACE]kpnbrqKPNBRQ`

The 2D array is given as a y-major array
that starts from the bottom left (a1 square),
which means accessing the array would be: `board[row][column]`.
For example: `board[0][0] is a1`, and `board[3][5] is f4`

Character set:
King - `K`
Pawn - `P`
Knight - `N`
Bishop - `B`
Rook - `R`
Queen - `Q`

Your own pieces are in uppercase, and the enemy pieces are in lowercase.
Also, enemy pieces only serve the purpose of blocking a check, so they are essentially the same as pawns.

**Test case:**
In this game, the given array would be:

```
r bqk  r
p pp Bpp
 pn  n
    p  Q
 b PP
  P
PP   PPP
RNB K NR

```

and should return true. Note that even if the bishop on f7 wasn't protected, it should still return true.

Happy golfing!

# Answer
> 4 votes
# Charcoal, 95 bytes

```
≔⪫ＥθＳ¶η¿⊙⌕ＡηN⁼⁵ΣＸ⟦⁻÷ι⁹÷⌕ηk⁹⁻﹪ι⁹﹪⌕ηk⁹⟧²-«Ｐη…η⌕ηk≔Ｅ⁸ＫＤ⁹✳ιζ⎚∨⊙✂ζ⁵χ²⁼§ι¹P⊙ζ№⊞Ｏ⟦Q⟧§RBκ§Φι⊙…ι⊕μ∧π⁻ ν¹

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for in check, nothing if not. Explanation:

```
≔⪫ＥθＳ¶η

```

Input the board and join it on newlines.

```
¿⊙⌕ＡηN⁼⁵ΣＸ⟦⁻÷ι⁹÷⌕ηk⁹⁻﹪ι⁹﹪⌕ηk⁹⟧²-«

```

If there is a knight a knight's move away from the king, then output a `-`, otherwise:

```
Ｐη…η⌕ηk≔Ｅ⁸ＫＤ⁹✳ιζ⎚

```

Temporarily write the board to the canvas so that all of the ranks, files and diagonals to the king can be extracted.

```
∨⊙✂ζ⁵χ²⁼§ι¹P⊙ζ№⊞Ｏ⟦Q⟧§RBκ§Φι⊙…ι⊕μ∧π⁻ ν¹

```

Check for pawns that are checking the king and check the first piece in every direction for a piece that can check the king from that direction.

# Answer
> 4 votes
# JavaScript (ES6), 188 bytes

Expects a matrix of characters and returns a Boolean value.

```
f=(m,P,X,Y)=>m.some((r,y)=>r.some((p,x)=>P?{N:(H=x-X,H*=H)+(v=y-Y)*v-5,B:B=H-v*v|(g=A=>u=(c=m[A+=-(A>Y)|A<Y][x+=-(x>X)|x<X])!=P&&c>g|g(A))(y),R:u|=H*=v,Q:B*u,P:H-1}[p]+P=='0k':f(m,p,x,y)))

```

Try it online!

## Position editor

```
f=(m,P,X,Y)=>m.some((r,y)=>r.some((p,x)=>P?{N:(H=x-X,H*=H)+(v=y-Y)*v-5,B:B=H-v*v|(g=A=>u=(c=m[A+=-(A>Y)|A<Y][x+=-(x>X)|x<X])!=P&&c>g|g(A))(y),R:u|=H*=v,Q:B*u,P:H-1}[p]+P=='0k':f(m,p,x,y)))
let board = document.getElementById("board"), pce = document.getElementById("pce"), b = [...Array(8)].map(_ => Array(8).fill(-1)), sel = 5; b[1][2] = 6; b[2][4] = 4; setClick(board, (x, y) => { b[y][x] = b[y][x] == sel ? -1 : sel; draw(); }); setClick(pce, (x, y) => { sel = x * 6 + 5 - y; draw(); }); draw(); function setClick(el, callback) { el.addEventListener("click", e => { let o = el.getBoundingClientRect(); callback(e.clientX - o.left >> 5, e.clientY - o.top >> 5); }) } function draw() { let html = "", m = []; for(let y = 0; y < 8; y++) for(let x = 0; x < 8; x++) { html += `<div class="sq ${x + y & 1 ? "dark" : "light"}">${~b[y][x] ? `&#${9812 + b[y][x]};` : ""}</div>`; (m[y] = m[y] || [])[x] = " KQRBNPkqrbnp"[b[y][x] + 1]; } document.getElementById("res").innerHTML = f(m) ? "YES" : "NO"; board.innerHTML = html; html = ""; for(let y = 0; y < 6; y++) for(let x = 0; x < 2; x++) html += `<div class="sq ${x * 6 + 5 - y == sel ? "sel" : x + y & 1 ? "dark" : "light"}">&#${9817 + x * 6 - y};</div>`; pce.innerHTML = html; }
```

```
body { font-family:Arial; } #board { float:left; width:256px; height:256px; } #pce { float:left; margin-left:32px; width:64px; height:192px; } .sq { float:left; width:32px; height:32px; line-height:32px; text-align:center; font-size:30px; cursor:pointer; } .dark { background-color:#7ab; } .light { background-color:#9cd; } .sel { background-color:#fd4; }
```

```
<p>Black king in check: <span id="res"></span></p><div id="board"></div><div id="pce"></div>
```

## Commented

### Main function

```
f = (               // f is a recursive function taking:
  m,                //   m[] = input matrix
  P,                //   P = piece on the target square
  X, Y              //   (X, Y) = position of the target square
) =>                //
m.some((r, y) =>    // for each row r[] at index y in m[]:
  r.some((p, x) =>  //   for each piece p at index x in r[]:
    P ?             //     if P is defined (2nd pass):
      {             //
        N: ...,     //       \    test whether the target square is
        B: ...,     //        |   attacked by the source square (x, y)
        R: ...,     //        |-- according to the piece p
        Q: ...,     //        |   these tests (which are detailed below)
        P: ...      //       /    return 0 for truthy
      }[p]          //
      + P           //       append P to the result
      == '0k'       //       if we get '0k', the enemy king is attacked
    :               //     else (1st pass):
      f(m, p, x, y) //       do a recursive call, using the current
                    //       square as the target square
  )                 //   end of inner some()
)                   // end of outer some()

```

### Knight test

```
(                   // define:
  H = x - X,        //   H = (x - X)²
  H *= H            //
) + (               // and:
  v = y - Y         //   v = y - Y
) * v               //
- 5                 // test whether H + v² = 5, which may only happen
                    // if we have H = 4, v² = 1 or H = 1, v² = 4

```

### Bishop test

```
B =                 // save the result in B
H - v * v |         // we must have H = v²
( g = A =>          // g is a recursive function
  u =               // which sets a flag u if the path from the source
  (                 // square to the target square is blocked:
    c =             //   c is the value of the square that is reached
    m[              //   when we move towards the target square
      A += -(A > Y) //   by adding the sign of Y - A to A
           | A < Y  //
    ][              //
      x += -(x > X) //   and adding the sign of X - x to x
           | x < X  //
    ]               //
  ) != P &&         //   stop when c = P
  c > g |           //   set u if c is greater than or equal to 'B'
                    //   (i.e. the square is not empty)
  g(A)              //   recursive call
)(y)                // initial call to g with A = y

```

### Rook test

```
u |= H *= v         // we must have u = 0 and either H = 0 or v = 0

```

### Queen test

```
B * u               // queen = bishop * rook

```

### Pawn test

```
H - 1               // we must have (x - X)² = 1 and y - Y = 1
                    // and H is now (x - X)² * (y - Y)

```

### King test

Assuming that the position is valid, a king may not be attacked by the other king. Therefore, there is no test at all for king attacks.

# Answer
> 3 votes
# Ruby, ~~192 170 167~~ 166 bytes

```
->s{z=!k=/k/=~s+=$/*9
72.times{|i|i%8<1?(C=D=i/8%3+i/24*9-10;J=k):" "!=W&&D=0
z||="RQBP"[~C%2,C/8>i%16?3:2]=~/#{W=s[J+=D]}/||s[i]*((i%9-k%9)*(i/9-k/9))**2==?N*4}
!!z}

```

Try it online!

Function taking a newline separated string as an argument. See meta for discussion of equivalence of strings and arrays, and use of sentinel values as separators/terminators. A final newline is required (It would cost 1 byte `$/*9`-\>`$/*10` to remove this requirement.) The two `!!` at the end ensure a clean true/false value is returned. Deleting them would save 2 bytes but return only a truthy/falsy output.

**Explanation**

Take a 72-character argument consisting of 8 lines each of 9 characters including the final newline. Add 9 newlines `$/`to the end. The newlines will act as non-space characters and prevent scanning from circling round to the other side of the board. Assign `k` to the index of the king by regex `/k/`. Assign `false=!k` to `z`. Iterate 72 times (scan up to 8 squares from the king in 9 possible directions. Simultaneously scan all 72 characters for knights.)

```
->s{z=!k=/k/=~s+=$/*9
72.times{|i|

```

If `i%8==0` set `J` to the location of the king and select a new direction `C=D` to scan in. Offsets for horizontal scanning are `i/8%3-1=[-1,0,1]` Offsets for vertical scanning are `i/8/3*9-9=[-9,0,9]`. Combining these gives diagonal scanning `+/-10` and `+/-8`. `0+0=0` is also generated as a ninth possible offset but makes no difference to the result. If `i%8>0` check if the last character scanned `W` was a space, and if not set `D=0` to prevent further scanning in that direction.

```
i%8<1?(C=D=i/8%3+i/24*9-10;J=k):" "!=W&&D=0

```

Check the character at `s[J+=D]` advancing `J` in direction `D`. Depending on the value of `C` select the values of character that would threaten the king. Where `C` is odd `+/-1`,`+/-9` they start at index 0: `RQ`. Where `C` is even `+/-8`,`+/-10` they start at index 1: `QBP`. Pawns should only be checked for on the first step in a diagonal direction `i%16=0` and where the `y` direction is positive `C/8>0`.

```
z||="RQBP"[~C%2,C/8>i%16?3:2]=~/#{W=s[J+=D]}/

```

Check also for knights, which threaten the king on squares `s[i]` where `(i%9-k%9)*(i/9-k/9)` is `+/-2`. Squaring this gives `4`. We take the character at `s[i]` and multiply by the numerical value giving a string of identical characters, then check if equal to the string `?N*4="NNNN"`. This is fewer bytes than separate string and numerical checks.

```
||s[i]*((i%9-k%9)*(i/9-k/9))**2==?N*4

```

Close the iteration loop and clean up the final value `z` from truthy/falsy to true/false by inverting twice.

```
}
!!z}

```

# Answer
> 1 votes
# Python 3, 258 bytes

I thought I'd try my own challenge cuz why not. It's not terrible but it could be better. I'll try to post an explanation when I have time.

Takes a 2D array (just like the challenge description).

```
f=lambda b:any(['PN'[(p:=z-60)>0]in(g:=f"{(' '*16).join(map(''.join,b)):^576}")[(k:=g.find('k'))-p]+(p>0)*g[k+p]for z in b'%#mkVR']+[((t:=g[k-8*n:k+8*n:n])[9+(i<0)*i:8+(i>0)*i].split()==[])*(t[i+8]in'RBQQ'[n<0::2])for n in[1,24,-23,-25]for i in range(-8,8)])

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=pairmap`, ~~316~~ 286 bytes

```
sub{map{map{($r,$c)=($t,$_)if($l=$_[$t][$_])eq'k';push@n,$t,$_ if'N'eq$l}0..7;++$t}@_;map{$v.=$_[$u=$r+$_][$c];$x.=$c+$_>=0&&$_[$u][$c+$_];$y.=$c-$_>=0&&$_[$u][$c-$_];}-$r..7-$r;(pairgrep{abs(($r-$a)*($c-$b))==2}@n)|(grep/[QR] *k|k *[QR]/,$v,"@{$_[$r]}")|grep/kP|[QB] *k|k *[QB]/,$x,$y}

```

Try it online!

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


# Question
Title: Tile the chessboard with four-colored triominoes
### Task:

Consider the problem: "given a chessboard with one square missing, cut it into 21 L-triominoes". There is a well-known constructive proof that this can be done for any square chessboard size that is a power of two. It works by splitting the chessboard into a smaller chessboard with the hole in it and one big triomino and then observing that that triomino can be cut into four triominoes recursively.

In this task, you are required to cut an 8x8 chessboard into L-shaped triominoes and then to color them with four colors such that no two adjacent triominoes have the same color.

### Specification:

Your input is the position of the hole, given as a pair of integers. You may choose which one is the column index and which one is the row index. You may choose if each starts at 0 or at 1 and away from which corner they increase. You may require A..H as the first coordinate instead of 0..7 or 1..8. You may also accept both coordinates packed into a single integer 0..63 or 1..64 in lexicographical order (row-major or column-major, left to right or right to left, up to down or down to up). You may write a full program, or a function.

You may output the tiling as ASCII, as colored ASCII or as graphical primitives. If you choose ASCII output, you may choose any four printable ASCII characters to represent the four colors. If you choose colored ASCII, you may choose any four printable ASCII characters or just one character other than space. The hole must be represented by the space character. If one of your characters is the space character, no triomino adjacent to the hole or at the chessboard edge may be of this color.

If you choose colored ASCII or graphical output, you may choose any four colors out of #000, #00F, #0F0, #0FF, #F00, #F0F, #FF0, #FFF or their closest equivalents available in your environment. If you choose graphical output, your graphical primitives must be filled squares at least 32x32 pixels in size and separated by no more than two pixels of other color. If the above exceeds the screen resolution of your environment, the minimum size requirement is relaxed to the largest square size that still fits on the screen.

You may choose any valid tiling of the given chessboard. You may choose any four-coloring of the tiling you choose. Your choice of four colors must be the same across all outputs, but you aren't required to use every color in every output.

## Examples:

Possible output for input = \[0, 0\] (top left corner)

```
 #??##??
##.?#..?
?..#??.#
??##.?##
##?..#??
#.??##.?
?..#?..#
??##??##

```

Another possible output of the same program (input = \[0, 7\]):

```
??#??#?
?##?##??
..xx..xx
.?x#.?x#
??##??##
..xx..xx
.?x#.?x#
??##??##

```

A different program may also produce, for the input of "D1" (note the nonstandard but allowed chessboard orientation),

```
AABBCCAA
ACBACBAC
CCAABBCC
 ABBAADD
AABDABDC
BBDDBBCC
BABBACAA
AABAACCA

```

# Answer
# JavaScript (ES6),  ~~184 ... 171~~  163 bytes

Takes input as `(x)(y)`, with \\$0\leq x\leq7\\$ and \\$0\leq y\leq7\\$. Outputs as a string with 3 colors (marked as \\$0\\$, \\$1\\$ and \\$2\\$).

```
h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)

```

Try it online!

## Method

We work on a matrix of \\$4\times4\\$ triominoes:

$$\begin{pmatrix} t\_0&t\_1&t\_2&t\_3\\ t\_4&t\_5&t\_6&t\_7\\ t\_8&t\_9&t\_{10}&t\_{11}\\ t\_{12}&t\_{13}&t\_{14}&t\_{15} \end{pmatrix}$$

Each triomino is one of:

The initial configuration of the matrix is as follows:

$$\begin{pmatrix} 3&2&3&2\\ 1&3&2&0\\ 3&1&0&2\\ 1&0&1&0 \end{pmatrix}$$

We alternate the first 2 colors just like we would on any chessboard, which gives:

The next steps are:

1. According to the quadrant in which the hole is located, we rotate one of the 4 center triominoes (\\$t\_5\\$, \\$t\_6\\$, \\$t\_9\\$ or \\$t\_{10}\\$) by 180°.
2. We rotate the triomino on which the hole is located (it may be the same triomino as in step #1), so that it does not cover the hole.
3. We fill the holes with the 3rd color (except the 'real' hole).

For instance, assuming that the hole is located at \\$(3,0)\\$, this gives:

And it that case, the final matrix is:

$$\begin{pmatrix} 3&\color{red}1&3&2\\ 1&\color{red}0&2&0\\ 3&1&0&2\\ 1&0&1&0 \end{pmatrix}$$

## Commented

```
h => v => (                       // (h, v) = hole coordinates
  a = [...'3232132031021010'],    // a[] = flat representation of the 4x4 matrix
  a[5 + (v & 4 | h > 3)] ^= 3,    // first rotation, achieved by XOR'ing with 3
  a[v / 2 << 2 | h / 2] =         // second rotation according to the
    v % 2 * 2 + h % 2,            // position of the hole within the triomino's square
  g = x =>                        // g is a recursive function that converts the 4x4
                                  // matrix into a 8x8 ASCII art
    y & 8 ?                       // if y = 8:
      ''                          //   stop recursion and return an empty string
    :                             // else:
      ( x < 8 ?                   //   if this is not the end of the row:
          x - h | y - v ?         //     if this is not the position of the hole:
            a[y / 2 << 2 | x / 2] //       if this part of the triomino located at this
            ^ y % 2 * 2 + x % 2 ? //       position is 'solid':
              (x ^ y) & 2         //         use either color #0 or color #2
            :                     //       else:
              1                   //         use color #1
          :                       //     else:
            ' '                   //       the hole is represented with a space
        :                         //   else:
          `\n`                    //     append a linefeed
      ) + g(-~x % 9 || !++y)      //   append the result of a recursive call
)(y = 0)                          // initial call to g with x = y = 0

```

## Graphical output

Click on the picture to set the position of the hole.

```
f=
h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)

;(u = (x, y) => { for(out = '', a = f(x)(y).split('\n'), y = 0; y < 8; y++) for(x = 0; x < 8; x++) out += `<div class="b b${a[y][x] == ' ' ? 'H' : a[y][x]}"></div>`; o.innerHTML = out; })(0, 0); o.onclick = e => u(e.clientX >> 4, e.clientY >> 4)
```

```
body { margin: 0; padding: 0; }
#o { width: 128px; height: 128px; }
.b { float: left; width: 14px; height: 14px; border: solid 1px; }
.b0 { background-color: #44f; border-color: #66f #22d #22d #66f; }
.b1 { background-color: #652e65; border-color: #874f87 #430c43 #430c43 #874f87; }
.b2 { background-color: #ffc90e; border-color: #ffeb2f #dda70c #dda70c #ffeb2f; }
.bH { border-color: #000; }
```

```
<div id="o"></div>
```
> 25 votes

# Answer
# Charcoal, 78 bytes

```
ＮθＮη”{⊞⊟¦≦⁶q×fΣ\⊙t×_⊟✳-Y⁴℅=⁶υ”≔›θ³ζ≔›η³εＦζ≦⁻⁷θＦε≦⁻⁷ηＪ⊕÷θ²⊕÷η²§#$⁺ⅈⅉＪθη Ｆζ‖Ｆε‖↓

```

Try it online! Link is to verbose version of code. Outputs using `#$%` characters. Explanation:

```
ＮθＮη

```

Input the co-ordinates of the blank square.

```
”{⊞⊟¦≦⁶q×fΣ\⊙t×_⊟✳-Y⁴℅=⁶υ”

```

Output a compressed string. It contains newlines so to avoid breaking up the flow of this explanation you'll find the string at the end of the answer.

```
≔›θ³ζ≔›η³εＦζ≦⁻⁷θＦε≦⁻⁷η

```

If either co-ordinate is greater than `3` then remember that fact and subtract the co-ordinate from 7.

```
Ｊ⊕÷θ²⊕÷η²§#$⁺ⅈⅉ

```

Jump to the nearest `%` of the top-left square of `%`s and overwrite it with a `#` or `$` as appropriate. (But this will get overwritten by the blank if it was already in this square.)

```
Ｊθη Ｆζ‖Ｆε‖↓

```

Blank out the square at the reduced co-ordinates and then reflect the output as necessary to get the blank to the original position.

```
##$$##$$
#%%$#%%$
$%%#$$%#
$$##%$##
##$%%#$$
#%$$##%$
$%%#$%%#
$$##$$##

```

I tried starting with the square of `%`s in the centre and working my way out to the desired co-ordinates but that took 90 bytes.
> 4 votes

# Answer
# Python3, 936 bytes

Naive search from scratch with random candidate neighbor piece selection and restart. Still, fairly efficient on test cases.

```
import random
R=range
P=[[(0,x),(y,0)]for x in[1,-1]for y in[1,-1]]
M=[(0,1),(0,-1),(-1,0),(1,0)]
F=random.sample
def W(c):
 while c:
  (x,y),*c=c;c={*c}
  q,s=[(x,y)],[(x,y)]
  for x,y in q:
   for X,Y in M:
    if(U:=(x+X,y+Y))in c:c-={U};q+=[U];s+=[U]
  if len(s)<3:return 0
 return 1
C=lambda c:[(x,y)for x,y in c if sum((x+X,y+Y)not in c for X,Y in M)>1]
def f(h):
 c={(x,y)for x in R(8)for y in R(8)}-{h}
 q=[(c,[])]
 for c,T in q:
  if not c:T={tuple(i):0 for i in T};break
  if not W(c):continue
  s=C(c)
  if s:
   O=[]
   for x,y in c:
    for p in P:
     if len(U:=[(x,y)]+[t for X,Y in p if(t:=(x+X,y+Y))in c])==3 and s[0]in U:O+=[U]
   if O:
    for U in F(O,min(2,len(O))):q+=[(c-{*U},T+[U])]
 q=[(T,T)]
 for a,T in q:
  if[]==a:return T
  n,*a=a
  if(L:={*R(1,5)}-{T[j]for j in T if j!=n and any((x+X,y+Y)in j for x,y in n for X,Y in M)}):
   for i in F(L,1):q+=[(a,{**T,n:i})]
def X(h):
 while not(b:=f(h)):1
 return b

```

Try it online!
> 1 votes

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