title: Random CSS Color code

text:
# Question
Title: Random CSS Color code
This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this:

```
'#'+(Math.random()*0xffffff).toString(16).slice(-6)

```

If you are not familiar with CSS color code read documentations here.

Can we do better? What about other languages?

# Answer
> 34 votes
## PHP 23 bytes

```
#<?=md5(rand())&ÿÿÿÿÿÿ;

```

Where `ÿ` is character 255. Bitwise and will truncate the string returned from `md5`, which is already in hexadecimal format.

# Answer
> 9 votes
Three character codes are valid too, so I can save some chars (`4095 == 0xfff`):

## Ruby, ~~24~~ ~~23~~ ~~22~~ 18

```
'#%03x'%rand(4095)

```

If I *have* to use a 6-char one, then:

## Ruby, ~~28~~ ~~27~~ ~~26~~ ~~24~~ 20

Shaved one character off because `8**8-1 == 0xffffff`

```
'#%06x'%rand(8**8-1)

```

Thanks to chron for the format string, saving 4 chars!

---

Cheating (with this xkcd strip in mind):

## Ruby/JS/Python/Perl/lots more, 6 (or 5)

```
"#a83"

```

I assure you, I generated it randomly!

An even cheatier version:

```
"red"

```

# Answer
> 8 votes
# Javascript

```
'#'+Math.random().toString(16).substr(2,6)

```

Just a little shorter at 42.

```
function randomColor() {
  return '#' + Math.random().toString(16).substr(2, 6);
}

for (var n = 0; n < 16*9; n++) {
  var el = document.createElement('SPAN');
  el.style.backgroundColor = randomColor();
  document.getElementById('demo').appendChild(el);
}
```

```
span { width: calc(100%/16);
       height: calc(100vh/9);
       margin-top: -7px;
       display: inline-block;
     }
```

```
<div id='demo'></div>
```

# Answer
> 5 votes
# Fish 79

```
vnnnnnnnn
601234567;
>xxxxxxxx<
 89""""""?
 nnABCDEF:
 vv""""""-
 vvoooooo1
 >>>>>>>>^

```

Not the shortest solution in the world, but it was fun to code :)

It's also not a uniform distribution, but all outputs have a non-zero probability 7 and F are most likely digits.

Outputs:

```
python fish.py randomColor.fish
07FFF7

python fish.py randomColor.fish
07EFD7

python fish.py randomColor.fish
366F67

python fish.py randomColor.fish
977FD7

python fish.py randomColor.fish
97F7F7

python fish.py randomColor.fish
87F6FF

```

# Answer
> 4 votes
# PowerShell, ~~28~~ 24 bytes

*-4 bytes thanks to @Julian!*

```
"#{0:X6}"-f(random 16MB)

```

Try it online!

# Answer
> 4 votes
# Vyxal , ~~8~~ 7 bytes

```
\#k66ƈṅ

```

Try it Online!

```
\#      # Push a #
    6ƈ  # Choose six...
  k6    # Hex digits
      ṅ # Appended to the #

```

# Answer
> 2 votes
## APL (17)

```
'#',(⎕D,⎕A)[6?16]

```

Explanation:

* `6?16`: 6 random numbers from 1 to 16
* `⎕D,⎕A`: the digits (`0..9`) followed by the alphabet (`A..Z`) (but only the first 16 values are ever used, i.e. `0..F`)
* `'#',`: add a `#` to the front

# Answer
> 2 votes
# Python 3, 44 bytes

```
from secrets import*
print("#"+token_hex(3))

```

Try it online!

Did you know this built-in python module? It was added in python 3.6 to include some random function for paswords (more informations here).

## How it works ?

Basicaly, I generate a random 3-bytes long hexadecimal string ... Yeah, that's it.

# Python 2, ~~32~~ 31 bytes

I also have the slightly less elegant : (also works in Python3 in ~~34~~ 33 bytes by adding parenthesis for the `print` function)

```
print"#%06x"%((id(0)>>16)%8**8)

```

Try it online!

This one uses the fact that at each execution of the code, python uses an indivdual memory address for each object. This memeory address change at each execution of the program. As the last 16 bits of this id are not random, I shifted the result before using a modulo to have the right number of bits

Thanks to pxeger for -1 bytes

# Answer
> 2 votes
# Zsh, 37 bytes

```
<<<\#`tr -dc 0-9a-f</*/ur*m|head -c6`

```

Try it online!

* `</*/ur*m`: input from `/dev/urandom` (shortened with wildcards)
* `tr -dc 0-9a-f`: keep only characters in the range `0-9a-f`
* `head -c6`: take the first 6 characters
* `<<<#```: prepend `#` and print

# Answer
> 2 votes
# Vyxal , 7 bytes

```
\#6(k6℅

```

Try it Online!

## Explanation

```
\#6(k6℅
\#      Push "#"
   (    For _
  6     in range(6):
    k6    "0123456789abcdef"
      ℅   Random item

Ṫ Concatenate the stack

```

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

```
print(f"{hash('a'):x}#"[:-8:-1])

```

# Answer
> 1 votes
## Bash (51)

```
od -N4 -An -tx /dev/urandom | cut -c2-7 | sed s/^/#/

```

# Answer
> 1 votes
# Python 3, 53 bytes

```
from random import*;print(f"#{randint(0,16**6):06x}")

```

Try it online!

# Answer
> 1 votes
# Python 3, 50 bytes

```
import time
print(f"#{int(time.time()%16**6):6x}")

```

Try it online!

Random generation by modulo of current time saves two precious bytes

Also 0 before 06x can be omitted

# Answer
> 1 votes
# Nim, 57 bytes

```
import colors,random
randomize()
echo 0xffffff.rand.Color

```

Try it online!

# Answer
> 1 votes
# Jelly, 9 bytes

```
6ØhX¤€”#;

```

Try it online!

## Explanation

```
6ØhX¤€”#;   Main niladic link
6           6
     €      Map
    ¤       (
 Øh           "0123456789abcdef"
   X          Choose random
    ¤       )
        ;   Prepend
      ”#      "#"

```

# Answer
> 1 votes
# Julia 1.0, 24 bytes

```
'#'repr(rand(UInt))[3:8]

```

Try it online!

# Answer
> 1 votes
# Japt `-P`, 11 bytes

```
Gö6 msG i'#

```

Test it

# Answer
> 1 votes
# Ly, ~~29~~ 26 bytes

```
'#o6['0'??'9G[p'(+,0]po,]p

```

Try it online!

At a high level, here's how this one works...

1. write out `#`
2. loop 6 times...
3. each iteration, write out a random digit in `0-f` range

And for people who like gory details about stacks. :)

```
'#o6['0'??'9G[p'(+,0]po,]p
'#o                        - push "#" on stack, print it as char
   6[                  ,]  - loop 6 times
     '0'?                  - push "0" and "?" codepoints on stack
         ?                 - pick a random number between them
          '9G              - is it greater then "9" codepoint?
             [p    0]p     - if/then, called if pick is > "9"
               '(          - push 28 on stack (Note 1)
                 +         - add 28 to random pick (Note 1)
                  ,        - decrement (Note 1)
                      o    - print top of stack as a char
                         p - clear the loop artifact from the stack

```

Note 1: Mapping the codepoints `:-?` to `a-f` means adding 27 to the codepoint. The shortest way to do that would be to push `'` onto the stack, but the code for that (at least on TIO) `''` doesn't work. So this code loads 28 (which is `(` then decrements the result with `,` instead.

# Answer
> 1 votes
# Java (JDK), 54 bytes

```
n->"#"+Long.toHexString((int)(Math.random()*0xffffff))

```

Try it online!

# Answer
> 1 votes
# C (tcc), ~~46~~ 43 bytes

*-3 bytes, thanks @ceilingcat*

```
main(){srand(main);printf("#%08X",rand());}

```

Try it online!

4 byte color codes are valid, the last byte is used as alpha.
C is weird with random numbers because of how old it is. While the code above is *technically* a valid answer, it does a really bad job because different compilers treat `rand()` differently and often use a suboptimal generator, in addition to not actually guaranteeing every possible color. Importing a better library for generation isn't exactly a good idea for Code Golf though.

# Answer
> 1 votes
# Mathematica, 30 bytes

`0xfff == 4095`, so we can just take a random integer from 0-4095 and convert it to hexadecimal form. We save a few characters using prefix and infix notation.

```
RandomInteger@4095~BaseForm~16

```

Try it online!

# Answer
> 0 votes
# Zsh (coreutils), 26 bytes

Using `jot`, originally in BSD Unix. Try it Online.

```
jot -w\#%x -r 1 0 16777216

```

# Answer
> 0 votes
#### Red, 18 bytes

```
random 255.255.255

```

# Answer
> 0 votes
# Python 3.8 (pre-release), 43 bytes

```
from os import*
print("#"+urandom(3).hex())

```

Try it online!

1 byte less than current top Python 3 sol by @Jakque, as I don't think that one by @Ivar Matstoms is fair

---
Tags: code-golf, random, css
---


title: Tips for golfing in Lean

text:
# Question
Title: Tips for golfing in Lean
Lean is a theorem prover and programming language. It's also as of writing the Language of the Month!

What tips do people have for golfing in Lean? As always, tips should be specific to to Lean (e.g. "Remove comments" is not an answer), and stick to a single tip per answer.

# Answer
# Introductions

If you've just finished the natural number game you may be familiar with the `intro` tactic, this can be used to create implications / functions. However this tactic is rarely the golfiest.

If your intro is the first part of your proof then an implicit forall is probably better. Compare:

```
def q:list ℕ→ℕ:=by{intro x,induction x,exact 0,exact x_hd+x_ih}

```

with

```
def q(x:list ℕ):ℕ:=by{induction x,exact 0,exact x_hd+x_ih}

```

This is frequently always your best option. However if the type of your function can be inferred you have other options.

```
def f:ℕ→ℕ:=by{intro x,exact x+3}
def f(x:ℕ):ℕ:=by{exact x+3}
def f:=λx,by{exact x+3}
def f(x):=by{exact x+3}

```

These are ordered by length so implicit forall (the last option is still implicit forall) is the shortest. But the lambda can expression can have the `def f:=` removed if the function is your submission, making it the shortest in that case.
> 5 votes

# Answer
## Use `by` instead of `begin ... end`

`by` can be shorter than `begin` and `end`.

```
def foo(m:ℕ):m=m:=begin refl,end

```

is longer than

```
def bar(m:ℕ):m=m :=by refl

```

You can also use it for multiple tactics, though you'll need to encase the tactics in braces, as Wheat Wizard pointed out. For example, `by{rw add_assoc,refl}` is shorter than `begin rw add_assoc,refl end`.
> 4 votes

# Answer
## The `;` and `<|>` combinators.

`;` makes it so that all subgoals created by the last tactic have the next tactic applied; for example, `lemma asda (n : ℕ) : n = n := by { induction n; refl }` is a valid proof. As a bonus, it also allows you to not use the braces (e.g. `def k(n:ℕ):n=n:=by induction n;refl`).

The `<|>` is a bit more niche, but still useful; it allows you to do one tactic, and if it fails, the other instead. It also allows for no braces (although this is longer than `,`, so not as useful). For example:

```
example(x):0+x=x:=by induction x;refl<|>rw nat.zero_add

```
> 3 votes

---
Tags: code-golf, tips, lean
---


title: Is this Flow Free puzzle trivial?

text:
# Question
Title: Is this Flow Free puzzle trivial?
## Background

*Flow Free* is a series of puzzle games whose objective is to connect all the same-colored pairs of dots on the grid. In this challenge, we consider the original game on a rectangular grid (no variations like bridges, warps, or hexagonal grids).

A puzzle in *Flow Free* might look like this:

```
Puzzle   Solution
....1    11111
.....    13333
..24.    13243
1....    13243
23...    23243
...43    22243

```

One of the easiest techniques in the puzzle is that, if you can connect two dots by following the "border cells" in only one way, such a connection is always correct.

Border cells are unsolved cells that are (orthogonally or diagonally) adjacent to a solved cell (including those outside of the grid).

In order to use this technique, the two dots themselves must also be border cells, and two adjacent border cells can be connected only if they're adjacent to some common solved cell. See the explanation below for an illustration.

A puzzle is said to be "trivial" if this technique can be used from the start to the end.

The above example is an example of a trivial puzzle. Let's see how it is so.

```
Puzzle   Border   Trivial pair
....1    #####    11111
.....    #...#    1...#
..24.    #...#    1...#
1....    #...#    1...#
23...    #...#    #...#
...43    #####    #####

 ....     ####     3333
 .24.     #..#     3..3
 ....     #..#     3..3
23...    ##..#    #3..3
...43    #####    ####3

  24       ##       24
  ..       ##       24
2 ..     # ##     2 24
...4     ####     2224

```

Note that, in the last step, the following paths are not considered because a horizontal connection in the middle of the width-2 strip is not valid ("two adjacent border cells can be connected only if they're adjacent to some common solved cell"):

```
  2.     .4
  22     44
2 22   . 4.
222.   ..44

```

## Challenge

Given a solved Flow Free puzzle, determine if it is trivial.

The input can be taken as a single string/array or a list of lines. You may assume only the digits 1-9 are used, and each line represented by each digit is a valid polystrip of length 3 or higher.

For output, you can choose to

* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code in bytes wins.

## Test cases

### Truthy (is trivial)

```
11111
12221

11113
33333
32222

11111
13333
13243
13243
23243
22243

```

### Falsy (is not trivial)

m90 provided the last test case, which is specifically constructed to use an invalid bridge (the line 5).

```
11121
13121
13121
13111

11122
13121
13121
33111

13333
13443
13343
11243
21243
22244

1116777
1226666
1125555
5555344
8888334
9998444

```

# Answer
# Python 3, 331 bytes

```
def T(p):
 w=len(p[0])+2;p='..'.join(p).join(['.'*(w+1)]*2);d={};N={}
 for i,c in enumerate(p):d[c]=d.get(c,set())|{i};N[i]={i-w-1,i-w,i-w+1,i-1,i+1,i+w-1,i+w,i+w+1}
 u=d.pop('.')
 while d:
  for k,v in d.items():
   if not any(abs(a-b)in(1,w)and not(N[a]&N[b]&u)for a in v for b in v):u|=v;d.pop(k);break
  else:return 0
 return 1

```

Try it online!

Takes a list of strings. Returns 1 for a trivial solution, otherwise returns 0. On TIO it is run against all the test cases.

Here's brief explanation:

`p` is converted to a long string with '.' marking the initial out-of-bounds cells. This is so neighbors don't need to be checked if their outside the grid.

`d` is a dict mapping symbols in the solution to their set of indexes in `p`.

`N` maps indexes to neighbors.

`u` is a set of used (i.e., solved) cells. It gets initialized to the indices of the '.'s in `p`.

`k` and `v` are a symbol from the grid and it's set indices in `p`.

`if not any(...)` makes sure that any adjacent indices in `v` have a common neighbor cell in `u`. If True, `v` is a valid trivial path, it is added to `u` and removed from `d`; and the `for k,v` loop is exited early.

If the `for k,v...` loop runs to the end, there aren't any trivial paths, so return 0 (Falsey).

If `while d` ends, all the paths were trivial, so return 1 (Truthy).
> 4 votes

# Answer
# BQN, 124 114 bytes

```
∨´{0=⥊?1;W←(<4⌽⥊)⎉2 3‿3↕⊢↑˝·≍⟜¬2+≢⋄≡◶‿0∧´¬(<≡¨((¨0=1↓¨W)∘≥⚇1{⍟≢(⌈´×·×⊑)¨W}+`⊸×⌾⥊0=)∧¨<)¨⊸/}(⍷∘⥊=¨<)

```

Try it here.

Fairly unsophisticated method: it flood fills the solved cells to find disconnected regions, then marks as solved cells where all cells of the same number border the edge or a single solved region, then repeats until all cells are solved, or the input no longer changes.

Can definitely be golfed a lot more. In particular, I think it could probably be rewritten to avoid having to use rank 2 (`⎉2`) everywhere.

Edit: rewrote to use each (`¨`) instead of rank when possible and some other tweaks. Still a few parts I'm convinced can be improved, but I think ultimately trying a completely different approach would be better.
> 4 votes

---
Tags: code-golf, array, decision-problem, grid, puzzle-solver
---


title: Restricted mini challenges Cop's Thread

text:
# Question
Title: Restricted mini challenges Cop's Thread
> Robber's thread

Your task as cops is to select three things:

* A programming language
* An OEIS sequence
* A byte set

You are then to secretly write a program in that language that computes the nth term sequence using only the bytes in the set. You will reveal the three pieces of information so that robbers can try to figure out the program.

Answers will be scored by the number of bytes in the byte set with more score being good. Cracked answers have an automatic score of 0. If your answer is uncracked after one week you may reveal the intended program and mark your answer as "safe".

Answers must be capable of calculating every term in the b-files of the sequence, but are not required to calculate any terms after.

Sequences can be either 1 or 0 indexed for both cops and robbers.

Here is a Python Script that checks if your code matches the given byte set.

# Answer
## Haskell, A209229, (cracked)

11 characters (including newline):

```
s<=[ ]
how!

```

Outputs True/False as an indicator function for powers of 2:

```
1 => True
2 => True
3 => False
4 => True
5 => False
6 => False
7 => False
8 => True
9 => False
...

```

Inputs are positive integers.
> 12 votes

# Answer
# Python 2, A000045 (Cracked)

```
ml:= input(as,forge)

```

it contains a whitespace and a newline
Try it Online!
Intended solution
> 5 votes

# Answer
## Haskell, A000045 (cracked)

I made up my mind, I think I like `t` more than `s`.

So let's use these 30 bytes (including newline) instead:

```
abcdeFgh|jklmnopqrtTuvwxyz
=()

```

Please note that the general challenge description demands that

> Answers must be capable of calculating every term in the b-files of the sequence \[...\].

In this case, the b-file goes up to the 2000th number, which is way beyond what can be computed using `Int`.
> 5 votes

# Answer
# Octave, A000290, Cracked!

The sequence is the square numbers: **0, 1, 4, 9, 16, 25, 36, 49 ...** (so that you don't have to check the link).

```
'()/@^_

```
> 4 votes

# Answer
## Haskell, A000045 (Cracked)

Everyone likes Fibonacci numbers, I like Haskell...

I have carefully selected 30 bytes for you: the lowercase letters except `f`, `i` and `t`, you get the uppercase letters `F` and `T` and the pipe symbol `|` instead, and the three symbols `=()`, and newline. Here they are again:

```
abcdeFgh|jklmnopqrsTuvwxyz
=()

```
> 4 votes

# Answer
# Haskell, A034262, 43 bytes, cracked

`!"#%',.=?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_{|}~`

Computes `a(n) = n³ + n`.
> 4 votes

# Answer
## Haskell, A009056 (cracked)

Another simple one, now again with enough letters to make it look like ordinary Haskell and maybe for you to amaze me by finding a solution completely different from mine.

The sequence is *Numbers \>=3* and the charset consists of these 30 bytes:

```
{[abcdefghijklmnopqr uvwxyz]}.

```

---

The crack has some nice techniques. I was just thinking of this:

> `head . flip drop [ floor pi .. ]`
> 4 votes

# Answer
# C (C99), A000005, 25 Bytes#, Cracked!

These are the bytes for a full problem, takes n as a command line argument and outputs answer to stdout.(Space is included in bytecount).

```
<=>,;!"()*%+acdfhimnoprt

```
> 3 votes

# Answer
# Unary, A002275, 1 Byte

Byte set:

```
0

```

I had to at least try it :3

(I don't think it will be particularly hard seeing as every command in the language is available)
> 3 votes

# Answer
# Cubix, A000027 (SAFE) 17 points

```
!&')-/0;@Oiru.NSQ

```

My solution:

```
!O!;i)!/u&!!r-)0'u;;!@

```

watch it online here

I originally did this without `.NSQ` but I figured I could add them safely.

Explanation:

This sequence is just "The Positive Integers". However, Cubix has three input commands, `i`, which reads in a single char (pushing `-1` if input is empty), `A`, which reads in the rest of the input as chars (pushing a `-1` to the bettom of the stack), and `I`, which reads the next number off the input (pushing `0` if there isn't a match). So naturally, I only provided `i` which reads in digits as their ascii value. uh-oh. Additionally, `-1` is the usual marker for end of input, in conjunction with `?` so I got rid of `?`, forcing me to use `!` (skip next instruction if TOS is not zero) for control flow. Finally, I thought I needed `&` to concatenate digits for printing with `O` (which outputs the top of stack as a number), but I realize now that that wasn't necessary either!

Another part of the challenge was originally to not have `.` the no-op character, but you can use pairs of `!` instead if you're careful:

```
    ! O
    ! ;
i ) ! / u & ! !
r - ) 0 ' u ; ;
    ! @
    . .

```

`i)` : read input, increment.

`!/` : if top of stack is zero (end of input), turn left

left: `;O.@` : pop top of stack, output as number, halt.

otherwise:

`u'0`: push char code of `0` to top of stack

`)-r`: increment, subtract, and rotate

`;;` : pop top of stack twice

`u&` : concatenate digits

`!!` : net zero effect, now we are at `i)` again.
> 3 votes

# Answer
# Hexagony, A057077, 77 bytes

Periodic sequence `1, 1, -1, -1`. As a list:

```
a(0) = 1
a(1) = 1
a(2) = -1
a(3) = -1
a(4) = 1
a(5) = 1
a(6) = -1
   ...

```

Character set (edited), which includes a newline and a space character:

```
!%&(),0123456789;?@ABCDEFGHIJKLMOPQRSTUVWXYZ^abcdefghijklmnopqrstuvwxyz[]#.

```

Try it online!
> 3 votes

# Answer
# Perl 5, A000030 (Cracked)

Byte set:

```
imnprt7 $;()<>=~.

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), 17 bytes, A000290 (Cracked)

Again, this is the simple square sequence a(n) = n2.

Byte set:

```
$()=>CI`abelotv{}

```
> 3 votes

# Answer
# Seed, A005408 (Odd Numbers) - Safe

Here's a slightly more challenging one. You may use any characters valid in Seed:

```
[0-9 ]

```

You shouldn't be able to brute force this one in a week unless you have a monster of a computer. Good luck! It's crackable.

### Hint

> This is the Befunge-98 program used in my solution: `9&2*1-.@` (the `9` can be removed, but my solution just happens to have one)

### Solution

```
8 [encoded data, 6011 characters]

```
> 3 votes

# Answer
## Haskell, A000045 (cracked)

It's cracked, and I won't start a new version, but if you want to play more: it's possible without `y`, and it's possible to be efficient.

---

I apologize for leading you in wrong directions by giving a `g`. Let's do the same without!

Here are the 29 remaining bytes (including newline):

```
abcdeFh|jklmnopqrtTuvwxyz
=()

```

Again, remember that `Int` won't be enough to compute the 2000th Fibonacci number which is needed because it is in the b-file.
> 3 votes

# Answer
## Haskell, A000045 (cracked)

This is kindof (as announced) not a new version, but completely different. (Right?)

I still hope I can make you rediscover my nice little observation.

This time you are asked to implement the Fibonacci sequence using a charset of size 17, which (as far as I know) contains only ~~one~~ two unneeded chars:

```
eilnt=(,).[ ]_:0!

```

Note that there is no newline (but feel free to show a version which has them for readability) and remember that you have to be able to compute the 2000th Fibonacci number.
> 3 votes

# Answer
# Braingolf, A010701 Score: 9 \[SAFE\]

Byte set:

```
0x21, 0x24, 0x2F, 0x3A, 0x3F, 0x5B, 0x5D, 0x5F, 0x7C

```

Try it Online!

The code:

```
$_/[!?:]|[!?:]|

```

Try it online!

## Explanation

```
$_/[!?:]|[!?:]|  Implicit input from commandline args
$_               Remove top of stack
  /              Niladic division, push 5
   [...]         While loop, decrements bottom of stack at start of loop
                 then decrements each time loop reaches end
                 Exits when bottom of stack is 0
    !?:.|        If conditional without popping, runs contained code if top of stack is 0
                 This is the sneaky trick here. The conditional skips the end of the loop
                 As a result, this whole block from [ to | effectively acts as a decrement.
         [!?:]|  We do this twice to lower the 5 we pushed down to 3
                 Implicit output of top of stack.

```
> 2 votes

# Answer
# cQuents, A000217, Cracked

Byteset:

```
$:=1;
\-

```

~~Note that this uses a feature that I haven't pushed the documentation for yet, so I'll push that tonight, if you wait until then. (Or you can slop through my source code... have fun).~~ Documentation pushed. Would be a byte less if a recent bugfix was on TIO.

Intended solution:

> `=1-1:--\1$
>  ;$`

Try It Online!
> 2 votes

# Answer
# R, A000142, (Cracked)

Byte set:

```
-()*,`=cfinotu

```

Intended solution:

> `f=function(n,c=n==n)'if'(n,f(n-(n==n),c*n),c*(n==n))`
> 2 votes

# Answer
# Python 2, A000045 (Cracked)

```
l:= input(a,forge)[]

```

it contains a whitespace and a newline
Try it Online!
Intended solution
> 2 votes

# Answer
# PowerShell, A000012, 19 bytes, SAFE

```

$.0=[]acefilnorstv

```

Includes a newline and 18 other bytes. Good luck.

Try it online!

---

### Intended Solution:

```
$a=$a[0]
$error[0].invocationinfo.offsetinline

```

Try it online!

This sets `$a` to be the value of an uninitialized variable `$a` indexed at `[0]`. Since that won't work, you get an error stating the following:

```
Cannot index into a null array.
At line:1 char:1
+ $a=$a[0]
+ ~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

```

The second line then pulls the `.InvocationInfo` and `.OffsetInLine` (i.e., where the error occurred), which in this case is always `1`, and hence the A000012 sequence.
> 2 votes

# Answer
# cQuents, A000027, Cracked

```

 !"#%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```

That's right! You get all of ASCII! Wait... there's no `$`... what's `$` again in cQuents? Oh, yeah, the index builtin. Well, tough luck :/

Intended Solution:

> `#|A:A`

Try it online!
> 2 votes

# Answer
# CJam, A000042, cracked by Lynn

Byte set:

```
{})_%si

```
> 2 votes

# Answer
# R, A000290, (cracked)

Byte set:

```
()%cfinotu

```
> 2 votes

# Answer
# Ruby, A000004, 5 bytes, Cracked

Just messing around to start off. Should be easy for anyone familiar with Ruby. It's a low score, but whatever.

```
/np.$

```

---

Cracked, unintended exploit

Cracked (intended answer using `n` flag)
> 2 votes

# Answer
# Python 3, A007504 (Cracked)

This byteset, including newline:

```
bfuwo)nm1h[=(t+;0a
sig%pr, le:]

```

My code does not provide infinite output, but can compute the entire b-list.
> 2 votes

# Answer
## JavaScript (ES6), ~~13~~ 10 bytes, A000045, Cracked

This should be easy.

This is the Fibonacci sequence: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.

Byte set:

```
$()-:<=>?[]_~

```

**Edit:**

It can be even done with the following 10 bytes:

```
$()-:=>?_~

```
> 2 votes

# Answer
## Snowman, 212 bytes, A000042

```
#$%&*01:;=?@CEFGHIJLMOQUVXYZbcdefghijlmnopqsuvxyz~

```

... plus space, 0x00-0x1f inclusive, and 0x7f-0xff inclusive.
> 2 votes

# Answer
# Python3, A008615, Cracked

Bytemap (with newline):

```
n)ir=-
(u0*pt

```
> 2 votes

# Answer
# R, A105311, (Cracked)

Byte set:

```
'%(),:=acdegilnopstx

```
> 2 votes

# Answer
# R, A105311, (cracked)

```
'%(),:=acdeginpstx

```

Let's try this without the `l` or `o`.

Since this has been cracked, the intended solution:

> `cat(diag(diag((a=scan()))%x%diag((a==a):a)),sep='')`. `diag` is an interesting function, that can be used in three different ways. When presented with a single integer (`diag(n)`), it creates a NxN matrix with 1 on the diagonal. When presented with a vector (`diag(1:n)`), it creates an NxN matrix with the vector on the diagonal. When presented with a matrix (`diag(diag(n))`), it returns the diagonal as a vector. `%x%` computed the Kronecker product of two matrices, where each element in matrix 1 is multiplied with each element in matrix 2 separately. Doing this with a length `n` identity matrix and a `1:n` diagonal matrix, creates a length `n^2` diagonal matrix with `1:n` repeated `n` times. `diag` extracts that again, and `cat` prints.
> 2 votes

# Answer
# Befunge, A000142, 29 Bytes, (Cracked)

```
Byte Set: @.$_ ^*:\v>-1&

```

If you can't tell, that Byte set includes a space.

This should be *moderately* easy to solve.

Edit: Forgot the "A" before the OEIS
> 2 votes

# Answer
# R, A057077, (cracked)

```
1, 1, -1, -1, 1, 1, -1, -1, etc

```

Byte set:

```
()*/=2abcinopst

```

0-indexed.
> 2 votes

# Answer
# C, A027868 (Cracked)

I don't expect this to last too long...

Byte set: `int (){reu<5?-:/;}`
> 2 votes

# Answer
# Python 2, A000142, cracked

Probably not too difficult, but since I really enjoyed solving these I thought I'll be a cop for once. Here's the byteset (first one is a space):

```
 ()*-:=abcdfghijklmoqruwyzABCDEFGHIJKLMNOPQRSTUVWXYZ

```

### Intended solution

LyricLy's solution is much cleaner, but here's the one I had in mind:

> Basically it's the same but instead of using `bool(r)` for `1` I used `(r-r)**(r-r)`: `f = lambda r: (r==r-r or r==(r-r)**(r-r))*(r-r)**(r-r) or r*blam(r-(r-r)**(r-r))`
> 2 votes

# Answer
# CPython 3.6.2, A000002 (cracked)

I don't want anybody running out of single-character variables, so I'm giving you 70 pseudo-random characters courtesy of Latin-1.

```
·èõÉÀ]ýÜâô¾×l¡¿Ós¦Í½²uÊi´#¬©Åñ[);?ò
à¢ådêøóÎÐþÒÏ®,(Öß.=Õc_ö\§éºún$tÞb¨

```

This is evil. You can't make a `for` loop. You can't make a `while` loop. You can't even `try` to do anything, much less `except`. I have given a new line so that you can use more than one statement, but there aren't any spaces, tabs or even colons to let you use any sort of flow control. There are no numbers. There are no strings. There is nothing of any use.

You do have `\` and `#`, though, so you can write clear code with soft breaks and comments.

That is, if you speak Jelly.
> 2 votes

# Answer
# JavaScript (ES6), A000035, cracked

A000035 is **n mod 2**, in case the site goes down or you're too lazy to check yourself. Charset:

```
023456789\`efu

```

Taking the "somehow still Turing-complete" route. I suppose I could've added 51 or so non-ASCII chars to improve my score, but that feels kind of like cheating.

Takes input through `prompt` and outputs through `alert`, and can be run in any modern browser.

---

Intended solution:

\u0046\u0075\u006e\u0063\u0074\u0069\u006f\u006e`\u0046\u0075\u006e\u0063\u0074\u0069\u006f\u006e\u0028\u0046\u0075\u006e\u0063\u0074\u0069\u006f\u006e\u0028\u0022\u0072\u0065\u0074\u0075\u0072\u006e\u0028\u0034\u0038\u0032\u002f\u0032\u0029\u002e\u0074\u006f\u0053\u0074\u0072\u0069\u006e\u0067\u0028\u0032\u0032\u0029\\u002\u0062\u0027\u0065\u0072\u0074\u0028\u0070\u0072\u006f\\u006\u0064\u0070\u0074\u0028\u0029\u0025\u0032\u0029\u0027\u0022\u0029\u0028\u0029\u0029\u0028\u0029```</code></pre>

which, when the escapes are removed, translates to

<pre><code>Function`Function(Function("return(482/2).toString(22)\u002b'ert(pro\u006dpt()%2)'")())()```

which simplifies again to

Function`Function(Function("return(482/2).toString(22)+'ert(prompt()%2)'")())()```</code></pre>

This works because JavaScript allows `\uXXXX` escapes in variable names (though not in arbitrary code, as Java does). The outer `Function`code```` is necessary to run the code at all, since the entire thing needs to be escaped.

(If you're confused about how this works: JavaScript has something called tagged template literals, which for our purposes is just a function call on a string; it just uses `f`string`` instead of `f("code")`. So `Function`code```` is about the same as `Function("code")()`.)

Now, because of the lack of the hexadecimal chars `1abcd`, we'll have to double-encode certain necessary characters such as the `m` in `prompt()`. So instead of `\u006d`, it becomes `\\u006\u0064`. But now we need to evaluate this as a string twice to make sure this gets fully decoded. (`pro\u006dpt()` would work just fine, but using `\u002b` as `+` would not.) This is what the second `Function(code)()` is for.

One further obstacle exists: there's no `1` in the charset, necessary to create an `a` from `\u0061`. So there's no way to generate an `a` by unescaping a string (I checked, the octal representation is `\141`). Instead, we can generate it with e.g. `(20/2).toString(20)`. I went ahead and generated `al` in this manner because `l` would require double-escaping like `m`.

But the problem now is that the innermost `Function` call is now just generating a string. In order to actually *execute* it, we need to return it from the function and pass it to a *third* `Function` call. This we do, and finally our journey is complete.

<sup>\*I am aware of using `${}` within template literals, but those aren't in the charset, alright?</sup>
> 2 votes

# Answer
# Cubically, A016742 (Cracked)

This sequence is even square numbers: `0, 4, 16, 36, 64, ...`

**Byte set:**

* Any letter except `[UuDdLlRrFfBb]`
* The digits `[6789]`
* Any symbol except `[-^:@/]`
* Anything not mentioned in the ASCII character set, including whitespace.

Try It Online!
> 2 votes

# Answer
# Python 3, A000002, Cracked with the intended solution

These are the bytes of a full program, 0-indexed solution for the Kolakoski sequence: OEIS A000002.

```
pg*rn:e+%2a tu]
(=foi[)1l,

```

This contains a space, a newline, and all the other characters in the snippet above. ~~Hopefully this won't be too easy to crack :)~~
> 1 votes

# Answer
# Python 2, A000042, 11 Bytes (Cracked)

Byte set:

```
int(pru*1)'

```

Answer:

> print '1'\*input()

*Note: This is my first ever answer on PPCG, and I may have made a mistake...*
> 1 votes

# Answer
# cQuents, A033307, Safe

```
Fe_pz:"/`'-2;
```

Try it online!

Explanation:

> `":z--F_p-2`
> Try it online! `":` means a char sequence; basically, the output needed. Now, we need to just get the current index, which would usually be `$`. `z` starts out as `0` and is the previous number from then on, so we need just to add one to it. `--` is the equivalent of `+`, and `F_p-2` means `Floor(Pi-2)`, which works.
> 1 votes

# Answer
## JavaScript (ES6), 4 bytes, A005408 (Cracked)

This should be an easy one. Odd numbers: a(n) = 2n+1

Byte set:

```
$+=>

```
> 1 votes

# Answer
# CJam, A000142, 8 bytes, Cracked

Byteset: `{}*+)%1\`
> 1 votes

# Answer
# Python 2, A006577, Cracked

Byte set:

```
+s-t,n u
r)i1(d>]f[:e&

```

Shouldn't be too hard, but still fun.

EDIT: Cracked by @BruceForte. The crack looks just about identical to my crack, but here's mine for reference.

Try it Online
> 1 votes

# Answer
# Python 2, A001146, Cracked

Byte set:

```
print(2*u)

```
> 1 votes

# Answer
# Unreadable, A000027, 92 bytes, Cracked

Byte Set:

```
!"#%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Also add space and newline
> 1 votes

# Answer
# LOLCODE, A000290, Cracked

Byte set:

```
.12ABDEFGHIKLMNOPRSTUVXY

```

The byte set also includes space and newline.

*HAS FUNZ!*
> 1 votes

# Answer
# Perl 5, A007094 (Cracked)

Numbers in base 8

Byte set `sub {if($_[1]!=%/)ret-n;}`

Try it online!
> 1 votes

# Answer
# Octave, A000045

This produces the Fibonacci numbers, OEIS A000045. There's both a space and a newline in there.

It's 0-indexed, so input `0` gives `0`.

```

 ()-;=>cdefinotu

```
> 1 votes

# Answer
# JavaScript, A000004 (Cracked)

Look from the other side

```
at~N+1

```

*Step Hen*'s solution

> ~NaN+1

My solution #1

> ~1+1+1

#2

> ~~NaN
> 1 votes

# Answer
# Ly, A005150, Cracked

```
!$+-012<=>JS[]lnprsu

```

Well. Let's see how this plays out.
> 1 votes

# Answer
# dc, A028444 (cracked)

`-?/*+23568dpr`

There are no spaces in the byte set, but that’s not a big deal for `dc`.

Sequence is indexed at `0`.

Note: Rado’s Sigma function grows faster than any computable function and is thus **noncomputable**!

> Intended solution: `?dddddd***3*rdd**22*-rd*53*+r26*-8/p`
> 1 votes

# Answer
## CPython 3.6.2, A000796 (cracked)

I like Latin-1. Here's another 70 characters.

```
,Ðûô[u÷ÎÆ»énb¤Äö]?có´å¡ùÇõÓ«;Ñ$èñÙdÁ¼
¢üÔltsð½(þÚ#ä.×çÈýÅ§ã¯\)³íï¬Â±¥_Ê=iÌ

```

This bunch of characters can calculate the decimal digits of pi. *Surely* this requires flow control. And yet there isn't a colon, so that is impossible. You can't even `eval` a string when there is neither `eval` nor a string.

I'll give a hint: my program takes input from `stdin` and outputs to `stdout`, but I am almost completely certain that it is possible to use other I/O methods.
> 1 votes

# Answer
# shortC, A000240, 64 bytes

Uses the characters in this ASCII map:

```
    "     %     ( ) * + , -
  1 2                       >
@ A         F     I
    R   T             [   ]
  a     d         i         n o
p       t     w       {   }

```

Map credit: ETHproductions
> 1 votes

# Answer
# Perl 5 `-n`, A000290: the squares, score:18, safe.

```
 ;cdeghijklnopqrst

```

## Rules

* Input from stdin, as a string of decimal integer.

## Intended solution

> `int or print;int or die;int ne length q q q or print;int ne length q q q or die;s ss s;chr sqrt length eq chr or redo;print length`

> Try it online!

> Usage: from stdin, as a decimal integer. 0-indexed. Can accept only a line. Input shall match `/^\d+$/`. No trailing LF to your input. Output from stdin, as decimal integers. If your input is 0 or 1, the program dies but please don't care for such thing; this specification is just for this challenge.
> 1 votes

# Answer
# R, A000027 (Cracked)

An easy one to warm up :)

Byteset:

```
eiytnd

```

Solution:

> `identity` returns the input, so maps n to n.
> 0 votes

# Answer
# Python 2, 24 bytes, A001246, cracked

Byte set:

```

 )(+*-/12:=<acbdfmlonrx

```

Try it online!
> 0 votes

# Answer
# Python 2, 21 bytes, A157433, cracked

```

6ut1 28rp5=)ni+03(*7

```

Try it online!

Original solution:

> `n=input()
> print 128*n**2+2336*n+10657`

Probably super easy, but eh, I have `=)`.
> 0 votes

# Answer
# Jelly, 16 bytes, A000042 (Cracked)

Byte Set:

```
%1@JOiv¤ØȷḌṁị“”€

```

(The two quotes are different: one is opening and the other is closing).

(uses Jelly codepage)

The sequence is: `a(n)` is the unary representation of `n`.
> 0 votes

# Answer
# Python 3, 19 byteset, A000290, Cracked

This is the perfect squares: `0, 1, 4, 9, ...`.

Byteset:

```
(fam, l+db-ise=10:)
```

Note: I had two iterations with duplicate characters (and missing characters) because I'm dumb.

My solution (not very efficient):

> `f=lambda l,a=1,b=0:f(l-1,a+1+1,b+a) if l else b`

Try it online!
> 0 votes

# Answer
# MATL, 11 bytes, A000984

Uses some of these bytes (ASCII):

```
$&)+/:HZdep

```

Due to floating-point precision, results are only guaranteed to be accurate up to the `26`-th term. I hope that's acceptable.
> 0 votes

# Answer
# Ruby, A000217, 15 bytes, Cracked

Uses the `-p` flag to take input from stdin and output to stdout.

```
$mu.to_vim[d=s]

```

Intended solution:

> `$_=[$...$_.to_i][$..div$$].sum`
> 0 votes

# Answer
# JavaScript (ES6), 10 bytes, A000007

Byte set: `-)$>yRa=A(`
> 0 votes

# Answer
# Seed, A000027 (Counting Numbers) (Cracked)

You may use any valid character in Seed:

```
[0-9 ]

```

Have fun! The resulting Befunge program is short, so you should definitely be able to brute force it within a week (if you're crazy enough to do that).

## My Solution:

My solution is a little bit longer than Lynn's solution...

```
4 [encoded data, 6011 characters]

```
> 0 votes

# Answer
# C, A000312 (cracked)

`-,;:?(){} eglnortu`

The specs call for a complete program, however this would add many more characters to the byte set making the challenge trivial. Instead, you’ll be providing the code within this template:

```
«your-code-composed-of-characters-in-byte-set»

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv)
{
    int n = argc > 1? atoi(argv[1]): 0;
    printf("%d ^ %d = %lld\n", n, n, «your-function-name»(n));
    return 0;
}

```

Note that your code comes before the `#include`s.

> Answer: `long long l(long long o,long long n){return o- -n;} long long o(long long n,long long g){return g?(--g?l(o(n,g),n):n):g;} long long n(long long g,long long l){return l?o(n(g,--l),g):- --l;} long long g(long long l){return n(l,l);}` Addition `l` is expressed as subtraction of a negated value `m + n = m − (−n)`, multiplication `o` as a series of additions `m × n = m × (n − 1) + m`, exponentiation `n` as a series of multiplications `mⁿ = mⁿ⁻¹ × m`, and finally the function `g` which calls the exponentiation function. On machines where `long long` is 64 bits wide, this code will give incorrect answers for `n ≥ 16`, but note there are machines out there with word lengths of more than 64 bits, *e.g.* the Ethereum Virtual Machine (EVM) with 256-bit words where `long long` could naturally accommodate values ≫ `2⁶⁴`. So *in theory* the code would work for `n ≥ 16`.
> 0 votes

# Answer
## Haskell, A001107 (cracked)

This one is easier, the sequence is growing slower and the charset is smaller.

Compute the decagonal numbers *n(4n-3)* using the following charset of size 9:

```
.,_-=[ ]!

```

Again there is no newline.
> 0 votes

# Answer
## CPython 3.6.2, A000720 (cracked)

I have decided to squeeze as many characters out of Latin-1 as possible without simplifying the challenge. There are some unprintables, so I will provide the characters in the following format:

```
print(",".join((
    "0x0-0x8",
    "0xa-0x1f",  #inc. \n
    "0x23-0x24",  # chars #$
    "0x28-0x29",  # chars ()
    "0x2c",  # char ,
    "0x2e",  # char .
    "0x3b",  # char ;
    "0x3d",  # char =
    "0x3f",  # char ?
    "0x41-0x5d",  # A-Z and chars [\]
    "0x5f",  # char _
    "0x62-0x64", # chars bcd
    "0x69",  # char i
    "0x6c",  # char l
    "0x6e",  # char n
    "0x73-0x75", # chars stu
    "0x7f-0xff"
)))

```

I think that makes 208 characters. Feel free to use any of these.

I did not hard-code; that would take *so* many characters I would have to start meta-meta-programming. This set of characters is provably Turing-complete.
> 0 votes

# Answer
# Python 2, A005150 (Look and say), safe

```
 "()+,.01:=ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_celnortwx

```

Gee, you ~~don't~~ didn't have much, ~~do~~ did you?

Intended solution:

> `exec("FROM ITERTOOLS IMPORT GROUPBY\nA=\"1\"\nFOR _ IN RANGE(1,INT(INPUT())):\n\tA=[\"\".JOIN(GRP)FOR M,GRP IN GROUPBY(A)]\n\tA=\"\".JOIN([STR(LEN(X))+X[0]FOR X IN A])\nPRINT(A)".lower())` You have all of the uppercase characters, and just enough lowercase ones for `\n`, `\t`, `exec` and `lower`.
> 0 votes

# Answer
# Perl 5 `-p`, A005843, score:16, safe.

```
 .0123456789aelv

```

A simple problem. You should solve this easily if you are familiar with the language well.

## Intended solution

> `eval 36.95.42.61.50` How it works: version number such as `5.10.3` is represented as a string. So, you just need to construct a version number to be `eval`uated. Example: `v33` is `'!'`.
> 0 votes

# Answer
# CLC-INTERCAL 1.-94.-2, A001477, safe, score: 16.

Byteset:

```
@ABDEHIP`abdehip

```

You may use any i/o method. Also you may use any compiler option.

Try it online! Submitting as CLC-INTRCAL does not let you set compiler option, so you might need to try as shell.

## The answer

```
D`h@I@`P@pAB@d@p`DPb@PD`h@`P@d@aD`h@E@ABPb@P

```

This is equivalent to `DOWRITEIN.1DOREADOUT.1` in Hollerith character set; so input range is `OH` or `ZERO` to `SIX FIVE FIVE THREE FIVE` (inclusive).

Try the following Bash script online:

```
printf 'D`h@I@`P@pAB@d@p`DPb@PD`h@`P@d@aD`h@E@ABPb@P'>.i;sick -h .i;./.io

```

### How it works

The code can be in Hollerith character set. However, it is implemented incorrectly so the code above is for such behaviour as in implementation, not for documentation.

Here is the script to accept punch lines to generate a program in Hollerith.

Also why doesn't the compiler guess anything other than ASCII? So I had to force it to use my intended character code, by `-h`.

### See also

My answer on Print X without X
> 0 votes

# Answer
# CLC-INTERCAL, A001477, safe, score: 14.

Byteset:

```
ACFGIJLPRWX[\_

```

## Rules

* You may use any compiler option.
* You may specify i/o format by yourself.
* You may specify range of input.
* You may specify whether 0-indexed or 1-indexed.
* I made a program that works on this online environment.

## Answer

```
IXRJFPAFL[\W_IXJACIXGP[\W

```

This is `DOWRITEIN.1DOREADOUT.1` in Baudot encoding, so input range is `OH` or `ZERO` to `SIX FIVE FIVE THREE FIVE`. Due to the encoding, you need compiler option `-b` if it is newer so the character guessing does not work.

## Try the following Bash script in online environment

```
printf %s 'IXRJFPAFL[\W_IXJACIXGP[\W'>.i
sick -b .i
./.io<<<'THREE FOUR FIVE'

```

Copy and paste to try it online!

## See also
> 0 votes

# Answer
# Javascript (ES6), A000079, 6 Bytes

```
[]()+!

```

Hint:

> Intended solution is 25496 characters long.
> -5 votes

---
Tags: sequence, restricted-source, cops-and-robbers
---


title: Lean golf: List Game Lv1 (rev_rev)

text:
# Question
Title: Lean golf: List Game Lv1 (rev_rev)
The title is an homage of the Natural Number Game, which is a nice interactive tutorial into proving certain properties of natural numbers in Lean.

Given that the previous two were slightly too involved (either mathematically or technically) for newcomers to Lean (i.e. the vast majority of CGCC community), I decided to pose some simpler theorems.

---

Let's start with the classic definition of a linked list. You can ignore most of the theoretical fluff; the point is that `list A` is a linked list containing values of type `A`, and defined as either an empty list `[]` (aka `list.nil`) or a pair (cons) of a value and a tail `h :: t` (aka `list.cons`).

Our definitions of `list` and functions on it live in the namespace `mylist` in order to avoid clash with the existing definitions.

```
universe u
variables {A : Type u}
namespace mylist

inductive list (T : Type u) : Type u
| nil : list
| cons : T → list → list

infixr ` :: `:67 := list.cons
notation `[]` := list.nil

```

We then define `append` and `rev` (reverse) on lists. Note that `has_append` instance is necessary in order to use `++` notation, and unfolding lemmas are needed to use the definitional equations of `append` on `++`. Also, `rev` is defined using the simplest possible definition via `++`.

```
def append : list A → list A → list A
| [] t := t
| (h :: s) t := h :: (append s t)
instance : has_append (list A) := ⟨@append A⟩

@[simp] lemma nil_append (s : list A) : [] ++ s = s := rfl
@[simp] lemma cons_append (x : A) (s t : list A) : (x :: s) ++ t = x :: (s ++ t) := rfl

@[simp] def rev : list A → list A
| [] := []
| (h :: t) := rev t ++ (h :: [])

```

Now your task is to prove the following statement:

```
theorem rev_rev (s : list A) : rev (rev s) = s := sorry

```

You can change the name of this statement and golf its definition, as long as its type is correct. Any kind of sidestepping is not allowed. Due to the nature of this challenge, adding imports is also not allowed (i.e. no mathlib).

The entire boilerplate is provided here. Your score is the length of the code between the two dashed lines, measured in bytes. The shortest code wins.

For beginners, proving the following lemmas in order will help you solve the challenge:

> ```
> lemma append_nil (s : list A) : s ++ [] = s := sorry
> lemma append_assoc (s t u : list A) : s ++ t ++ u = s ++ (t ++ u) := sorry
> lemma rev_append (s t : list A) : rev (s ++ t) = rev t ++ rev s := sorry
> ```

# Answer
> 9 votes
# Lean, 101 bytes

```
def r:∀s,rev(@rev A s)=s|[]:=rfl|(x::t):=by
conv{to_rhs,rw<-r t};simp;induction rev t;simp;simp[ih]

```

Try it online!

I'm pretty happy with this.

*Thanks to Huỳnh Trần Khanh for their help.*

# Answer
> 8 votes
# Lean, ~~102~~ 93 bytes

```
def R:∀s,rev(@rev A s)=s:=by let:(∀s(h:A),rev(s++h::[])=h::rev s);intro;induction s;simp*

```

Try it on Lean Web Editor

The 102 byte solution I advertised earlier had suboptimal type annotations:

```
def R:∀s:list A,rev(rev s)=s:=by let:(∀(s:list A)h,rev(s++h::[])=h::rev s);intro;induction s;simp*

```

---
Tags: code-golf, lean
---


title: \$n\$ swaps into a nop

text:
# Question
Title: \$n\$ swaps into a nop
Given \\$n, m\ge 1\\$. There are \\$n\\$ balls. Do \\$m\\$ moves, each choose a ball (maybe also the first one), and exchange with the one currently on the first place. At the end, the order of balls should be the same as the initial state.

You can either output all possibilities, or a random one provided all possibilities have non-zero probability to be outputted. You can use 0-index or 1-index. You can output a specific ball either by its initial position or by its position at the time of that move. Shortest code win.

Tests: (1-index, current position)

```
n=9, m=1 => 1
n=4, m=2 => 1,1; 2,2; 3,3; 4,4
n=2, m=3 => 1,1,1; 1,2,2; 2,1,2; 2,2,1

```

For case 1, with only 1 move we can't do any actual swap but swapping with itself. For case 2, we can swap the first ball to anywhere but the next step we have to make it back.

# Answer
# Jelly,  ~~20~~  19 bytes

There is probably\* a terser way to swap the items...

```
’RŒBF!‘œ?@ƒ⁹Ƒ
ṗçƇR{

```

A dyadic Link that accepts the number of balls, \\$n\\$, on the left and the number of moves, \\$m\\$, on the right and yields a list of lists of valid move sequences using 0-indexing.

**Try it online!**

### How?

Filters all length \\$m\\$ potential instructions consisting of the alphabet \\$\[1,n\]\\$ keeping those which cause no change when applied.

In order to perform a single instructed swap the code translates this to an equivalent sequence of swaps of adjacent elements. The swaps are then applied in turn starting with an ordered list where the rightmost element is the first index and the leftmost is the last.

To swap the \\$k^{\text{th}}\\$ element with the \\$1^{\text{st}}\\$ we actually perform multiple swaps of neighbouting pairs, first to move the \\$1^{\text{st}}\\$ element to position \\$k\\$ and then to move the original \\$k^{\text{th}}\\$ element to to position \\$1\\$

For example starting with elements `GFEDCBA` (A being the "first") to swap the sixth element (`F`) with the first (`A`) we swap like so:

```
(indices):  7654321
    start:  GFEDCBA  moving A from index 1...
swap(2,1):  GFEDCAB  .
swap(3,2):  GFEDACB  .
swap(4,3):  GFEADCB  .
swap(5,4):  GFAEDCB  .
swap(6,5):  GAFEDCB  done, now moving F to index 1...
swap(5,4):  GAEFDCB  .
swap(4,3):  GAEDFCB  .
swap(3,2):  GAEDCFB  .
swap(2,1):  GAEDCBF  done.

```

This is then performed by noting that `swap(n,n-1)` can be performed by calculating the \\$((n-1)!+1)^{\text{th}}\\$ lexicographical permutation of the current state (which I wrote a built-in for a few years ago, `œ?`).

```
’RŒBF!‘œ?@ƒ⁹Ƒ - Link, is transform an invariant?: instruction string, [1..n]
’             - decrement (each instruction) e.g. [4,1,3] -> [3,0,2]
 R            - range                        -> [[1,2,3],[],[1,2]]
  ŒB          - bounce                       -> [[1,2,3,2,1],[],[1,2,1]]
    F         - flatten                      -> [1,2,3,2,1,1,2,1]
     !        - factorial                    -> [1,2,6,2,1,1,2,1]
      ‘       - increment                    -> [2,3,6,3,2,2,3,2]
                -> this is an equivalent set of instructions swapping neighbouring pairs in
                   turn, as lexicographical permutation indices.
           ⁹  - right argument = [1..n]
            Ƒ - is invariant under?:
          ƒ   -   apply the new instructions to [1..n] in turn using:
       œ?@    -     nth index-lexicographical permutation

ṗçƇR{ - Main Link: n, m
ṗ     - (n) Cartesian power (m) -> all length m strings of alphabet [1..m]
   R{ - range (n) -> [1..n]
  Ƈ   - filter (the strings) keeping those for which:
 ç    -   call last Link (1) as a dyad, f(potential_string, [1..n])

```

---

* Although this is 20:

```
J=o⁸ɗḊ⁹;ị⁸
ṗçƒ⁹Ƒ¥ƇR{

```

10 bytes to swap to list elements by index; perhaps Jelly should have a `œ.` built-in to swap elements of a list by indices?
> 3 votes

# Answer
# JavaScript (V8),  ~~123 120 113~~  112 bytes

Expects `(n)(m)`. Prints all 0-indexed solutions.

```
n=>g=(m,A=[...Array(n)],o)=>A.some((v,j)=>m?g(m-1,A,[o]+j+' ',[A[j],A[0],A]=[A[0]^j,v^j,[...A]]):v)|m?0:print(o)

```

Try it online!

### How?

Instead of storing \\$\[0,1,\dots,n-1\]\\$ into the reference array, we store the actual value at a given position XOR'ed with the expected value.

This makes the initialization and the final test easier and shorter to write because we start with an array filled with \\$0\\$'s and expect to end up with the same configuration. (In the JS code, we actually start with an array filled with undefined values and test that there's no truthy value in the final one.)

To exchange \\$A\_0\\$ and \\$A\_j\\$, we do:

$$\cases{A\_j\leftarrow A\_0\operatorname{xor}j\\ A\_0\leftarrow A\_j\operatorname{xor}j }$$

The implementation is a bit freaky. Within a recursive call to \\$g\\$, we pass the current instance of \\$A\[\\:\]\\$ and then simultaneously update \\$A\[0\]\\$, update \\$A\[j\]\\$ and set \\$A\[\\:\]\\$ to a new instance consisting of a copy of itself before the changes are applied, so that the array is restored to its initial state after the call:

```
g(…, A, …, [A[j], A[0], A] = [A[0] ^ j, v ^ j, [...A]])

```
> 2 votes

# Answer
# Haskell, 111 bytes

```
(0?y)q=[[]|q==y]
(n?y@(h:t))q=[k:x|k<-q,x<-(n-1)?(y!!(k-1):tail(take(k-1)y++h:drop k y))$q]
x#y=x?[1..y]$[1..y]

```

Try it online!

Just attempts every possible path and returns the ones that work.
> 2 votes

# Answer
# 05AB1E, 31 bytes

Uses 0-indexing. A lot more complicated than it has to be.

```
L©<Iãʒ®yv¹<!y*¹ÍLRyDĀ-£!O+.I}āQ

```

Try it online!

This generates all move sequences and selects the right ones by doing the swapping. Instead of directly swapping values (which would probably be shorter), this calculates the index of the permutation that does the right swap.

For a list of length \\$t\\$ the permutation that swaps the first with the \\$n\\$-th value has index

$$ (n-1) \cdot (t-1)! \\, + \sum\_{i=t-n+1}^{t-2} i! $$

(Uses 1-indexing, Related OEIS sequence: A211369)

This is calculated by `¹<!y*¹ÍLRyDĀ-£!O+`, where `¹` is \\$t\\$ and `y` is \\$n-1\\$. The sum part is quite annoying to compute, because all the range builtins don't want to return empty lists.

```
                     # Full program, taking two inputs
                     # ¹ the length of the move sequence
                     # ² the number of balls
L©                   # range from 1 to ¹, store in register
  <                  # decrement to get range from 0 to ¹-1
   Iã                # all ²-tuples of numbers in the range
     ʒ               # filter on:
      ®              #   start with the range 1 .. ¹
       yv       }    #   iterate over the current move sequence:
          ...        #     calculate permutation index
              .I     #     apply corresponding permutation
                 āQ  #   is the result equal to [1 .. length]?

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
Nest[#/.r&,r={1->#,#->1}&~Array~#,#2]~Position~r&

```

Try it online!

Input `[n, m]`.

Thanks to alephalpha's now-deleted answer for the idea to swap values instead of positions.

Swapping the positions \\$1\\$ and \\$x\\$ of the \\$\text{position}\to\text{ball}\\$ list is equivalent to swapping the values \\$1\\$ and \\$x\\$ of the \\$\text{ball}\to\text{position}\\$ list.

The list that's being mutated isn't actually `1..n`, but it contains all numbers in the range all the same.
> 2 votes

# Answer
# Python 3, 124 bytes

```
def f(n,m,*l):
 *p,=*q,=range(n)
 for x in l:q[0],q[x]=q[x],q[0]
 return m and sum([f(n,m-1,*l,i)for i in p],[])or[l][:q==p]

```

Try it online!

Brute force search. Outputs all options.

-3 bytes thanks to Jakque
> 2 votes

# Answer
# Ruby, 86 bytes

```
->n,m{w=*0...n;w.product(*[w]*~-m).select{|x|s=*w;x.map{|c|s[0],s[c]=s[c],s[0]};s==w}}

```

Try it online!
> 1 votes

# Answer
# , 118 bytes

```
function(n,m,l=expand.grid(rep(list(v<-1:n),m)))l[apply(l,1,function(s){for(i in s)v[c(1,i)]=v[c(i,1)];all(v==1:n)}),]

```

Try it online!
> 1 votes

# Answer
# Charcoal, 60 bytes

```
≔…⁰ＮθＮη⊞υ⟦⟦⟧θ⟧Ｆυ¿⁼Ｌ§ι⁰ηＦ⁼⊟ιθＩιＦθ⊞υ⟦⁺§ι⁰⟦κ⟧Ｅ§ι¹⎇∧μ⁻κμλ§§ι¹⁻κμ

```

Try it online! Link is to verbose version of code. Outputs all 0-indexed possibilities by current position. Explanation:

```
≔…⁰Ｎθ

```

Create the initial range of `n` elements.

```
Ｎη

```

Input `m`.

```
⊞υ⟦⟦⟧θ⟧

```

Start a breadth-first search with a possibility of `0` moves and the initial position.

```
Ｆυ

```

Loop over the possibilities.

```
¿⁼Ｌ§ι⁰η

```

If this possibility has `m` moves, then...

```
Ｆ⁼⊟ιθＩι

```

... print the possibility if the initial state was reached.

```
Ｆθ

```

Otherwise, looping over each position, ...

```
⊞υ⟦⁺§ι⁰⟦κ⟧Ｅ§ι¹⎇∧μ⁻κμλ§§ι¹⁻κμ

```

... push the possibility obtained from the switch to the search list.
> 0 votes

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


title: Who committed most?

text:
# Question
Title: Who committed most?
## Background

Sometimes, people think you didn't work at your git project. But - you can prove yourself with `git shortlog -n`. Now, the problem is you are a programmer and programmers are lazy. So you want to write a program which shows the person who committed at most.

## Rules

You may not do the following things:

* use `git shortlog` with the argument `-s`
* use any alias, which calls git on any way

You may assume the following:

* git is installed on the system
* You are in the working directory of the repository where to find out the person
* The output of `git shortlog -n` will be piped in your program, but you may also call the command in your program, even though I can't see the advantage.
* If there is a language-specific package or library for git, you may use it.

## The output

Your program has to output the name of the person with the most commits in the repo.

This is a challenge, so the program with the least amount of bytes wins!

# Answer
# Bash, 20 bytes

```
head -1|cut -d\( -f1

```

Try it online!
> 3 votes

# Answer
# Bash, 18 bytes

```
sed -n 1s/.\(.*//p

```

Try it online!

# sed, 11 bytes

Run with `-n` (counted as +1 byte).

```
1s/ (.*//p

```

Try it online!
> 3 votes

# Answer
# Befunge-98, 10 bytes

```
~:'(-!#@_,

```

Try it online!
> 3 votes

# Answer
# Retina, 8 bytes

```
s` \(.*

```

Try it online! Example input is the output from `shortlog -n` from Retina.
> 2 votes

# Answer
# Python 3, 29 bytes

```
print(input().split(' (')[0])

```

Try it online! Example input is the output from `shortlog -n` from Retina.
> 2 votes

# Answer
# AWK, 9 bytes

```
NR<2,NF--

```

Try it online!

This one is just a test, consisting of two statements, without any associated code block. The first test `NR<2` determines the truthy'ness of the test. So the default code block, which is effectively `print $0`, is only run for the first line of the input.

The secondary statement, `NF--` just drop the last field in the input line.
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
'(¡¬

```

Try it online!
> 1 votes

# Answer
# Jelly, 4 bytes

```
ṣ”(Ḣ

```

Try it online!

My first Jelly answer!

**How?**

```
ṣ”(Ḣ - Main Link. Takes a string X on left
ṣ    - Split X on the occurrences of
 ”(  - Literal "("
   Ḣ - Head

```
> 0 votes

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


title: ASCII Rubik's Cube

text:
# Question
Title: ASCII Rubik's Cube
Inspired by this and the following chat:

Your task is to output the following:

```
   _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/

```

Extra leading or trailing whitespace is allowed, as long as it does not change the appearance of the cube. As usual, returning the above or a list of strings from a function is allowed.

This is , so shortest answer in bytes wins!

# Answer
# SOGL V0.12, 27 bytes

```
Y=Q∫+ZΔ○H!╝Ηūf⅟Ξ∆׀Æģ≠a⁶‘6«n

```

Try it Here!

Sadly, the palendromization version `qE½Dε▒2β[}█O%q‘6«n╬∑` doesn't really work
> 9 votes

# Answer
# Charcoal, ~~28~~ 23 bytes

```
Ｆ³⁺⁺×\_³×\/⁻³ι¶ ‖Ｍ↑×_ ³

```

Try it online! Link is to verbose version of code. Not very Charcoal-y I know. I didn't realise that `‖Ｍ↓` deliberately moves the cursor so I had originally tried `Ｆ³«Ｐ⁺×/_³×/\⁻³ι↗»‖Ｍ↓×_ ³` which didn't work, because I was trying to do it upside-down. If you want something more Charcoal-y then try `Ｇ↗³←⁶↘³/\¶\/Ｇ↖³←⁷↘³_\¶\_↘‖Ｍ↑×_ ³` for 32 bytes: Try it online!
> 11 votes

# Answer
# Bubblegum, 35 bytes

```
00000000: 5350 5088 0741 2e05 05fd 7830 8ce1 82b3  SPP..A....x0....
00000010: 806c 0413 c889 8907 4330 8f4b 01c1 036a  .l......C0.K...j
00000020: 8671 00                                  .q.

```

Try it online!
> 6 votes

# Answer
# \>\<\>, ~~97 94 93~~ 89 bytes

```
">knknknk//>k>knknknk/>k>k>knknknkk>k>k>n>n>n>k>k>n>n>n>/k>n>n>n>//n/n/n///"01.
of-

```

Try it online!

Edit 3: Figured out that you can use the character "" (ascii 25) - Now the process just takes 15 off every stack item and prints. Also removed extra directional instructions and replaced all with 1 move (01.)
> 5 votes

# Answer
# Python 2, 81 bytes

```
i=7
while i:k=min(i,7-i);i-=1;print' '*(3-k)+'\/___ '[i/3::3]*3+k*'\//\\'[i>2::2]

```

Try it online!
> 5 votes

# Answer
# Python 3, ~~98~~ 94 bytes

*@KevinCruijssen suggested this...*

*-4 bytes thanks to @HyperNeutrino and @WheatWizard*

Output Hardcoding solution:

```
print(r"""   _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/""")

```

Try it online!

**or, 98 bytes:**

```
print("   _ _ _\n  /_/_/_/\\\n /_/_/_/\/\\\n/_/_/_/\/\/\\\n\_\_\_\/\/\/\n \_\_\_\/\/\n  \_\_\_\/")

```

Try it online!

---

# Python 3, 139 bytes

Dumb Python 3 Non-Hardcoding sumbmission, sure it can be golfed. Surprisingly, compressing the two `for`s in just one loop is longer:

```
p=print;p(' '*3+"_ "*3)
for i in range(3):p(abs(2-i)*' '+'/_'*3+'/'+i*"\/"+'\\')
for i in range(3):p(i*' '+'\\_'*3+'\\'+"/\\"*abs(2-i)+'/')

```

Try it online!

# Python 3, 140 bytes

```
print(' '*3+"_ "*3,'\n'+'\n'.join(abs(2-i)*' '+'/_'*3+'/'+i*"\/"+'\\'if i<3else (i-3)*' '+'\\_'*3+'\\'+"/\\"*abs(i-5)+'/'for i in range(6)))

```

Try it online!
> 4 votes

# Answer
# Tail, 99 bytes

```
#!/bin/tail -n+2
    _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/

```
> 4 votes

# Answer
# Java 8, 112 bytes

```
o->"   _ _ _\n  /_/_/_/\\\n /_/_/_/\\/\\\n/_/_/_/\\/\\/\\\n\\_\\_\\_\\/\\/\\/\n \\_\\_\\_\\/\\/\n  \\_\\_\\_\\/"

```

Hard-coded output.

Try it here.
> 3 votes

# Answer
# Bubblegum, 42 bytes

```
0000: e0 00 4f 00   22 5d 00 10   68 13 e2 04   15 00 b7 11 │ à.O."]..h.â...·.
0010: 7a 0e c5 f5   30 27 b5 b3   3d 39 8f a6   1f f9 74 52 │ z.Åõ0'µ³=9.¦.ùtR
0020: c5 66 98 bd   bd 0a 9a 8d   44 00                     │ Åf.½½¶..D.

```
> 3 votes

# Answer
# PHP, 77 bytes

```
<?=strtr('   _ _ _
  0\
 01\
011\
2111
 211
  21',["/_/_/_/","\/","\_\_\_"]);

```

Try it online!
> 3 votes

# Answer
# Retina, 59 bytes

```

   _¶  /_/\¶ /_/V\¶/_/VV\¶\_VVV¶ \_VV¶  \_V
._
$&$&$&
V
\/

```

Try it online! Explanation: The first stage simply creates the following:

```
   _
  /_/\
 /_/V\
/_/VV\
\_VVV
 \_VV
  \_V

```

The second stage then expands all the `_`s by repeating them and the previous character 3 times, while the third stage turns the `V`s into `\/`s.
> 3 votes

# Answer
# C#, 86 bytes

```
o=>@"   _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/"

```

Try it here.
> 2 votes

# Answer
# 05AB1E, ~~34~~ 31 bytes

```
„_ 3×Âð'/:3F„/\«∞2ä`RˆD}\)¯R«.c

```

Try it online!

**Explanation**

```
„_ 3×             # push the string "_ _ _ "
     Â            # push a reversed copy
      ð'/:        # replace spaces with slashes
3F                # 3 times do
  „/\«            # append "/\"
      ∞           # mirror
       2ä`        # split into 2 separate parts on stack
         Rˆ       # reverse the second part and push to global list
           D      # duplicate the remaining part
            }     # end loop
\)                # discard the last copy and wrap stack in a string
  ¯R              # push the global list and reverse it
    «             # append to the rest of the list
     .c           # pad lines to equal length

```

**Alternate 31 byte solution**

```
„ _3×3FDð'/:„/\«∞2ä`R.Á})ÀÀÀ.c¦

```
> 2 votes

# Answer
# CSS, ~~225~~ 223 bytes

*-2 bytes thanks to Stephen S, extra spaces removed*

I'm not exactly sure if this counts because CSS isn't *really* a programming language, but technically CSS can be standalone since the `<html>` element is autogenerated if there isn't one.

```
html:after{content:'   _ _ _ \A   /_/_/_/\005c\A  /_/_/_/\005c/\005c \A /_/_/_/\005c/\005c/\005c \A \005c_\005c_\005c_\005c/\005c/\005c/ \A  \005c_\005c_\005c_\005c/\005c\/\A   \005c_\005c_\005c_\005c /';white-space: pre;}
```

# And here's a version with a monospaced font, **~~247~~ 246 bytes**.

*-1 byte thanks to Stephen S, extra spaces removed*

```
html:after{font-family:'Courier';content:'   _ _ _ \A   /_/_/_/\005c\A  /_/_/_/\005c/\005c \A /_/_/_/\005c/\005c/\005c \A \005c_\005c_\005c_\005c/\005c/\005c/ \A  \005c_\005c_\005c_\005c/\005c\/\A   \005c_\005c_\005c_\005c /';white-space: pre;}
```
> 2 votes

# Answer
# 05AB1E, ~~35~~ ~~32~~ 31 bytes

```
"/ _\"•₁7æ¤ÝI}?ÕR&Ü•4вè4ôJ€∞ø¨»

```

Try it online!

100% different method than Emigna.

---

**Edit:** If I start with the pattern already transposed I can cut out 3 bytes.

---

```
"/ _\"            # Push ASCII-art characters used.
•₁7æ¤ÝI}?ÕR&Ü•4в  # Push transposed version of base-4 pattern.
è                 # Replace all digits in base-4 number with appropriate symbol.
 4ô               # Split into groups of 4.
   J              # Join together.
    €∞            # Mirror each row (technically column).
      ø           # Transpose back.
       ¨»         # Remove the extra "_ _ _", and print with newlines.

```
> 2 votes

# Answer
# JavaScript (ES6), 95 bytes

```
_=>String.raw`   _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/`

```

# JavaScript (ES6), ~~103~~ 94 bytes

*-9 bytes thanks to @Shaggy*

```
_=>`   _ _ _
  ${a=`/_/_/_/\\`}
 ${a}/\\
${a}/\\/\\
${b=`\\_\\_\\_\\/`}\\/\\/
 ${b}\\/
  ${b}`

```

# JavaScript (ES6), 106 bytes

```
_=>`   _ _ _
  /_/_/_/\\
 /_/_/_/\\/\\
/_/_/_/\\/\\/\\
\\_\\_\\_\\/\\/\\/
 \\_\\_\\_\\/\\/
  \\_\\_\\_\\/`

```
> 1 votes

# Answer
# Ruby, ~~72~~ 70 bytes

```
7.times{|i|puts' '*(j=i^i/4+3)+'_ \_/_'[-i/3*2,2]*3+'/\/'[i/4,2]*j^=3}

```

Latest edit: avoid double `\` by enclosing strings in `''` instead of `""`.

**Ungolfed** (note in Ruby negative string indexes wrap around. `-1` is the last character.)

```
7.times{|i|                       #7 lines.
  puts" "*(j=i^i/4+3)+            #Print j= 3,2,1,0, 0,1,2 spaces.
      "_ \\_/_"[-i/3*2,2]*3+      #Print 3 repeats of 2 characters from the string, index 0,-2,-2,-2,-4,-4,-4.
      "/\\/"[i/4,2]*j^=3          #Print 2 characters from the string, /\ or \/, repeated 3^j times.
}

```
> 1 votes

# Answer
# Windows Batch, 122 bytes

```
@echo    _ _ _
@echo   /_/_/_/\
@echo  /_/_/_/\/\
@echo /_/_/_/\/\/\
@echo \_\_\_\/\/\/
@echo  \_\_\_\/\/
@echo   \_\_\_\/

```

Pretty self-explantory.
> 1 votes

# Answer
## Brainf\*ck 387 bytes

Not even sure if this is still a thing but I was bored and did it for sh\*ts and giggles :)

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

```

Edit: TIL: I am 54.28% more effective than some generator I found online ^.^

Edit2: Try it online Make sure Wrap is on for Memory overflow behaviour in the options
> 1 votes

# Answer
# COBOL, 238 bytes

Compiled with open-cobol. Note that the indentation is a single tab, not spaces, even if this website formats it that way.

```
    IDENTIFICATION DIVISION.
    PROGRAM-ID. a.
    PROCEDURE DIVISION.
    DISPLAY "   _ _ _".
    DISPLAY "  /_/_/_/\".
    DISPLAY " /_/_/_/\/\".
    DISPLAY "/_/_/_/\/\/\".
    DISPLAY "\_\_\_\/\/\/".
    DISPLAY " \_\_\_\/\/".
    DISPLAY "  \_\_\_\/".
    STOP RUN.

```
> 1 votes

# Answer
# Perl 5, 89 bytes

```
say"   _ _ _";$r[7-$_]=($r[$_]=$"x(3-$_).'/_'x3 .'/\\'x$_.$/)=~y|/\\|\\/|r for 1..3;say@r

```

Try it online!
> 1 votes

# Answer
# Deadfish~, 687 bytes

```
{iii}iiccc{iiiiii}iiic{dddddd}dddc{iiiiii}iiic{dddddd}dddc{iiiiii}iiic{{d}ii}dddddc{ii}iicc{i}iiiiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{{d}ii}ddc{ii}iic{i}iiiiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{{d}ii}ddc{iiii}dddc{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{{d}ii}ddc{{i}dd}iiciiicdddciiicdddciiicdddc{dddd}dddddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{dddd}dddddc{dddd}iiic{ii}iic{iiiiii}ciiicdddciiicdddciiicdddc{dddd}dddddc{iiii}iiiiic{dddd}dddddc{dddd}iiic{ii}iicc{iiiiii}ciiicdddciiicdddciiicdddc{dddd}dddddc

```

Try it online!
> 1 votes

# Answer
# Vyxal `j`, ~~33~~ 32 bytes

<sup>-1 bytes thanks to Aaron Miller</sup>

```
»\!¡øoΠ¥⅛831‟½ø↲p∇±₀WṀ»‛_ k/+τ7/

```

## Explanation

```
»\!¡øoΠ¥⅛831‟½ø↲p∇±₀WṀ»             - Push a base-4 number containing the cube
                       ‛_ k/+τ      - Change to custom base, replacing the numbers
                                      with the symbols.
                              7/    - Divide into seven lines.
<j flag>                            - Join by newlines
<implicit output>                   - Print it!

```

Try it Online!
> 1 votes

# Answer
# Self-modifying Brainfuck, 86 bytes

Replace the ␀ with an actual null byte (0x00).

```
<[.<]␀/\_\_\_\
/\/\_\_\_\
/\/\/\_\_\_\
\/\/\/_/_/_/
\/\/_/_/_/
\/_/_/_/
_ _ _

```

Try it online!

## Explanation

Another literal output answer.

```
<[.<]             - Print the source code in reverse until a NULL byte is found.
     ␀            - Null, replace with 0x00. Ends program.
      <the rest>  - The cube in reverse.

```
> 1 votes

# Answer
# Zsh, 86 bytes

Port of the PHP solution. Try it online!

```
sed 's|0|/_/_/_/|;s|1|\\/|g;s|2|\\_\\_\\_|'<<<'   _ _ _
  0\
 01\
011\
2111
 211
  21'

```

But the naïve approach only costs 1 extra, for 87 bytes ...

```
 <<<'    _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/'

```
> 1 votes

# Answer
# Python 2, 93 bytes

```
print r"""   _ _ _
  /_/_/_/\
 /_/_/_/\/\
/_/_/_/\/\/\
\_\_\_\/\/\/
 \_\_\_\/\/
  \_\_\_\/"""

```

Try it online!
> 0 votes

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


title: Rock Paper Scissors (Sorta) Quine

text:
# Question
Title: Rock Paper Scissors (Sorta) Quine
Create three programs, which we'll call Rock, Paper, and Scissors.

Each program must be unique, and accept input.

If a program gets any input which is not one of the programs Rock, Paper or Scissors, it must print itself.

RPS style, the programs will each print one of the following four outputs:

1. "win" if the running program beats the program that is being input
2. "lose" if the running program loses against the program that is being input
3. "tie" if the input is equal to the source code of the running program
4. The source code of the running program itself for any other input (including an empty input)

General rules:

* The three programs can be in any language. Rock can be in a different language from Paper: same for any other pair.
* They are not restricted by size.
* They must print through STDOUT or closest equivalent, and must print strings or closest equivalent. They must not print to STDERR.
* They need not be full programs. They can be functions, if you wish to get rid of the stuff needed in a program, like C's #includes.

This is a challenge, where your score is determined by the sum of the programs' sizes. The person with the lowest score wins.
If two people have the same score, the person whose largest program by bytes out of the set Rock, Paper, Scissors is smaller wins.

# Answer
# Jelly, ~~67~~ 59 bytes × 3 = score of 177

```
“3ṛṾ;Ṫ,ɠ;µḣ2O_/2ị%3+1×ḣ2a2¦Ɱ3Ṿ€¤ċɗ/$ịṚ“win“lose“tie“1ịv”1ịv

```

Try it online!

A full program that reads a line from STDIN and returns `tie` if given the same program, `win` if given a program against which it can win and `lose` if a program against which it loses. If provided with anything except one of the rock, paper or scissors programs it prints itself.

The digit in second position in the program indicates which it is:

1. Rock
2. Scissors
3. Paper
> 2 votes

# Answer
# Python 3, ~~273, 489,~~ 429 bytes

Rock:

```
r=['tie', 'lose', 'win'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

```

Try it online against itself!
Try it online against Paper!
Try it online against Scissors!
Try it online against rubbish!

Paper:

```
r=['win', 'tie', 'lose'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

```

Try it online against itself!
Try it online against Scissors!
Try it online against Rock!
Try it online against garbage!

Scissors:

```
r=['lose', 'win', 'tie'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

```

Try it online against itself!
Try it online against Rock!
Try it online against Paper!
Try it online against trash!

The same as the previous version, but check that the input exactly matches the source code of one of the programs.

Try it online (together)!

# Old (invalid) version

Rock:

```
s="print(['tie','lose','win','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

```

Paper:

```
s="print(['win','tie','lose','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

```

Scissors:

```
s="print(['lose','win','tie','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

```

Try it online!

Three almost identical programs (all with 91 bytes), the only difference is the order of the win/tie/lose, which each program uses the position of the `'tie'` to determine the result from it's own ordering.

As pointed out, these programs are invalid, as they will only print out themselves if the input doesn't contain 'ti' (or the 'ti' is in a certain place).
> 3 votes

# Answer
# Java 10, 1716 (three time 572) bytes

Rock program:

```
interface R{static void main(String[]a){var s="interface R{static void main(String[]a){var s=%c%s%1$c;System.out.print((s=s.format(s,34,s)).equals(a[0])?%1$ctie%1$c:t(s).equals(a[0])?%1$close%1$c:t(t(s)).equals(a[0])?%1$cwin%1$c:s);}static String t(String s){var r=%1$c%1$c;for(int b:s.getBytes())r+=(char)(b==82?80:b==80?90:b==90?82:b);return r;}}";System.out.print((s=s.format(s,34,s)).equals(a[0])?"tie":t(s).equals(a[0])?"lose":t(t(s)).equals(a[0])?"win":s);}static String t(String s){var r="";for(int b:s.getBytes())r+=(char)(b==82?80:b==80?90:b==90?82:b);return r;}}

```

The Paper program is similar, except with both `R` replaced with `P`.
The Scissor program is similar, except with both `R` replaced with `Z` (since `S` is already used in `String`).

*Rock program:*
\- Try it online with itself as input.
\- Try it online with the Paper program as input.
\- Try it online with the Scissor program as input.
\- Try it online with rubbish input.

*Paper program:*
\- Try it online with itself as input.
\- Try it online with the Scissor program as input.
\- Try it online with the Rock program as input.
\- Try it online with rubbish input.

*Scizzor program:*
\- Try it online with itself as input.
\- Try it online with the Rock program as input.
\- Try it online with the Paper program as input.
\- Try it online with rubbish input.

## Explanation:

**General explanation:**

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

**Challenge part:**

I've added a separated method `t` which will transliterate the characters `RPZ` once clockwise in all three programs:

```
static String t(String s){ // Method with String as both parameter and return-type:
  var r="";                //  Result-String, starting empty
  for(int b:s.getBytes())  //  Loop over the characters of the input-String:
    r+=                    //   Append to the result-String:
       (char)(             //    A character with codepoint:
              b==82?       //     If the character is 'R':
               80          //      Change it to 'P' (codepoint 80)
              :b==80?      //     Else-if the character is 'P':
               90          //      Change it to 'Z' (codepoint 90)
              :b==90?      //     Else-if the character is 'Z':
               82          //      Change it to 'R' (codepoint 82)
              :            //     Else:
               b);         //      Leave the character unchanged
  return r;}               //  Return the resulting String

```

When we're printing, it will do the following checks:

```
s.equals(a[0])?            // If the program equals the input:
 "tie"                     //  Print "tie"
:t(s).equals(a[0])?        // Else-if the program transliterated once equals the input:
 "lose"                    //  Print "lose"
:t(t(s)).equals(a[0])?     // Else-if the program transliterated twice equals the input:
 "win"                     //  Print "win"
:                          // Else:
 s                         //  Print the source code-String itself

```
> 2 votes

# Answer
# 05AB1E, ~~219~~ ~~207~~ 201 (three times ~~73~~ ~~69~~ 67) bytes

Rock program:

```
2"D34çý…·‡§ÍŽ°#sª¤¸YF¤₁DÀ‡ª}IQZ_ªÏ"D34çý…·‡§ÍŽ°#sª¤¸YF¤₁DÀ‡ª}IQZ_ªÏ

```

Paper program is similar, but with leading `5` instead of `2`.
Scissor program is similar, but with leading `6` instead of `2`.

Similar transliterate approach as my Java answer.

*Rock program:*
\- Try it online with itself as input.
\- Try it online with the Paper program as input.
\- Try it online with the Scissor program as input.
\- Try it online with rubbish input.

*Paper program:*
\- Try it online with itself as input.
\- Try it online with the Scissor program as input.
\- Try it online with the Rock program as input.
\- Try it online with rubbish input.

*Scizzor program:*
\- Try it online with itself as input.
\- Try it online with the Rock program as input.
\- Try it online with the Paper program as input.
\- Try it online with rubbish input.

## Explanation:

**General explanation:**

Uses the default 14 bytes quine program of *@OliverNi*, since it's easy to modify (even though there is a shorter 05AB1E quine).

This quine will:

```
2               # Push a 2 (or 5 or 6 depending on the program used)
 "D34çý"        # Push the trailing part of the source-code as string
         D      # Duplicate this string on the stack
          34ç   # Push a 34 as ASCII character (a double quote '"')
             ý  # Join the three values on the stack by this
                # (and output the result implicitly)

```

Try it online.

**Challenge part:**

I've combined this with the following if-else construction:

```
…·‡§ÍŽ°         # Push dictionary string "tie lose win"
       #        # Split it on spaces: ["tie","lose","win"]
        sª      # Swap, and append the quine-string we created
¤               # Get the last item (the quine we added) of the list (without popping)
 ¸              # Wrap it into a list
  YF            # Loop 2 times (the default value of variable `Y` is 2):
    ¤           #  Get the last item of the list (without popping)
     ₁D         #  Push builtin 256 twice
       À        #  Rotate the digits once towards the left: 562
        ‡       #  Transliterate the 256 to 562 in the string
         ª      #  And append it to the list
  }IQ           # After the loop: check for each value if it's equal to the input
     Z          # Get the maximum (without popping) to check if any are truthy
      _         # Inverse this boolean (0 becomes 1; 1 becomes 0)
       ª        # Append it to the list of truthy/falsey values
        Ï       # Leave the strings of the earlier created list at the truthy positions

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `…·‡§ÍŽ°` is `"tie lose win"`.
> 1 votes

# Answer
# Python 3.8 (pre-release), 127 * 3 = 381 bytes

## Rock :

```
x=0;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")

```

Try it online!

## Paper :

```
x=1;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")

```

Try it online!

## Scissors :

```
x=2;exec(s:="a=';exec(s:=%r)'%s;i=input();print(a==i[3:]and'x=/'<i[:3]<'x=3'and['tie','win','lose'][x-int(i[2])]or'x=%d'%x+a)")

```

Try it online!

## How it works :

The structre of this quine is a variation of `exec(s:="print('exec(s:=%r)'%s)")`

* `x=0`, `x=1`, `x=2` defines the type of the program (rock, paper or scissors)
* `a=';exec(s:=%r)'%s` stores the quine in `a`
* `i=input()` stores the input in `i`
* `a==i[3:]and'x=/'<i[:3]<'x=3'` verify that the input is any of `rock`, `paper` or `scissors`.
* `and['tie','win','lose'][x-int(i[2])]` If the above is true, prints the corresponding result using as index the difference of the type of each code
* `or'x=%d'%x+a` otherwise, prints the quine
> 1 votes

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


title: Revert Flow Free puzzle

text:
# Question
Title: Revert Flow Free puzzle
*Inspired by Is this Flow Free puzzle trivial? by @Bubbler. Lengthy chunks of this challenge are borrowed from there. This may be one step of a solution for the linked challenge, depending on chosen strategy.*

## Background

*Flow Free* is a series of puzzle games whose objective is to connect all the same-colored pairs of dots on the grid. In this challenge, we consider the original game on a rectangular grid (no variations like bridges, warps, or hexagonal grids).

A puzzle in *Flow Free* might look like this:

```
Puzzle   Solution
....1    11111
.....    13333
..24.    13243
1....    13243
23...    23243
...43    22243

```

## Challenge

Given a solved Flow Free puzzle, output the unsolved puzzle.

The input can be taken as a single string/array or a list of lines. You may also take the dimensions of the array as input.

You may assume only the digits 1-9 are used and the numbers used in the solved puzzle will be a strict prefix of these (i.e. no need to handle there being `2`s but no `1`s in the input). Also, each line represented by each digit is a valid polystrip of length 3 or higher.

Unsolving means identifying the ends of the polystrips and keeping them in place, while replacing other cells with a `0` or any consistent non-digit character.

Output the string/array in any convenient manner.

This is , the shortest code per language wins!

## Test cases

| Inputs | Outputs |
| --- | --- |
| ``` 11111<br>12221<br><br>11113<br>33333<br>32222<br><br>11111<br>13333<br>13243<br>13243<br>23243<br>22243<br><br>11121<br>13121<br>13121<br>13111<br><br>11122<br>13121<br>13121<br>33111<br><br>13333<br>13443<br>13343<br>11243<br>21243<br>22244<br><br>1116777<br>1226666<br>1125555<br>5555344<br>8888334<br>9998444 ``` | ``` .....<br>12.21<br><br>1..13<br>.....<br>32..2<br><br>....1<br>.....<br>..24.<br>1....<br>23...<br>...43<br><br>...21<br>.3...<br>...2.<br>13...<br><br>....2<br>.3..1<br>1..2.<br>3....<br><br>1....<br>..4..<br>..3..<br>..2..<br>21..3<br>....4<br><br>..167.7<br>.2....6<br>.12...5<br>5...34.<br>8....3.<br>9.984.. ``` |

# Answer
> 5 votes
# JavaScript (ES6),  ~~87 84 83~~  82 bytes

*Saved 1 byte thanks to @tsh*

Expects a matrix of integers. Returns another matrix where empty cells are set to `0`.

```
m=>m.map((r,y)=>r.map((v,x)=>v*-(g=d=>d+2?((m[y+d--%2]||0)[x+d%2]==v)+g(d):d)(2)))

```

Try it online!

Or **79 bytes** with optional chaining:

```
m=>m.map((r,y)=>r.map((v,x)=>v*-(g=d=>d+2?(m[y+d--%2]?.[x+d%2]==v)+g(d):d)(2)))

```

(not supported by TIO)

### Commented

```
m =>                       // m[] = input matrix
m.map((r, y) =>            // for each row r[] at position y in m[]:
  r.map((v, x) =>          //   for each value v at position x in r[]:
    v * -(                 //     set v to 0 if the result of g() is 0
                           //     or leave it unchanged if it's -1
      g =                  //     g is a recursive function taking
      d =>                 //     a direction d in [-1, 0, 1, 2]
      d + 2 ?              //       if d is not equal to -2:
        (                  //         we test whether the adjacent cell
          (                //         at (x', y') with:
            m[y + d-- % 2] //           y' = y + (d % 2)
            || 0           //
          )                //
          [x + d % 2]      //           x' = x + ((d - 1) % 2)
          == v             //         is equal to v
        )                  //         and increment the result if it is
        + g(d)             //         recursive call
      :                    //       else:
        d                  //         stop the recursion and subtract 2
    )(2)                   //     initial call to g with d = 2
  )                        //   end of inner map()
)                          // end of outer map()

```

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

```
ArrayFilter[Count[Extract[#,{{1,2},{2,1},{2,3},{3,2}}],#[[2,2]]]/.{1->#[[2,2]],_->0}&,#,{1,1},Padding->0]&

```

Try it online!

```
ArrayFilter[                       -apply to each 3x3 block, padded with 0s
  Count[                           -count the
    Extract[#,                     -occurrences at
      {{1,2},{2,1},{2,3},{3,2}}    -positions up, down, left, right
    ],
    #[[2,2]]                       -of the center element
  ]
  /.{1->#[[2,2]],_->0}&,           -replace with center element if count is 1, otherwise 0
#,{1,1},Padding->0]&

```

# Answer
> 3 votes
# Charcoal, 51 bytes

```
ＷＳ⊞υιυＵＭυ⪪ι¹ＦＬυ«Ｊ⁰ιＦＬ§υι«Ｆ⊖№ＫＶＫＫ§≔§υικ.→»»Ｊ⁰¦⁰Ｅυ⪫ιω

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings of digits. Explanation:

```
ＷＳ⊞υιυ

```

Input the strings and print them to the canvas.

```
ＵＭυ⪪ι¹

```

Split the strings into character lists so that they can be replaced.

```
ＦＬυ«

```

Loop over each of the lists.

```
Ｊ⁰ι

```

Jump to the start of its line.

```
ＦＬ§υι«

```

Loop over the cells of the list.

```
Ｆ⊖№ＫＶＫＫ§≔§υικ.

```

Count the number of times the cell appears in its Von Neumann neighbourhood. If it's more than once then replace the state with a `.`.

Move to the next cell.

```
»»Ｊ⁰¦⁰Ｅυ⪫ιω

```

Overwrite the canvas with the new states.

# Answer
> 2 votes
# Retina 0.8.2, 125 bytes

```
(.)(?<=(\1).)?(?=(?<2>\1))?(?<=(?<!.)(?(3)$)(?<-3>.)*(?<2>\1).*¶(.)*.)?(?=(?<=(.)*.).*¶(?<-4>.)*(?(4)$)(?<2>\1))?(?<-2>){2}
.

```

Try it online! Link includes test suite that splits on double-spaced tests and double-spaces the results. Explanation:

```
(.)

```

Match a character...

```
(?<=(\1).)?

```

... that might be preceded by a copy of that character, ...

```
(?=(?<2>\1))?

```

... that might be followed by a copy of that character, reusing capture group 2 for the count of copies, ...

```
(?<=(?<!.)(?(3)$)(?<-3>.)*(?<2>\1).*¶(.)*.)?

```

... that might be below a copy of that character, using a .NET balancing group to ensure both characters are in the same column, ...

```
(?=(?<=(.)*.).*¶(?<-4>.)*(?(4)$)(?<2>\1))?

```

... or that might be above a copy of that character, ...

```
(?<-2>){2}

```

... where two copies exist.

```
.

```

Replace it with a dot.

# Answer
> 2 votes
# Python 3, 111 bytes

```
lambda k:[c*(sum('0'<c==(k+" "*d)[n+q]for d in(1,k.find('\n')+1)for q in(d,-d))<2)or'.'for n,c in enumerate(k)]

```

Try it online!

Returns a list of characters.

-1 byte thanks to ovs

Thanks to PertinentDetail for fixing a bug for only +3 bytes

# Answer
> 2 votes
# Jelly, 18 bytes

```
ŒĠạⱮ§ỊSʋÐṀ⁸$€ẎŒṬ¬a

```

A monadic Link that accepts a list of list of positive integers and yields a list of lists of non-negative integers (`0` representing the unclued cells).

**Try it online!** Or see the test-suite.

### How?

```
ŒĠạⱮ§ỊSʋÐṀ⁸$€ẎŒṬ¬a - Link: list of lists, A
ŒĠ                 - group multi-dimensional indices by their values
            €      - for each group (a list of coordinates, G, where one of the values are):
           $       -   last two links as a monad, f(G):
          ⁸        -     using G as the right argument...
        ÐṀ         -     filter G keeping those [a,b] which are maximal under:
       ʋ           -       last four links as a dyad, f([a,b], G)
   Ɱ               -         map across G with:
  ạ                -           absolute difference (vectorises)
    §              -           sums (-> Manhatten distances)
     Ị             -           insignificant? (0 or 1?)
      S            -           sum
             Ẏ     - tighten to a list of coordinates (of the blanks in the puzzle)
              ŒṬ   - multi-dimensional untruth
                ¬  - logical NOT (vectorises)
                 a - logical AND with A (vectorises)

```

# Answer
> 2 votes
# , 112 bytes

```
function(m)m*(apply(which(m|1,T),1,function(j)sum(m[t((j+rbind(o<-c(1:-1,0),rev(o)))%%(dim(m)+1))]==m[t(j)]))<2)

```

Try it online!

```
unsolved=function(m)                # get unsolved puzzle for matrix m:
 m*                                 # m multiplied by...
  (apply(which(m|1,T),1,function(j) # function applied to all coordinates of m:
    sum(m[                          #  sum of elements of m...
     t((j                           #  at each coordinate...
      +rbind(o<-c(1:-1,0),rev(o)))  #  plus (1,0),(0,-1),(-1,0) & (0,1)...
     %%(dim(m)+1))                  #  modulo dimensions of m +1...
                                    #  (prevents offset coordinates becoming too big)
    ]==m[t(j)]))                    #  that are equal to the value at this coordinate
  <2)                               # is less than 2
                                    # (so, is equal to 1, since there are no 'lonely'
                                    # digits without any equal neighbours as each line
                                    # is guaranteed to be length 3 or longer)

```

# Answer
> 2 votes
# BQN, 41 bytes

```
4⊸⊑⊸(⊣×1=·+´1‿3‿5‿7⊏=)∘⥊⎉2 3‿3↕⊢↑˝·≍⟜¬2+≢

```

Try it here.

It is a tacit function which takes input as an integer array and returns an integer array. The function can be split into three parts:

Pad the input with 0s on all sides.

```
⊢↑˝·≍⟜¬2+≢ #
       2+≢ # Add 2 to each dimension of the shape
⊢↑˝·≍⟜¬    # and use that to over-take from the input in each direction

```

Make a rank 4 array of the 3 by 3 windows.

```
3‿3↕

```

Replace each window with it's center element if it is an endpoint, otherwise replace with 0.

```
4⊸⊑⊸(⊣×1=·+´1‿3‿5‿7⊏=)∘⥊⎉2 #
                        ⎉2 # On the rank 2 subarrays:
                      ∘⥊   # flatten
4⊸⊑                        # get the center element,
   ⊸(                )     # and pass as the left argument into the train:
                    =      # compare equality of flattened window with center
            1‿3‿5‿7⊏       # pick out only the Manhattan neighbors
         ·+´               # sum the true values
       1=                  # test if equals 1,
     ⊣×                    # and multiply bool result by the center element

```

# Answer
> 1 votes
# Ruby, 170 bytes

```
->m{(0...R=m.size).map{|y|(0...C=m[0].size).map{|x|[[y-1,x],[y,x-1],[y+1,x],[y,x+1]].reject{|a,b|a<0||a>=R||b<0||b>=C}.map{|a,b|m[y][x]==m[a][b]?1:0}.sum<2?m[y][x]:'.'}}}

```

Try it online!

* Straightforward approach : we cross check every element against the 4 adjacent elements and we keep it if there are only 1, we put a dot instead.
* to check adjacent elements we build an array of \[y,x\] indexes and we reject pairs out of bounds, this costs so many bytes!

# Answer
> 1 votes
# Matlab, ~~102~~ 90 bytes

```
function a=f(a)
for i=1:9
b=a==i
a=a-b.*(conv2(b,[0 1 0;1 0 1;0 1 0],'same')~=1)*i
end
end

```

The input is *a* and the output is also *a*. This goes through all the values in the grid (1 to 9). For each value it finds cells that have more than one neighbor of that value. This is done using the 4-directional 2D convolution conv2. It then sets those cells to 0. What is left is the required grid. Note this will also work if there are multiple paths with the same digit. It also works for the case when digit 1 is missing, but digit 2 exists.

-12 bytes by removing unnecessary white space. Thanks to @MarcMush!

---
Tags: code-golf, array, grid, path-finding
---