title: Minimal distinct character quine

text:
# Question
Title: Minimal distinct character quine
Your challenge is to construct a *proper* quine using as few *distinct* characters as possible.

## Scoring

Your score is equal to the number of distinct characters in your code, aiming to minimise this. Standard quine rules apply.

# Answer
> 11 votes
# Python 3, 9 distinct characters, 15341 bytes

```
exec('%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+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1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+'%c'%(+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1))

```

Try it online!

This encodes each character as a series of `+1`s and then sums them all together before executing the final encoded program:

```
A="""print(end='exec('+'+'.join("'%%c'%%("+'+1'*ord(B)+")"for B in'A=""'+'"'+%r+'"'+'"";exec(A%%A)')+")")""";exec(A%A)

```

Try it online!

# Answer
> 9 votes
# \>\<\>, 3 distinct characters, 1432 bytes

```
111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--1111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1--111-1--p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11p

```

Try it online!

This uses the characters `1-p` to `p`ut this code at the start of the program:

```
"/
o<
:/r~:

```

This quotes the whole program, accounts for the characters that were overwritten, and then outputs the program itself.

# Answer
> 6 votes
# Haskell, Score 13, 523 bytes

```
p=putStr;main=a>>mmm>>a>>mmm>>mmmm>>mmmmm>>mmm>>mm>>mmm>>mmmm>>mm>>mmmmm>>mmm>>mmmmmm>>mmm>>mmm>>mmmm>>mm>>mm>>mmmmm>>mmm>>mmmm>>mmm>>mmmm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmm>>mmm>>mmmm>>mm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmmm>>mmmmmm>>mmm;a=p"p=putStr;main=a>>mmm>>a>>mmm>>mmmm>>mmmmm>>mmm>>mm>>mmm>>mmmm>>mm>>mmmmm>>mmm>>mmmmmm>>mmm>>mmm>>mmmm>>mm>>mm>>mmmmm>>mmm>>mmmm>>mmm>>mmmm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmm>>mmm>>mmmm>>mm>>mm>>mm>>mm>>mmmmm>>mmm>>mmmmmm>>mmmmmm>>mmm;a=p";mm=p"m";mmm=p"\"";mmmm=p";m";mmmmm=p"m=p";mmmmmm=p"\\"

```

Try it online!

The used characters are:

```
p=utSr;main>"\

```

# Answer
> 4 votes
# Charcoal, 31 bytes, 4 distinct characters

```
≔´θ´´´≔´´´´´⪫´θ´´´´´θθ´≔´´⪫θ´´θ

```

Try it online! Explanation: I started with the standard Charcoal quine from Golf you a quine for great good! (which uses six distinct characters) and adapted it to try to remove the ,  and `ι` characters, which I was able to do at the cost of having to use the  character instead. I was then amused to discover that in fact the final quine was the same length as the original quine (less the trailing newline, which was needed for a true quine in the then version of Charcoal that used  instead of ).

# Answer
> 4 votes
# Ruby, 31 bytes, score: 8 distinct bytes

```
$;="$;=%p;$><<$;%%$;";$><<$;%$;

```

Try it online!

# Answer
> 4 votes
# Jelly, 3 bytes, 2 distinct bytes

```
”ṘṘ

```

Try it online!

## How it works

This is the standard Jelly quine, nothing too interesting

```
”ṘṘ - Main link. Takes no arguments
”Ṙ  - Yield the character "Ṙ"
  Ṙ - Convert to a Jelly representation ("Ṙ" -> ”Ṙ) and print
    - Implicitly output the character "Ṙ"

```

# Answer
> 3 votes
# Python 3, 11 distinct bytes

```
p='p=%r;print(p%%p)';print(p%p)

```

Try it online!

Nice. Uses p and r as variables because print is necessary, so why not just use the characters from there? 31 bytes in length if that's a tiebreaker.

I don't see this being improved on, given TC Python 3 is already ~~7~~ 8 characters.

# Python 2, 10 distinct bytes

```
p='p=%r;print p%%p';print p%p

```

Try it online!

What I do see, however, is that Recursive Co. has gotten a 10 byte answer, which, again, is 3 from optimal. Go upvote their answers as well!

# Answer
> 2 votes
# JavaScript console (~~9 8~~ 7 distinct characters, ~~21 22~~ 24 bytes)

```
($=$=>'($='+$+')($)')($)

```

Thanks to JoKing, again for -1 byte!

Older versions

```
($=_=>`($=`+$+`)()`)() // 8 distinct characters
($=_=>`($=${$})()`)() // 9 distinct characters

```

# Answer
> 2 votes
# Ruby, 25 bytes 8 distinct bytes

```
p="p=%p;$><<p%%p";$><<p%p

```

Try it online!

Thanks to Jo King for -1 distinct byte

# Answer
> 2 votes
# Klein, score 6, 71 bytes

```
<22+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+@+2+2+2+2+2+2+2+2+2+2+2+2+2+2+2+22<"

```

Try it online!

Uses the characters `<2+@"` and newline. This uses `"` to push all the rest of the program backwards. However since this portion of the program is a palindrome, there is no need to put it in the correct order. All we have to do is add `"` onto the end. This is done by adding a whole bunch of `2`s up to 34.

# Answer
> 2 votes
# C (gcc), score 21, 64 bytes

```
main(s){printf(s="main(s){printf(s=%c%s%c,34,s,34);}",34,s,34);}

```

Try it online!

Standard C quine, except not using the `%1$c` since that's extra chars.

### Breakdown

* `main(,){";}` (11) are probably required
* `printf` (+5=16) is required for most standard quines
* `%cs` (+3=19) from the format string
* `34` (+2=21), the ASCII code for the double quote. I don't believe hexadecimal or octal will be better here

# Answer
> 2 votes
# C (gcc) for Linux x86\_64, score 13, ~~8241~~ 7604 bytes

```
main[]={+1111+1111+1111+1111+1111+111+111+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+111+111+111+11+11+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+11+11+11+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+11111+11111+1111+111+111+111+111+111+111+111+11+11,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+1,+1111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+111+111+11+11+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+111+111+111+111+111+111+111+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+1111111+1111+111+11+11+11+11+11+1+1+1+1+1+1+1+1+1,+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+11+11+11+11+1+1+1+1+1+1+1,+1111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+11+11+11+11+1+1+1+1+1+1+1+1+1+1,+1111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+111+111,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+1+1+1+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+1+1+1+1+1+1,+1111111111,+1111111111+111111111+111111111+111111111+111111111+11111111+11111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+11+11+11+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+111111+11111+11111+11111+11111+1111+1111+111+111+111+111+111+11+11+11+11+1+1,+1111111111+1111111111+1111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+1+1+1+1+1+1,+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+1,+1111111111+1111111111+1111111111+111111111+111111111+11111111+11111111+1111111+1111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+1+1,+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+1111+1111+111+111+111+111+111+11+11+11+11+11+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+11111+1111+1111+1111+1111+1111+1111+111+111+111+111+11+11+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+1111111111+111111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+111+11+11+11+11+11+1+1+1+1+1,+1111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+1111+1111+1111+1111+1111+1111+111+111+111+11+11+1,+1111111111+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+11+1+1+1+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+11111+11111+11111+11111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+1+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+111+11+1+1+1+1,+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+11111111+1111111+1111111+111111+111111+111111+11111+11111+1111+1111+1111+1111+111+11+11+11+11+11+1+1+1+1,+11111111+11111111+11111111+11111111+11111111+1111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+1111+1111+1111+111+1+1,+1111111111+1111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111111+11111111+1111111+1111111+1111111+1111111+111111+111111+111111+111111+111111+111111+11111+11111+11111+11111+11111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+111+111+111+11+11+11+11+11+11+1+1+1,1};

```

Try it online!

This uses the characters `aimn[]={}+1,;`

Bootstrap program:

```
.text
.section .text.startup,"ax",@progbits
.globl main
.type main, @function
main:
.cfi_startproc
call poprbp
.ascii "main[]={,+1111111111};"
poprbp:
pop %rsi
lea -5(%rsi),%rbp
lea 119(%rsi),%r8
push %rdi
pop %rax
push $8
pop %rdx
syscall
add $9, %rsi
push:
mov 0(%rbp),%r12d
push $11
pop %r13
mov $1111111111,%ebx
push $10
pop %r14
cmp:
cmp %r12d, %ebx
jbe movslq
xchg %ebx, %eax
xor %edx, %edx
dec %r13d
div %r14d
xchg %eax, %ebx
jmp cmp
movslq:
movslq %r13d, %rdx
ones:
push %rdi
pop %rax
syscall
sub %ebx,%r12d
jne cmp
comma:
dec %rsi
push %rdi
pop %rax
push %rdi
pop %rdx
syscall
inc %rsi
add $4, %rbp
cmp %r8, %rbp
jne push
theend:
add $10, %rsi
push $3
pop %rdx
syscall
ret
.cfi_endproc
.size main, .-main

```

Try it online!

This was based on the following C program.

```
#include<unistd.h>
main(){
  write(1,"main[]={",8);
  int i = 0;
  do {
    unsigned int x = 1111111111;
    unsigned int y = ((unsigned int*)main)[i];
    do {
      while( y<x ) {
        x/=10;
      }
      printf("+%d",x);
    }
    while(y-=x);
    write(1,",",1);
  } while ( i++<10 );
  write(1,"1};",3);
}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 18 distinct bytes

```
$_=q(print"\$_=q($_);eval;");eval;

```

Try it online!

This is a classic Perl quine. I have no idea how Perl works, but this is tested on TIO. Feel free to tell me how to improve this. 34 bytes if that matters.

# Answer
> 1 votes
# Vyxal, 2 distinct bytes, 4 bytes

```
`I`I

```

Try it Online!

classic vyxal quine

---
Tags: code-challenge, quine
---


title: Irradiated Polyglots

text:
# Question
Title: Irradiated Polyglots
Design a function or program that, when run normally, outputs the triangular numbers. However, when any single character is deleted, the program/function should not function in the original programming language, but instead produce the triangular numbers in one other programming language.

## Scoring

Your score will be the number of characters in your program for which the program is not valid in your second chosen language.

Lowest score wins, tiebreaker is byte count.

## Specific Rules

You may infinitely output triangular numbers, produce a list of the first N with a positive integer input N, or produce the Nth triangular number. Each of the programs may have different behavior in this respect.

Your original program may run in the second language, but it can't produce the correct output.

Your programs may also output in different bases/use different indexing/use different output formats, as long as that format would be valid in a challenge.

No more than 20% of your characters, rounded down, may be invalid.

An invalid character is any character that, when removed, creates no program or function that outputs triangular numbers in your second chosen language.

Any time you remove a character from the original code, it should break it.

Separate versions of programming languages ARE permitted to be treated as different languages.

# Answer
> 9 votes
# Perl 5 `-M5.010` \+ A Pear Tree, score 0, tiebreak score 96 bytes

```
$_='{length==86&&6&&say$T0+=++$b9F;redo}{print$tYC+=++$nKy;redo}#{print$tYC+=++$nKy;redo}#';eval

```

Try it online! (Perl)

Try it online! (A Pear Tree)

A Pear Tree was designed for challenges and challenges. I think, however, this is the first time I've used it on a challenge that falls into both categories.

This was annoyingly time-consuming to verify – my normal verifier programs don't handle infinite loops well, and yet an infinite loop is shorter to write than a "loop up to input" is in Perl, so I ended up having to check all the irradiated programs manually.

The `-M5.010` argument to Perl is a version selection argument that's basically standard in golfing at this point (and used to be allowed without penalty even back when we penalised for command-line arguments) – I would add it out of habit even if it didn't do anything (although it's required here).

## Explanation

### Perl

Most of the program is stored in a string, `$_`, which is immediately evaluated:

```
$_='…';eval
$_='…'         initialize variable $_
       eval    evaluate {$_} as a program

```

(`$_` is chosen as the variable because it's the default variable that most commands use when an operand is missing, so this helps out the tiebreak score a little.)

The program itself does the following:

```
{length==86&&6&&say$T0+=++$b9F;redo}{…}#…
{                             ;redo}        infinite loop
                say                           print
                   $T0                          the value of $T0
                      +=                      after adding
                          $b9F                  the value of $b9F to it
                        ++                    after adding 1 to that
              &&                            but only if
 length                                       the length {of $_}
       ==86                                     is 86
           &&                               and
             6                                6 is truthy
                                    {…}     unreachable code
                                       #…   comment

```

The actual calculation of the triangular numbers is very simple (although confusing because there are two assignments inside the expression) – `$T0` holds the triangular number itself, and `$b9F` its index, and we repeatedly add 1 to `$b9F` and then add `$b9F` to `$T0` in order to produce the sequence of triangular numbers. Perl variables are initialised with `undef`, which acts like 0 when you increment it or add numbers to it. (The variable names don't matter to the Perl program, and are as weird as they are due to how A Pear Tree works.)

The unreachable code – part of the A Pear Tree program – is syntactically valid, but never runs because there's an infinite loop immediately before it.

The `length==86` check is used to ensure that none of the irradiated versions of the program print the triangular numbers in Perl. Deleting most things outside the long string literal, or its delimiters, produces a syntax error. Deleting characters from `eval` is not a syntax error, but the resulting program does nothing when run, because the string is never evaluated. Some deletions inside the string produce syntax errors; these are caught by `eval` (thus no error message is printed), but prevent the string being evaluated. For other deletions inside the string, the `length==86` check will prevent anything actually being printed (it will either be intact, or be corrupted into something falsey), so the code still doesn't output the triangular numbers.

The check for 6 being truthy is mostly irrelevant – it was added purely so that I could have two `&&`s in there, thus preventing the scenario in which a lone `&&` (short-circuiting AND) gets irradiated into `&` (bitwise AND) and causes the `say` statement to run uncondtionally. (With the two `&&`s, if either of them gets corrupted into `&`, the other still prevents the `say` statement running because its left-hand side will be falsey.)

### A Pear Tree

To write an A Pear Tree program, you need to decide which substrings of the program are going to be checked for corruption by the interpreter – the interpreter will rotate the largest such part to the start before running the program (and error out if there is no such portion). The substrings in question are marked implicitly by changing irrelevant internal details of them in such a way that their CRC32 is 0.

In this program, there are three such sections with a CRC32 of 0 – the entire program, and the two `{print$tYC+=++$nKy;redo}#` substrings.

In a non-irradiated run of the program, the largest section is the program itself, so it runs unrotated, and is has effectively identical control flow to the Perl. However, `say` is not a keyword in A Pear Tree (the "print with newline" builtin is called `print` there, in one of its very minor differences from Perl), so the program hits an error when it tries to execute `say` (which is caught by the `eval` and the program exits naturally). It would be possible to exploit other differences between the languages (e.g. `$\` is falsey in Perl but truthy in A Pear Tree), but using the existence/nonexistence of `say` is terser.

If you delete any character from the program, the program as a whole will no longer have a CRC32 of 0, so one of the `{print$tYC+=++$nKy;redo}#` substrings (whichever one didn't get irradiated, or the first one if they're both intact) is rotated to the start, followed by the rest of the program. However, the `#` at the end of the substring comments the rest of the program out, so we just end up with a small loop that calculates triangular numbers. This is identical to the triangular number calculation part of the Perl code, except for the variable names and the use of `print` rather than `say`. (Incidentally, although A Pear Tree often allows you to omit the `$` before a variable name, it doesn't allow this after the `++` operator and wouldn't save bytes after the `print`, so for once all the `$`s are present.)

In order to mark the appropriate substrings of the code, I changed the variable names (and other details like the specific truthy constant in the Perl code – obviously, any truthy constant would work for Perl, not just `6`, but `6` worked best for A Pear Tree), which is why they're so weird.

---
Tags: code-challenge, sequence, polyglot, radiation-hardening
---


title: Lexicographically self-comparing code

text:
# Question
Title: Lexicographically self-comparing code
This is a challenge related to Write the shortest self-identifying program (a quine variant)

Write a function or a full program that compares lexicographically its source code and input, that is, output three distinct values of your choice telling if `input` / `source code` is *Bigger*, *Equal* or *Less* than `source code` / `input`.

# Specifications

> A Lexicographic order is a *generalization of the alphabetical order of dictionaries to sequences of elements of an ordered set \[Wikipedia\].*

In short it works just like dictionaries:
To determine if string *A* is greater than a string *B*

* we compare the order of each first character (from the left).
The string with bigger order element is greater.
* If first character of each are equal we compare the second and so on.
* If one string ends then that string is smaller.
* If *A = B* they are equal.

The ordered set is the natural character encoding of the language you choose and your submission has to work correctly with it.
For example UTF or ASCII.

# Examples

We use *Less, Eq and Greater* as output and ASCII as alphabet for clarity and simplicity.

source: "A"
input : "B"
output : Greater (input \<=\> source)

source: "a\_X"
input : "A\_x"
output : Greater (source \<=\> input)

source: "A,X"
input : "A,x"
output : Less (source \<=\> input)

source: "#!\*"
input : " "
output : Greater (source \<=\> input)

source: "x!y"
input : "x!y"
output : Eq (source \<=\> input)

# Rules

* Standard rules apply and specifically reading your own source code is not allowed.
* 0-length answers are disallowed.
* input: a sequence of characters in any convenient format (string, list or array of characters, codepoints).
You can handle empty input but it is not required.
* output:
Three distinct values of your choice meaning less equal and greater.
You are free to choose to tell if input is \<=\> than source or if source is \<=\> than input, just be consistent and specify it.
* This is , all usual rules apply.

Sandbox

# Answer
# , ~~92~~ 90 bytes

```
'->T;f=\\(a,b=paste(sQuote(T),T))(a>=b)+(a>b)' ->T;f=\(a,b=paste(sQuote(T),T))(a>=b)+(a>b)
```

Attempt This Online!

Outputs `2` if the input is greater than the code, `1` if they're equal and `0` otherwise.

Simple modification of @Dominic van Essen's `R` quine.
> 3 votes

# Answer
# Jelly,  ~~32~~  22 bytes

-10 thanks to Unrelated String! (Using `M` (-8) and using a full program (-2)).

```
“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM

```

Expects the code using characters from the code-page from STDIN and prints `2` if equal to the code, `0` if less, or `1` if more.

* without the deprecated, but supported, alternative characters of  and `ṿ`, or the newline alternative to .

**Try it online!**

### How?

```
“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM - Main Link: no arguments
“Ṿ;,ɠØJiⱮⱮM”           - "Ṿ;,ɠØJiⱮⱮM"
            Ṿ          - unevaluate -> "“Ṿ;$,⁸ØJiⱮⱮṢƑ+EƊ”"
             ;         - concatenate -> the source code = "“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM"
               ɠ       - read a line from STDIN = I
              ,        - pair -> [source, I]
                ØJ     - Jelly's code-page
                  iⱮⱮ  - index of each character in each of [source, I]
                     M - maximal, 1-indexed, indices:
                                            source < I -> [2]
                                            source = I -> [1,2]
                                            source > I -> [1]

```
> 3 votes

# Answer
# PARI/GP, 31 bytes

```
f=(a)->if(a<s=Str("f="f),2,s<a)
```

Attempt This Online!

Outputs `1` if the input is greater than the code, `0` if they're equal and `2` otherwise.

---

## PARI/GP, cheating, 28 bytes

```
(a)->if(a<s=Str(self),2,s<a)
```

Attempt This Online!
> 2 votes

# Answer
# 05AB1E (legacy), ~~28~~ 26 bytes

```
"34çì·‚Ð{QsË+"34çì·‚Ð{QsË+

```

-2 bytes by switching to the legacy version of 05AB1E, where double on string works

Outputs `0` if the source code is smaller; `1` if the input is smaller; and `2` if both are equal.

Try it online or verify a few example test cases.

**Explanation:**

It's based on this base quine: `"34çì·"34çì·`.

```
"34çì·‚Ð{QsË+"  # Push string "34çì·‚Ð{QsË+"
 34ç            # Push 34, converted to a character: '"'
    ì           # Prepend it to the string: '"34çì·‚Ð{QsË+'
     ·          # Double it: '"34çì·‚Ð{QsË+"34çì·‚Ð{QsË+'
      ‚         # Pair it with the (implicit) input
       Ð        # Triplicate it
        {       # (Lexicographically) sort the pair
         Q      # Check if the top two pairs are the same
          s     # Swap to get the remaining pair
           Ë    # Check if both values are the same
            +   # Add the two checks together
                # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Ruby, 85 bytes

```
->a{z,m,w='->a{z,m,w=',',',';a<=>[z,z,m,m,m,w,w]*39.chr}';a<=>[z,z,m,m,m,w,w]*39.chr}

```

Try it online!

### Explanation:

Not very golfy, I know.

I could take the answer to the linked question and replace '==' with '\<=\>' for 29 bytes, but I wanted to try something different, and opted not to use `eval`.

There is a lot of room for improvement, but I like the way it turned out.
> 2 votes

# Answer
# Haskell, 42 bytes

```
compare$s++show s;s="compare$s++show s;s="

```

Try it online!

*compare* program Vs input.

Outputs *Ord* value :
EQ equal
GT program \> input
LT otherwise
> 2 votes

# Answer
# JavaScript, 23 bytes

```
f=s=>s<(F='f='+f)?0:F<s

```

Try it online!

Outputs `0` if input less than source, `false` for equal, and `true` for greater than.
> 2 votes

# Answer
# Vyxal `D`, 14 bytes

```
`I~>∇≥+`I~>∇≥+

```

Try it Online!

prints `0` for smaller, `1` for equals and `2` for greater
> 2 votes

# Answer
# Ruby, ~~74~~ 49 bytes

```
p [*$<]*''<=><<'2'*2+?2
p [*$<]*''<=><<'2'*2+?2
2

```

Try it online!

~~Note trailing newline~~

Adapted from the typical Ruby quine. Outputs `0` if input is the same as source, and `1` or `-1` if it is different. Thanks to Jo King for suggesting the use of `[*$<]*''` to capture input.
> 1 votes

# Answer
# Julia, 70 bytes

```
(q=:(show((ARGS[] > (Q = "(q=:($(q)))|>eval")) - (ARGS[] < Q))))|>eval

```

Try it online!

takes input as a single command line argument, and prints `0` for *Equal*, `1` for *Greater* and `-1` for *Less*

Based on the following quine, which is explained in this answer by Dennis (adapted for Julia 1.0):
`(q=:(print("(q=:($(q)))|>eval")))|>eval` Try it online!

Sadly, all the spaces are neccessary, since the code is stored as an AST, and converting it to a string will put all the spaces back. Also, defining a function or using a macro don't work because of the lengthy comments that are automatically added in the AST
> 1 votes

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


title: Solve the Zany car game

text:
# Question
Title: Solve the Zany car game
The **Zany Car Game** is a tile matching game. You are given a number of tiles, with coloured cars split into a top and bottom half. To win the game, you need to find a square arrangement of the tiles so that only whole, correctly coloured cars are formed at each tile join , like the image below.

## Challenge

Given a square set of mixed tiles, output any solution of correctly ordered tiles. If there is no solution, output nothing. You can choose how to input the tiles. You may either output the tiles in your input format, or output the required rearranged position of the tiles and their rotations from the input (see the example).

This is , the shortest answer in bytes wins

## Example

Take each tile as a flat list, of the form `[UP, RIGHT, DOWN, LEFT]`. The colour-half combinations are represented by numbers as follows

```
Red top = 1
Red bottom = 8
Green top = 2
Green bottom = 7
Blue top = 3
Blue bottom = 6
Yellow top = 4
Yellow bottom = 5

```

So that the top and bottom of any given colour add to 9 (similar to how a die is arranged).

For this example we will use the following arrangement of tiles that needs solving:

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

```

Which can be represented as a 2D list or a flattened list:

```
input = [
[[2,1,5,6],[3,5,7,1],],
[[7,4,1,6],[2,8,6,4],],
]
or
input = [[2,1,5,6],[3,5,7,1],[7,4,1,6],[2,8,6,4]]

```

The solution for this example can either be given as the rearranged tiles or the new position of each tile in the flattened list, with the rotation for each tile given as `0=0°, 1=90°, 2=180°, 3=270°`

```
output = [[6, 4, 2, 8], [7, 1, 3, 5], [7, 4, 1, 6], [6, 2, 1, 5]]
or
positions = [3, 1, 2, 0]
rotations = [2, 2, 0, 3]

```

Either of these should correspond to the solution:

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

```

A python script solving this example can be found here.

## Test Cases

It's worth noting that each unique solution will have 4 solutions, 1 for each rotation of the whole grid. Only one orientation will be given here.

Input 1:

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

```

Output 1:

```
[[6,4,2,8],[7,1,3,5],[7,4,1,6],[6,2,1,5]]
or
positions = [3, 1, 2, 0]
rotations = [2, 2, 0, 3]

```

Input 2:

```
[[1,2,3,4],[2,3,4,1],[3,4,2,1],[4,1,2,3]]

```

Output 2:
No solution

Input 3:

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

```

Output 3:

```
[[7,3,4,8],[4,2,8,6],[5,7,1,2],[1,5,6,2]]
or
Positions = [0, 3, 1, 2]
Rotations = [2, 3, 2, 2]

```

Input 4:

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

```

Output:

```
[[1,5,6,2],[1,6,7,4],[4,8,7,3],[3,5,7,1],[2,8,6,4],[2,5,6,1],[2,5,7,1],[8,6,4,3],[3,5,7,1]]
or
Positions = [8, 1, 2, 0, 4, 5, 6, 3, 7]
Rotations = [2, 0, 0, 0, 0, 0, 0, 0, 2]

```

# Answer
> 3 votes
# Python3, 408 bytes:

```
lambda s:(q:=int(len(s)**0.5))and[j for k in next(f([[0]*q]*q,[(x//q,x%q)for x in R(q**2)],s),[])for j in k]
R=range
v=lambda x,L,A,B:all(all(0 in[i[j],i[j+1]]or 9==i[j][A]+i[j+1][B]for j in R(L-1))for i in x)
def f(b,M,s):
 if[]==s:yield b
 x,y=M[0]
 for O in s:
  for j in R(4):
   B=eval(str(b));B[x][y]=O[j:]+O[:j]
   if v(B,L:=len(b),1,3)and v(zip(*B),L,2,0):yield from f(B,M[1:],[i for i in s if i!=O])

```

Try it online!

# Answer
> 2 votes
# Python 3, 204 bytes

```
f=lambda a,*i:[z for b in a for c in f(a-{b},1)or[[]]for n in(0,1,2,3)for z in[c+[b[n:]+b[:n]]]if{p[2-b]+q[b*3]for b in(0,1)for p,q in zip(z,z[b or int(len(z)**.5):])if z.index(q)**2%len(z)-b+1}=={9}or i]

```

Try it online!

Recursively tries every possible permutation and returns the valid ones. This is a brute-force approach and times out for the last test case. It should work in principle, though.

---
Tags: code-golf
---


# Question
Title: Filter an array so that duplicate items are removed
In the shortest amount of code in any programming language, filter out the duplicate items in an array of which the order is irrelevant.

Here are some test cases:

```
[1, 2, 2, 3, 1, 2, 4] => [1, 2, 3, 4]
['a', 'a', 'b', 'a', 'c', 'a', 'd'] => ['a', 'b', 'c', 'd']

```

> I also should note that there currently aren't any open questions that meet these exact criteria.

# Answer
> 15 votes
# 1-byte built-ins

### 05AB1E (legacy)

```
Ù

```

Try it online!

Alternatively:

```
ê

```

Try it online!

### APL (Dyalog Unicode)

Try it online!

### Jelly

```
Q

```

Try it online!

#

```
U

```

# Stax

```
u

```

# MATL

```
u

```

Try it online!

# MathGolf

Try it online!

# Seriously/Actually

# Japt

```
â

```

Try it online!

# Pyth

```
{

```

Try it online!

# Husk

```
u

```

Try it online!

# Pyke

```
}

```

Try it online!

# Canvas

Try it online!

# Vyxal

```
U

```

Try it Online!

# Answer
> 6 votes
# Python 3, ~~15~~ 3 bytes

Reduced to 3 bytes thanks to a'\_'!!!

```
set

```

Try it online!

# Without set

# Python 3, ~~35~~ \\$\cdots\\$~~30~~ 29 bytes

Saved 3 bytes thanks to a'\_'!!!
Saved a byte thanks to Jitse!!!
Saved a byte thanks to Jonathan Allan!!!

```
lambda l:list(dict(zip(l,l)))

```

Try it online!

# Answer
> 4 votes
# Python 3, 3 bytes

```
set

```

Try it online! It also works on Python 2

Or without `set`:

## Python 3, ~~34~~ ~~29~~ 26 bytes

```
lambda l:[*dict(zip(l,l))]

```

Try it online! Thanks to Jonathan Alan and Surculose Sputum for helping me golf this one!

# Answer
> 4 votes
# Ruby, 8 bytes

```
->a{a&a}

```

or

```
->a{a|a}

```

Try it online!

Set intersection (`&`) or set union (`|`), both of which remove duplicates. Shorter than the built-in `uniq` method.

# Answer
> 4 votes
# Java 8, ~~27~~ 15 bytes

```
S->S.distinct()

```

Stream I/O.

Try it online.

**~~27~~ 22 bytes:**

```
java.util.HashSet::new

```

-5 bytes thanks to *@OlivierGrégoire*.

List input, Set output.

Try it online.

# Answer
> 3 votes
# Retina 0.8.2, 6 bytes

```
D`
G`.

```

Try it online! Doesn't work on empty strings. Explanation:

```
D`

```

Replace all duplicates with empty strings.

```
G`.

```

Remove all empty strings.

# Answer
> 3 votes
# JavaScript (Node.js), 13 bytes

```
a=>new Set(a)

```

Try it online!

Unfortunately `Set` must be used with `new`, otherwise the answer will be just 3 bytes: `Set`, as a function.

# Answer
> 3 votes
# Batch, 182 Bytes

```
@Echo Off&Setlocal EnableDelayedExpansion
For %%A In (%~1)do (
Set M=F
IF "!O!"=="" (Set O=%%A) Else (
For %%B in (!O!)do If %%A==%%B Set M=T
IF !M!==F Set O=!O!,%%A))
ECHO(!O!

```

Builds a string starting with first element of the original string, compares each element of the new string against the next element of the original string, assigning and testing a troothy value before appending the next element to the new string.

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

```
Union

```

Try it online!

# Answer
> 2 votes
# Io, 18 bytes

Io doesn't allow assigning functions. It's terrible!

```
method(x,x unique)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 9 bytes

```
Ｗ⁻θυ⊞υ⊟ιυ

```

Try it online! Link is to verbose version of code. Works best on strings due to the way Charcoal prints numbers by default. Explanation:

```
Ｗ⁻θυ

```

Remove all occurrences of elements in the result from the input. While this temporary value is not empty...

```
⊞υ⊟ι

```

... push the last element of that value to the result.

```
υ

```

Print the result.

# Answer
> 2 votes
# Erlang (escript), 41 bytes

Great thanks for the Haskell answer! (so that I can port it)

```
u([H|T])->[H]++u([X||X<-T,X/=H]);u(I)->I.

```

Try it online!

# Erlang (escript), ~~79~~ 72 bytes

It's a recursive definition of uniquifying. The premise is that Erlang doesn't have a set-conversion built-in.

```
u([H|T])->case string:find(T,[H])of nomatch->[H];_->[]end++u(T);u(I)->I.

```

Try it online!

# Explanation

u([H|T])-> % Try to split the input into a head & tail.

case string:find(T,[H])of
           % Check whether H is a substring of T.
           % Strings are lists in Erlang, so it
           % doesn't raise a type error when applied on lists.

nomatch->[H];
           % If false, return head.
_->[]end   % Else, return empty list.
++u(T);    % Recurse down until ...

u(I)       % ... the operand is an empty list,
->I.       % where the operand is returned
```
</code></pre>

# Answer
> 2 votes
# Haskell, 29 bytes

```
f(a:b)=a:f[x|x<-b,x/=a]
f x=x

```

Try it online!

This answer gives us the list with the first occurrence of every element.

# Haskell, 33 bytes

```
f(a:b)=[a|notElem a b]++f b
f x=x

```

Try it online!

This answer gives us the last occurrence of every element.

# Answer
> 2 votes
# Sledgehammer, 2 bytes

```
⠓⣻

```

Decompresses into this Wolfram Language function:

```
Union

```

# Answer
> 2 votes
# perl -E, 23 bytes

```
@_{<>}=0;say for keys%_

```

Reads an array from `STDIN`, one element per line. Writes the unique elements to `STDOUT`, elements separated by two newlines.

(No TIO link, as it seems to not terminate the final line of the input with a newline, which leads to an incorrect output).

# Answer
> 2 votes
# , 6 bytes

```
unique

```

Try it online!

# Answer
> 2 votes
# perl -MList::Util=uniq -E, 17 bytes

```
say for uniq@ARGV

```

Accepts an array as arguments, prints the unique elements to `STDOUT`, one element per line. TIO

# Answer
> 1 votes
# IBM/Lotus Notes Formula, 10 bytes

```
@Unique(i)

```

Takes input from multi-value field `i`. Screenshots below.

# Answer
> 1 votes
# Symja, 16 bytes

```
DeleteDuplicates

```

Try It Online!

# Answer
> 1 votes
# Clojure, 3 bytes

```
set

```

Try it online!

Returns a set, or preserving order:

# Clojure, 8 bytes

```
distinct

```

Try it online!

# Answer
> 1 votes
# MOO, 36 bytes

```
return #372:remove_duplicates(@args)

```

Extremely implementation-specific. The shortest non-implementation-specific way of doing this is `return $list_utils:remove_duplicates(@args)` (43 bytes).

Unfortunately, functions aren't first-class objects in this language, so `#372:remove_duplicates` (22 bytes) is a syntax error and thus isn't valid.

The shortest way of doing this without using a builtin is `x={};for y in (args[1])x=setadd(x,y);endfor return x;` (53 bytes)

# Answer
> 1 votes
# T-SQL, 24 bytes

```
SELECT DISTINCT v FROM t

```

Takes input as separate rows in a table *t* with varchar field *v*, which is permitted per our IO rules.

Without an `ORDER BY`, SQL returns the rows in a non-prescribed order.

# Answer
> 1 votes
## sh + POSIX utilities, 7 bytes

```
sort -u

```

## sh + POSIX utilities, 9 bytes

```
sort|uniq

```

---

### Notes

* The TIO uses `bash` because it doesn't provide plain `sh`, but it should work fine in any shell.
* I was flexible with the input (one entry of the array per line, no other markers) because `sh` doesn't have arrays. If you wanted to do it with, e.g., `bash` arrays, you could do this (TIO):

```
a=(1 2 2 3 1 2 4 a a b a c a d)
printf '%s\n' "${a[@]}" | sort -u

```

# Answer
> 1 votes
# C++ (gcc), 69 bytes

```
#import<set>
using s=std::set<int>;s f(int*a,int l){return s{a,a+l};}

```

This is what I like about C++: It has a lot of features.

Try it online!

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

```
i,j;f(a,l)int*a;{for(i=l;i--;)for(j=l;j--;)i-j?a[i]-a[j]?:bcopy(a-~i,a+i,--l-i<<2):0;}

```

Hoping to roll the two loops together.

Try it online!

# C (gcc), 87 bytes

```
i,j;f(a,l)int*a;{for(i=j=l;i-=j--==l;j=j?:l)i-j?a[i]-a[j]?:bcopy(a-~i,a+i,--l-i<<2):0;}

```

Turns out longer.

Try it online!

# Answer
> 0 votes
# Factor, 7 bytes

```
members

```

Try it online!

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


# Question
Title: Recreate a 'Snake' game in a console/terminal
## Games are fun

This Code Golf here was so fun I had to make a version for other classic games similar in complexity: Shortest Way of creating a basic Space Invaders Game in Python

This time, however, try to recreate the classic 'Snake' game, in which you start out as a small shape, constantly moving to collecting pieces to increase your score. When you collect a piece, your 'tail' grows, which follows the path you have made. The objective is to last the longest without crashing into your own tail, or into the walls

Qualifications:

* You, the characters that make up the tail, the walls, and the pieces you collect should all be different characters
* Show a HUD with the score. The score increases by 1 point for each piece you collect
* The player loses when they collide with their own tail or the wall
* A piece spawns in a random area immediately after a piece is collected, not to mention at the start of the game
* Speed of the game doesn't matter, as long as it is consistent
* ~~The 'cells' should be 2x1 characters, since the height of block characters is ~twice the width~~ Can be 1x1, because 2x1 is just ugly and I didn't really think of that
* The keys for changing the direction should be `awsd`, left, up, down, right respectively
* The starting direction should always be up
* You must show the edges of the wall. The score may overlap the wall

Shortest code that meets the above criteria wins. Imaginary Bonus Points for creativity.

# Answer
## JavaScript (~~553~~ 512 bytes)

Link to playable version

```
c=0;a=b=d=-1;e=[f=[20,7],[20,8]];i=Math.random;~function n(){if(c&&(87==a||83==a
))c=0,d=87==a?-1:1;if(d&&(65==a||68==a))d=0,c=65==a?-1:1;p([j=e[0][0]+c,k=e[0][1
]+d])||!j||39==j||!k||10==k?b+=" | GAME OVER":(e.unshift([j,k]),p(f)?(f=[1+38*i(
)|0,1+9*i()|0],b++):e.pop());for(m=h="";11>h;h++){for(g=0;40>g;g++)l=g+","+h,m+=
!g||39==g||!h||10==h?"X":e[0]==l?"O":p(l)?"*":f==l?"%":" ";m+="\n"}x.innerHTML=m
+b;!b.sup&&setTimeout(n,99)}();onkeydown=function(o){a=o.keyCode};function p(o){
return e.join(p).indexOf(p+o)+1}

```

I tried to make it output to the real console at first (with `console.log` and `console.clear`), but it was flickering too much, so I put it into console-like HTML. It will work with this:

```
<pre id=x>

```

Also I implemented it with 2x1 cells first, but it just looked worse than 1x1. That would be a minor change though.

Uses `awsd` keys on keyboard.

**Update:**

I was able to cut it down to 512 (exactly 0x200) bytes by improving the tail search and doing some more magic.

You now get 2 points when a piece spawns in your tail (it's a feature). I also fixed the overlapping when the snake bites itself.
> 33 votes

# Answer
**16 bit 8086**

526 bytes / 390 bytes

Decode this using a Base64 decoder and call it "snake.com" then execute from Windows command prompt. Tested on WinXP, you may need to use DosBox to get the right video mode. Control keys are 'wasd' and space to exit. Press 'w' to start.

```
uBMAzRC5AD+2AOipAb1AAbgAoI7Auf//v4sMsAHzqrgAtLksAfOqg8cU/sx19OgsAYs+8gKwAuj4
ALQAzRpCiRYOA4kWEAPouAC0C80hCsB0IbQIzSG+ygKDxgOAPAB0EjgEdfSLRAGzAP/Qo1cBiB7w
AulqAIEGdAGu/7P+uNECgMMEw7MCuNsCgMMGw4s+8gKLHvACisPolwADv+YCJoo16I0AiT7yAoD+
A775AnREiz70AiaKHbAA6HUAA7/mAok+9AKA/gB0FscGVwHNAoEudAGu/zPJtj/o2QDofQC0AM0a
OxYOA3X2/wYOA+lZ/8YEAE7+BIA8CnT16F4AaOAB6EQAM9K5LQD38YvCweACBQoA9+WL+OguALlL
ADPS9/HB4gKDwgsD+iaAPQB10rADiMRXq4HHPQGrq4HHPAGrq4HHPQGrX8OhEAO62wD34rntf/fx
iRYQA4vCw772Ar8K9bUEshCstACL2AHDi4f6ArMDtwXR+LEAwNEC/smA4Q8miA0p7/7PdevoIQA6
xHQE/st13ugKAP7NdcroAwB1+8O3BSbGBQEp7/7PdfaBx0EG/srDuBAQM9uAwwLNEID7CnX2w7gD
AM0QzSB3dgEgxgIAYYcBZIUBIMYCAHd8AXN+ASDGAgAA+wAF/P8EAAIAH4ofigAAAADRxeD/TJlO
gQPvQrVA4++BVdVjgQ==

```

Here's a character mode version that's 390 bytes long:

```
uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq7LdfCxUPOr6BgBiz5+AqF8Aqu0AM0aQ
okWhgKJFogC6MUAtAvNIQrAdCG0CM0hvlYCg8YDgDwAdBI4BHX0i0QBswD/0KNSAYgefALpdgCBB
m8Bov+z/rhdAoDDBMOzArhnAoDDBsOLPn4Cix58AiaJHQOclgmijUmiR2JPn4CgP4DvoUCdFOLPo
ACJoodJscFAAADv3JYiT6AAoD+AHQkxwZSAVkCgS5vAaL/vwEAudAHJoA9qnUEJsYFzIPHAuLx6F
4AtADNGjsWhgJ19oMGhgIC6Uz/xgQATv4EgDwKdPXoPgBo5wHoIgC5FwD38Wn6oADoFgC5TgD38U
ID0gP6JoA9AHXhJscFA93DoYgCutsA9+K57X/38YkWiAKLwjPSw76CAr8CALkEALSfrAQwq+L6w8
0gd3EBIFcCAGGCAWSAASBXAgB3dwFzeQEgVwIAYP+gAP7/AgACqtAH0AcAAAAA

```

This character mode one's three bytes longer (but the snake's better):

```
uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq/7LdfCxUPOr6BsBiz6BAibHBQEKtADN
GkKJFokCiRaLAujHALQLzSEKwHQhtAjNIb5ZAoPGA4A8AHQSOAR19ItEAbMA/9CjUwGIHn8C6XgA
gQZwAaD/s/64YAKAwwTDswK4agKAwwbDiz6BAosefwImiR0Dv3VYJoo1JscFAQqJPoECgP4DvogC
dFOLPoMCJoodJscFAAADv3VYiT6DAoD+AHQkxwZTAVwCgS5wAaD/vwEAudAHJoA9qnUEJsYFzIPH
AuLx6F4AtADNGjsWiQJ19oMGiQIE6Ur/xgQATv4EgDwKdPXoPgBo6gHoIgC5FwD38Wn6oADoFgC5
TgD38UID0gP6JoA9AHXhJscFA93DoYsCutsA9+K57X/38YkWiwKLwjPSw76FAr8CALkEALSfrAQw
q+L6w80gd3IBIFoCAGGDAWSBASBaAgB3eAFzegEgWgIAYP+gAP7/AgACqtAH0AcAAAAA

```
> 10 votes

# Answer
## shell/sh, 578 chars

I tried to be POSIX compliant (being as much portable as possible and avoid bashisms, even the random-number-generator does not need /proc). You can e.g. play it in your native terminal or via a SSH-session: run with 'dash -c ./snake' There is also an unuglyfied/readable variant in ~2800 bytes, which can be seen here.

Some notes: shell-scripting is not suited for coding games 8-)

* to be fair, we only used so called 'builtins', which means:
    + no external calls of programs like 'clear', 'stty' or 'tput'
    + because of that, we redraw the whole screen on every move
    + the only used builtins (aka native commands) are:
        - echo, eval, while-loop, let, break, read, case, test, set, shift, alias, source
* there is no random number generator (PRNG), so we have to built our own
* getting a keystroke blocks, so we have to spawn another thread
    + for getting the event in parent-task we use a tempfile (ugly!)
* the snake itself is a list, which is cheap:
    + each element is a (x,y)-tuple
    + loosing the tail means: shift the list by 1
    + adding a (new) head means: append a string
* the grid is internally an array, but shell/sh does not know this:
    + we "emulated" array(x,y) via an ugly eval-call with global vars
* and finally: we had a lot of fun!

```
#!/bin/sh
alias J=do T=let E=echo D=done W=while\ let
p(){ eval A$1x$2=${3:-#};}
g(){ eval F="\${A$1x$2:- }";}
r(){
E $((1+(99*I)%$1))
}
X=9
Y=8
L="8 8 $X $Y"
I=41
W I-=1
J
p $I 1
p $I 21
p 1 $I
p 41 $I
D
p 3 3 :
>L
W I+=1
J
E -ne \\033[H
y=22
W y-=1
J
Z=
x=42
W x-=1
J
g $x $y
Z=$Z$F
D
E "$Z"
D
E $B
. ./L
case $D in
a)T X+=1;;d)T X-=1;;s)T Y-=1;;*)T Y+=1;;esac
g $X $Y
case $F in
\ |:)p $X $Y O
L="$L $X $Y"
case $F in
:)W I+=1
J
x=`r 39`
y=`r 19`
g $x $y
[ "$F" = \  ]&&{
p $x $y :
break
}
D
T B+=1;;*)set $L
p $1 $2 \
shift 2
L=$@;;esac;;*).;;
esac
D&
while read -sn1 K
J
E D=$K>L
D

```
> 7 votes

# Answer
### C# .NET Framework 4.7.2 Console (~~2,456~~ ~~2,440~~ ~~2,424~~ ~~2,408~~ ~~2,052~~ ~~1,973~~ ~~1,747~~ 1,686 bytes)

This was fun, but I really had to think what variables were what, because they are only one letter.

```
using m=System.Console;using System;using System.Collections.Generic;using System.Threading;class s{static void Main(){m.CursorVisible=0>1;new s()._();}int l;Action<string> w=(x)=>m.Write(x);Action<int,int>n=(x,y)=>m.SetCursorPosition(x,y);(int x,int y)d,c,a;int h,u;List<(int x,int y)>p;void _(){while(1>0){f();h=25;u=25;p=new List<(int x,int y)>();l=0;d=(0,-1);c=(u/2,h/2);e();m.SetWindowSize(u+4,h+4);m.SetBufferSize(u+4,h+4);while(1>0){k();if(t())break;g();r();}f();m.SetWindowSize(u+4,h+6);m.SetBufferSize(u+4,h+6);n(1,h+3);w("        Game over,\n   press any key to retry.");f();m.ReadKey(1>0);m.Clear();}}private bool t(){if(c.x<0||c.y<0||c.x>=u||c.y>=h){r();n(c.x+2,c.y+2);w("X");return 1>0;}for(i=0;i<p.Count;i++){for(int j=0;j<i;j++){if(p[i].x==p[j].x&&p[i].y==p[j].y){r();n(c.x+2,c.y+2);w("X");return 1>0;}}}return 0>1;}private void e(){a=(z.Next(u),z.Next(h));l++;}void f(){while(m.KeyAvailable)m.ReadKey(1>0);}int i;void k(){var b=DateTime.Now;while((DateTime.Now-b).TotalMilliseconds<230)Thread.Sleep(10);if(!m.KeyAvailable)return;var a=m.ReadKey(1>0).Key;switch(a){case ConsoleKey.A:if(d.x==0)d=(-1,0);break;case ConsoleKey.W:if(d.y==0)d=(0,-1);break;case ConsoleKey.S:if(d.y==0)d=(0,1);break;case ConsoleKey.D:if(d.x==0)d=(1,0);break;}f();}void g(){c.x+=d.x;c.y+=d.y;p.Add((c.x,c.y));while(p.Count>l)p.RemoveAt(0);if(c.x==a.x&&c.y==a.y)e();}void r(){n(1,1);w("/");w(new string('-',u));w("\\");n(1,h+2);w("\\");w(new string('-',u));w("/");for(i=0;i<h;i++){n(1,i+2);w("|");n(u+2,i+2);w("|");}for(i=0;i<h;i++){for(int j=0;j<u;j++){n(i+2,j+2);w(" ");}}n(a.x+2,a.y+2);w("@");for(i=0;i<p.Count;i++){n(p[i].x+2,p[i].y+2);w("#");}n(2,0);w("Score:"+l);}Random z=new Random();}

```

Some screenshots:

\<no longer have binaries, you can compile yourself\>
> 6 votes

# Answer
# Applesoft Basic - 478 (462)

This was my first ever code golf, but it was written back in 1989, and it mostly implements the snake game as requested (but without food, the snakes just continuously grow, and it's actually two players, not one) using only two lines of Applesoft Basic.

There were a number of two-line program contests at the time, such as in Dr. Dobbs journal. I spent 6 months figuring out how to fit this into two lines which have a limit of 255 characters (and only one branch)

More info at: http://davesource.com/Projects/SpeedWaller/

The program typed in is exactly two lines:

```
1ONSCRN(X,Y)<>7ANDB<>0ANDSCRN(U,V)<>7GOTO2:HOME:GR:X=10:Y=20:U=30:V=Y:I=201:J=202:K=203:M=205:W=215:A=193:S=211:Z=218:O=1:Q=-1:P=49152:COLOR=7:HLIN0,39AT0:HLIN0,39AT39:VLIN0,39AT0:VLIN0,39AT39:VTAB22: ?"WASZ IJKM  "C:ONB=0GOTO2:CALL-678:RUN
2PLOTX,Y:PLOTU,V:B=PEEK(P):G=B<>ZANDB<>W:H=B<>AANDB<>S:O=G*(O*H+(B=S)-(B=A)):L=H*(L*G+(B=Z)-(B=W)):G=B<>IANDB<>M:H=B<>JANDB<>K:Q=G*(Q*H+(B=K)-(B=J)):R=H*(R*G+(B=M)-(B=I)):X=X+O:Y=Y+L:U=U+Q:V=V+R:FORN=1TO99:NEXT:C=C+1:VTAB22:HTAB12:?C:GOTO1

```

The listing when formatted looks like this:

```
1 ONSCRN(X,Y)<>7 AND B<>0 AND SCRN(U,V) <> 7 GOTO 2: HOME : GR :
  X=10 : Y=20 : U=30 : V=Y : I=201 : J=202 : K=203 : M=205 : W=215 :
  A=193 : S=211 : Z=218 : O=1 : Q=-1 : P=49152 : COLOR=7 : HLIN 0,39
  AT 0 : HLIN 0,39 AT 39 : VLIN 0,39 AT 0 : VLIN 0,39 AT 39 : VTAB 22 :
  ? "WASZ IJKM  "C : ON B=0 GOTO 2 : CALL -678 : RUN
2 PLOT X,Y : PLOT U,V : B=PEEK(P) : G= B<>Z AND B<>W: H=B<>A AND B<>S :
  O=G*(O*H+(B=S)-(B=A)) : L=H*(L*G+(B=Z)-(B=W)) : G=B<>I AND B<>M :
  H=B<>J AND B<>K : Q=G*(Q*H+(B=K)-(B=J)) : R=H*(R*G+(B=M)-(B=I)) :
  X=X+O : Y=Y+L : U=U+Q : V=V+R : FOR N=1 TO 99 : NEXT : C=C+1 :
  VTAB 22 : HTAB 12 : ? C : GOTO 1

```

The game is actually *two players* and includes "instructions" at the bottom of the page showing the keys as well as a counter so you can see how many steps you survived. It's 478 characters, 16 of those are the instructions and counter output, so 462 if you want to shave those off.
> 5 votes

# Answer
# TI-Basic, 307 bytes

This one is very special to me, since I learned to program with a similar snake game on my TI-83+ (in high school, during boring classes). Also, on these calculators, golfing the programs was a real concern because of the limited space and performance

The controls are the direction keys, but they could easily be changed for `awsd` (although noone would want that since it's an `abc` layout)

codes for the keys would be: `A`: 41, `W`: 85, `S`: 81, `D`: 51

```
ClrHome
99→dim(ʟX
ʟX→Y
{8,16→dim([A]
For(X,1,16
For(Y,1,8
If X=1 or X=16 or Y=1 or Y=16
Then
Output(Y,X,":
1→[A](Y,X
End:End:End
8→X:7→Y:-1→V
Repeat [A](Y,X
1+I(I<99→I
Y→ʟY(I
X→ʟX(I
Output(Y,X,0
1→[A](Y,X
If X=N and Y=O or not(N
Then
Repeat not([A](O,N
randInt(2,7→O
randInt(2,15→N
End
Output(O,N,1
Output(1,1,S
S+1→S
Else
1+J(J<99→J
ʟY(J
Output(Ans,ʟX(J),"
0→[A](Ans,ʟX(J
End
getKey→G
not(G)U+(G=26)-(G=24→U
not(G)V+(G=34)-(G=25→V
X+U→X:Y+V→Y
End

```
> 5 votes

# Answer
**Ruby 1.9 */Windows only/* (354 337 355 346 bytes)**

```
require'Win32API';G=(W=Win32API).new g="crtdll","_getch",t=[],?I
B=(c=?#*39+h="#
#")+((S=' ')*38+h)*20+c;n=proc{c while B[c=rand(800)]!=S;B[c]=?*;S}
n[h=760];k={97=>-1,100=>1,119=>d=-41,115=>41}
(B[h]=?O;system'cls';$><<B<<$.;sleep 0.1
d=k[G.call]if W.new(g,"_kbhit",[],?I).call>0
t<<h;B[h]=?o;B[h+=d]==?*?B[h]=n[$.+=1]:B[t.shift]=S)while B[h]==S

```

Plays in a 20x40 board in the windows console. The score is shown under the board. Use `WASD` to control the snake, any other key to exit (forcefully!). Edit the sleep time at the end of line 5 to control the speed. *(Or save 10 characters and make it nearly unplayable by removing the sleep entirely!)*

Bonus feature: randomly fails to start (when initial piece is generated in snake's location).

I needed ~100 chars to work around the lack of a non-blocking getchar. Apparently Ruby 1.9.3 includes a "io/console" library which would have saved roughly half of those. And this solution is Windows specific. There are published solutions to do the same type of thing in \*nix systems, but I haven't tested them to compare the character count.

Edit:

Had to add 18 bytes after I realized that the tail only grows after eating, not after each step.

Edit 2: (Possibly) fixed crash issue, saved the 9 bytes by restricting to one food item.
> 4 votes

# Answer
# Python 3 - 644

```
from curses import *
import time
from collections import deque
from random import randrange as R
N,W,S,E=z=119,97,115,100
t=tuple
u=0,0
def m(s):
 a=lambda o,y,x:y.addch(o[0],o[1],x);q=lambda:(R(L-2),R(C-2));L,C=s.getmaxyx();curs_set(0);s.nodelay(1);s.border();s.refresh();r=newwin(L-2,C-2,1,1);n=deque();y,x=[L-2,0];d=N;n.append(u);c=N;p=q();a(p,r,N);a(u,s,48)
 while 1:
  if c in z:d=c
  if d==N:y-=1
  if d==S:y+=1
  if d==W:x-=1
  if d==E:x+=1
  l=n.pop()
  if (y,x) in n:return
  if (y,x)==p:p=q();a(p,r,N);n.append(l);s.addstr(0,0,str(len(n)))
  n.appendleft((y,x));a((y,x),r,S);a(l,r,32);r.refresh();time.sleep(.2);c=s.getch()
wrapper(m)

```

Does not quit cleanly. Piece might disappear if it spawns on top of the snake.
> 4 votes

# Answer
## Bash (too many characters: ca. 1522)

```
t=tput
tc="$t cup"
tr="$t rev"
ts="$t sgr0"
ox=5
oy=5
((w=$($t cols)-2-2*ox))
((h=$($t lines)-2-2*oy))
trap "$t rmcup
stty echo
echo 'Thanks for playing snake!'
" EXIT
$t smcup
$t civis
stty -echo
clear
printf -v hs %$((w+2))s
printf -v v "|%${w}s|"
$tc $oy $ox
printf %s ${hs// /_}
for((i=1;i<=h+1;++i)); do
$tc $((oy+i)) $ox
printf %s "$v"
done
$tc $((oy+h+2)) $ox
printf %s ${hs// /¯}
dx=0
dy=-1
hx=$((w/2))
hy=$((h-2))
l=2
xa=($hx $hx)
ya=($hy $((hy+1)))
$tr
for((i=0;i<${#xa[@]};++i)); do
$tc $((ya[i]+1+oy)) $((xa[i]+1+ox))
printf \
done
$ts
print_food() {
$tc $((fy+1+oy)) $((fx+1+ox))
printf "*"
}
nf() {
rf=1
while((rf))
do
rf=0
((fx=RANDOM%w))
((fy=RANDOM%h))
for ((i=0;i<${#ya[@]};++i))
do
if((ya[i]==fy&&xa[i]==fx))
then
rf=1
break
fi
done
done
print_food
}
nf
ps() {
s="SCORE: $l"
$tc $((oy-1)) $((ox+(w-${#s})/2))
printf "$s"
}
ps
while :
do
read -t 0.2 -s -n1 k
if (($?==0))
then
case $k in
w|W)((dy==0))&&{ dx=0;dy=-1;};;
a|A)((dx==0))&&{ dx=-1;dy=0;};;
s|S)((dy==0))&&{ dx=0;dy=1;};;
d|D)((dx==0))&&{ dx=1; dy=0;};;
q|Q)break;;
esac
fi
((hx=${xa[0]}+dx))
((hy=${ya[0]}+dy))
if((hx<0||hy<0||hx>w||hy>h))
then
go=1
break
fi
for((i=1;i<${#ya[@]}-1;++i))
do
if((hx==xa[i]&&hy==ya[i]))
then
go=1
break 2
fi
done
$tc $((ya[-1]+1+oy)) $((xa[-1]+1+ox))
printf \
$tr
$tc $((hy+1+oy)) $((hx+1+ox))
printf \
$ts
if((hx==fx&&hy==fy))
then
((++l))
ps
nf
else
ya=(${ya[@]::${#ya[@]}-1})
xa=(${xa[@]::${#xa[@]}-1})
fi
ya=($hy ${ya[@]})
xa=($hx ${xa[@]})
done
if((go))
then
$tc 3 3
echo GAME OVER
read -t 3 -s -n1
fi

```
> 1 votes

# Answer
# Binary - ~~617~~ 274 Bytes

Base 64:

```
jtiO0LgAuI7AMf+50Ae4IAJg86u4//+5JgC/qALzq7kRAKtguSkAMcDzq7j//6thgceeAOLsuSYAv0oN86
thic+9BgDojADkYCR/PEh0HDxLdBM8TXQKPFB17IHHoADrDoPHBOsJg+8E6wSB76AAsAkmgD0HD5TEdAYm
gD0gdYCqT2AGHgeJ6UG+GH0B7on3R0f986T8B2FXiT4YfYD8AXQJi74YfbAgquskRUW/MAKDBhR9AaEUfb
MK9vOGxAQwqoPvA4jgMOQIwHXu6AQAX+l0/2Bmuf//AABm9/G5///38YnXgef/D4H/gAJ95on6g8Iog+oo
g/ooffiD+hJ91IHH0wDB5wImgD0JdMewB6phww==

```

Hex:

```
d88ed08e00b88eb831c0b9ff07d020b86002abf3ffb8b9ff0026a8bff302b9ab001160ab29b93100f3
c0b8abffff61abc781009eece226b9bf000d4aabf38961bdcf00068ce8e40024603c7f74483c1c744b
3c13744d3c0a755081eca0c7eb00830e04c709ebef83eb048104a0efb00026093d800f07c494067480
26203d80754faa0660071ee989be417d18ee01f7894747f3fdfca461078957183e807d01fc0974be8b
7d1820b0ebaa4524bf45023006837d14a1017d140ab3f3f6c486300483aa03efe088e430c008ee7504
e85f0074e960ffb966ffff0000f766b9f1fffff1f7d789e7810fffff810280e67dfa89c283832828ea
fa837d2883f812fad47dc78100d3e7c126023d807409b0c7aa07c361

```

Create a .com file from the above hex and run it in DOSBox.

Even though the qualifications says:

> Speed of the game doesn't matter, as long as it is consistent

You should use the command `cycles 1` if you want the game to be playable

There is also a version with no score which is 232 bytes

```
8ed88ed0b800b88ec031ffb9d007b8200260f3abb8ffffb92600bfa802
f3abb91100ab60b9290031c0f3abb8ffffab6181c79e00e2ecb92600bf
4a0df3ab6189cfbd0600e86c00e460247f3c48741c3c4b74133c4d740a
3c5075ec81c7a000eb0e83c704eb0983ef04eb0481efa000b00926803d
070f94c4740626803d207580aa4f60061e0789e941bee87c01ee89f747
47fdf3a4fc076157893ee87c80fc0174098bbee87cb020aaeb054545e8
03005feb9460b9ffff66f7f181e2ff0f81fa80027df089d783c22883ea
2883fa287df883fa127dde81c7d300c1e70226803d0974d1b007aa61c3

```
> 1 votes

# Answer
# JavaScript (Node) (348 bytes)

```
B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0
]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3)
}#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>
f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z>
3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D()

```

Pretty is not a requirement, right? Or easy? Or big?

You start in the top-left corner of a 2x2 grid, facing up (so you better push "d" real quick). A "9" represents a background character, a "1" is the head of your snake, any "0"s are tails, and a "2" is a piece you're trying to collect.

Browser-playable version

```
// Mocking Node
process = {
  stdin: {
    setRawMode: () => ({
      on(_, callback) {
        addEventListener('keydown', e => callback(e.key))
      }
    })
  }
}
process.exit = () => {
  for (let i = 0; i < 9999; ++i) clearInterval(i)
  throw new Error('Game Over!')
}

// Allow restarting
document.getElementById('run')
  .addEventListener('click', () => {
    for (let i = 0; i < 9999; ++i) clearInterval(i)
    main()
  })

function main() {
  // The game
  B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3)}#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z>3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D()
}
```

```
<button id=run>run</button>
```

A slowed-down version (A 99ms interval is pretty difficult)

```
// Mocking Node
process = {
  stdin: {
    setRawMode: () => ({
      on(_, callback) {
        addEventListener('keydown', e => callback(e.key))
      }
    })
  }
}
process.exit = () => {
  for (let i = 0; i < 9999; ++i) clearInterval(i)
  throw new Error('Game Over!')
}

// Allow restarting
document.getElementById('run')
  .addEventListener('click', () => {
    for (let i = 0; i < 9999; ++i) clearInterval(i)
    main()
  })

function main() {
  // The game
  B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3)}#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z>3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),499);D()
}
```

```
<button id=run>run</button>
```

You know you've won when you get a max-call-stack-exceeded error :).

If you want a version that's a little nicer to play, I also golfed a 3x3 version down to 381 bytes.

```
B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0]
==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h:
'#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin.
setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:
-3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s
=[z,...s],z^o?s.pop():o=B(I++)),99);D()

```

Browser-playable version

```
// Mocking Node
process = {
  stdin: {
    setRawMode: () => ({
      on(_, callback) {
        addEventListener('keydown', e => callback(e.key))
      }
    })
  }
}
process.exit = () => {
  for (let i = 0; i < 9999; ++i) clearInterval(i)
  throw new Error('Game Over!')
}

// Allow restarting
document.getElementById('run')
  .addEventListener('click', () => {
    for (let i = 0; i < 9999; ++i) clearInterval(i)
    main()
  })

function main() {
  // The game
  B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0]==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h:'#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D()
}
```

```
<button id=run>run</button>
```

Slowed down version

```
// Mocking Node
process = {
  stdin: {
    setRawMode: () => ({
      on(_, callback) {
        addEventListener('keydown', e => callback(e.key))
      }
    })
  }
}
process.exit = () => {
  for (let i = 0; i < 9999; ++i) clearInterval(i)
  throw new Error('Game Over!')
}

// Allow restarting
document.getElementById('run')
  .addEventListener('click', () => {
    for (let i = 0; i < 9999; ++i) clearInterval(i)
    main()
  })

function main() {
  // The game
  B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0]==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h:'#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),299);D()
}
```

```
<button id=run>run</button>
```
> 1 votes

# Answer
# Haskell, 579 bytes

```
import System.Process;import System.IO;p=('#'<$j)++"##\n";j=[0..20];r=fromEnum<$>withBinaryFile"/dev/urandom"ReadMode hGetChar;e(a,b)x|x=a|0<1=b;m s@(h@(x,y):t)d f=e(putStrLn"You Lost",do system"clear";putStr$foldr(++)p[show$length t,"\n",p,do y<-j;'#':[let z|elem(x,y)s='@'|f==(x,y)='F'|0<1=' 'in z|x<-j]++"#\n"];c<-hWaitForInput i 99;d<-e(getChar,pure d)c;a<-r;b<-r;let n|d>'s'=(x,y-1)|d>'r'=(x,y+1)|d>'a'=(x+1,y)|0<1=(x-1,y)in m(e(id,init)(h==f)$n:s)d$e((mod a 17+2,mod b 17+2),f)$h==f)$or[h`elem`t,x<0,y<0,x>20,y>20];main=hSetBuffering i NoBuffering>>m[(9,8)]'w'(9,8);i=stdin

```

Try it online!
> 1 votes

# Answer
# C (gcc), 581 bytes

```
#define S++s;for(i=0,j=0;m[i][j];i=rand()%h)j=rand()%w;m[i][j]=2;
#define F for(i=0;i<h;++i){for(j=0;j<w;++j)
i,j,w=24,h=12;x=6,y=9;s;*t;c='w';
main(n){int m[h][w];for(memset(m,0,4*w*h);i<h;)*m[i++]=m[i][w-1]=1;for(srand(time(0));j<w;)j++[*m]=m[h-1][j]=1;m[y][x]=-1;S for(fcntl(0,4,2048);1;*t=-s){F n=m[i][j],putchar(n+s?n<0?'O':n-1?n-2?' ':'$':'#':'@');puts("");}printf("score:%d\n\n",s);usleep(200000);while(read(0,&n,1)+1)c=n-97&&n-'w'&&n-'s'&&n-'d'?c:n;c&2?y-=((c&4)-2)/2:(x-=(c&1)*2-1);t=m[y]+x;if(*t==2){S}else if(*t){puts("you died");break;}else F if(m[i][j]<0)++m[i][j];}}}

```

Try it online!

Some bytes can be saved by replacing variables `w` and `h` with fixed values, and characters `O @#$` with two-digits integers, but I prefer to keep it as it is in order to make it easier to customize.
> 0 votes

---
Tags: code-golf, game
---


title: Count the Liberties - Advanced

text:
# Question
Title: Count the Liberties - Advanced
Here's an advanced version of the Count the Liberties challenge.

The definitions of the terms *liberty* and *group* are the same as the previous challenge, so have a look at the previous one for details, but briefly put,

* A *group* is a group of stones that are connected horizontally or vertically.
* *Liberty* is the number of empty spaces connected horizontally or vertically to a group.

For example,

```
. . O .
. X X .
. X . .
. O O .

```

black's group (`X`) has 5 liberties, the upper group of white (`O`) has 2 liberties, and the lower group of white has 3 liberties.

For input, you will be given an 2D array of arbitrary size, in which each cell has one of `black`, `white`, or `empty`. You may map any value of any data type for `black`, `white`, and `empty`; but 1 value can be mapped to each.

All groups in the input will always have 1 or more liberties.

For output, the cells that had `empty` will be `0`, and the cells that had `black` or `white` will be filled with the number of liberties of its group.

### Examples

```
. . O .      0 0 2 0
. X X .  ->  0 5 5 0
. X . .      0 5 0 0
. O O .      0 3 3 0

. X . O  ->  0 2 0 1

X      1
X      1
.  ->  0
.      0
O      2
.      0

. X X .      0 3 3 0
X . X O  ->  2 0 3 2
X X O .      2 2 1 0

```

---

If you have participated in the previous challenge, having to count the liberties of multiple groups may require a quite different strategy.

# Answer
# 05AB1E, ~~85~~ 81 bytes

```
2FINi(}Θ©˜ƶIgäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅs«à]+ÐU˜ê¦©vyX®y†AS:¾1:'a0:4FJTx:€Søí}S2¢:

```

"*If you have participated in the previous challenge, having to count the liberties of multiple groups may require a quite different strategy.*" That's an understatement, haha. This answer is almost 8 times as large as my 05AB1E answer for the related challenge. Although this is primarily because flood-filling is so expensive in 05AB1E; and the conversion I use is currently pretty verbose as well..

Uses `-1`/`1` for `O`/`X` and `0` for empty spaces.

Try it online or verify all test cases.

**Explanation:**

Step 1: Flood-fill the individual islands. I've done this before in 05AB1E for this challenge (which actually contained a bug that I discovered thanks to the final test case here):

```
2F            # Loop 2 times (for each 1/-1 type of piece individually):
  I           #  Push the input-matrix
   Ni }       #  If the 0-based loop-index is 1:
     (        #   Negate all values
       Θ      #  Check which values are equal to 1 (maps 1→1; 0→0; -1→0)
        ©     #  Store this in variable `®` (without popping)
  ˜           #  Flatten it to a list
   ƶ          #  Multiply each value by its 1-based index
      ä       #  Convert it back to the matrix,
    Ig        #  using the input-length amount of rows
  Δ           #  Loop until it no longer changes to flood-fill:
   2Fø0δ.ø}   #   Add a border of 0s around the matrix:
   2F     }   #    Loop 2 times:
     ø        #     Zip/transpose; swapping rows/columns
       δ      #     Map over each row:
      0 .ø    #      Add a leading/trailing 0
   2Fø€ü3}    #   Convert it into overlapping 3x3 blocks:
   2F    }    #    Loop 2 times again:
     ø        #     Zip/transpose; swapping rows/columns
      €       #     Map over each inner list:
       ü3     #      Convert it to a list of overlapping triplets
   ®*         #   Multiply each 3x3 block by the value in matrix `®`
              #   (so the 0s remain 0s)
   εεÅsyøÅs«à #   Get the largest value from the horizontal/vertical cross of
              #   each 3x3 block:
   εε         #    Nested map over each 3x3 block:
     Ås       #     Pop and push its middle row
       y      #     Push the 3x3 block again
        ø     #     Zip/transpose; swapping rows/columns
         Ås   #     Pop and push its middle rows as well (the middle column)
           «  #     Merge the middle row and column together to a single list
            à #     Pop and push its maximum
]             # Close the nested maps, flood-fill loop, and outer loop
 +            # Add the values in the two matrices together

```

Try just step 1 online.

Step 2: Loop over the individual islands, and convert all `0`s to `1`s; the current island to `0`s; and all other islands to lowercase letters, as preparation for the next step:

```
Ð             # Triplicate the resulting matrix
 U            # Pop one, and save it in variable `X`
  ˜           # Flatten another one
   ê          # Sort and uniquify the values
    ¦         # Remove the leading 0
     ©        # Store these island-values in variable `®` (without popping)
v             # Loop over each island-value `y`:
  X           #  Push matrix `X`
   ®          #  Push list `®`
    y†        #  Filter the current island to the front
      AS      #  Push the lowercase alphabet as list
        :     #  Replace the island-values with letters
   ¾1:        #  Replace all 0s with 1s
   'a0:       #  Replace all "a" (the current island) with 0s

```

Try the first 2 steps online (with some added debug-lines).

Step 3: Use the same method as in the linked challenge to get the liberty-counts of each island:

```
  4F          #  Loop 4 times:
    J         #  Join the inner rows together to strings
     T        #  Push 10
      x       #  Double it (without popping): 20
       :      #  Replace all "10" with "20"
        €S    #  Convert each row back to a list again
          øí  #  Rotate the matrix 90 degrees clockwise:
          ø   #   Zip/transpose; swapping rows/columns
           í  #   Reverse each inner row
   }          #  Close the loop
    S         #  Convert the matrix to a flattened list of characters
     2¢       #  Count how many 2s are in this list

```

Try the first 3 steps online (again with added debug-lines).

Step 4: Convert the current island to this count in the matrix:

```
              # The matrix from the triplicate of step 2 is still on the stack
 y            #  Push island-value `y` from the still open loop of step 2
       :      #  Replace all of these islands with its count from step 3
              # (after which the resulting matrix is output implicitly)

```
> 4 votes

# Answer
# APL(Dyalog Unicode), 43 bytes SBCS

Takes an integer matrix with 0 for blanks and any positive integer for a color (Supports any number of colors)

```
⍴⍴,+.<∘.(2>+⍥|.-)⍨⍤,⍤⍳⍤⍴∨.∧⍨⍣≡⍤∧,∘.(=≠0=⊣),

```

Try it on APLgolf!

The general strategy is to build an adjacency matrix for positions on the board, find the transitive closure, and, for each position with a color, count how many blank squares are connected to it. Some step-by-step results can be seen on APLgolf.

`,` Flatten the board matrix. To work with 2d adjacency matrices, we must represent the board in 1d. In the end `⍴⍴` will put the result into the correct shape.

`,∘.(...),` Create a matrix by applying the inner function between each pair of values:
`=` are the values equal (of same color)?
XOR
`0=⊣` is the right one a zero.
This connects places of equal colors, and colored pieces to blank squares in one direction.

`(2>+⍥|.-)⍨⍤,⍤⍳⍤⍴` adjacency matrix for horizontal and vertical neighbourhood on the grid.
`,⍤⍳⍤⍴` Indices of the grid, flattened
`(...)⍨⍤` Table for all pairs of these values
`2>+⍥|.-` Is the absolute distance less than 2?

The final adjancency table is generated by  of the two matrices, then `∨.∧⍨⍣≡` finds the transitive closure (The matrix that has 1's where there is a valid path between two nodes)

`,+.<` Magic inner product, counting for each node on the grid, to how many blank spaces it is connected.

`⍴⍴` Reshape the resulting flat vector into a matrix of the same shape of the input.
> 4 votes

# Answer
# JavaScript (ES7),  ~~153 135 133~~  130 bytes

Expects a matrix of integers with \\$0\\$ for empty, \\$1\\$ for white, \\$2\\$ for black.

```
f=(m,V,X,Y,n=0,M=m.map((r,y)=>r.map((v,x)=>V?n+=V[k=[x,y]]|(x-X)**2+(y-Y)**2-1?0:(V[k]=1,v-V)?!v:f(m,V,x,y):f(m,[v],x,y))))=>V?n:M

```

Try it online!

### How?

When defined, the parameter \\$V\\$ is a singleton array whose value is the reference color that triggered the recursion and whose underlying object is used to store the positions of the connected squares that were already visited.

On the initial call, we walk through the matrix and simply trigger a recursive call for each square \\$v\\$ at position \\$(x,y)\\$:

```
f(m, [v], x, y)

```

On subsequent calls, we receive \\$V\\$ along with the reference position \\$(X,Y)\\$. We walk through the matrix again, this time applying the following logic:

```
n +=                 // update the liberty counter n:
  V[k = [x, y]] |    //   if this square was already visited
  (x - X) ** 2 +     //   or the squared Euclidean distance between
  (y - Y) ** 2 - 1 ? //   (x, y) and (X, Y) is not equal to 1:
    0                //     do nothing
  :                  //   else:
    (                //
      V[k] = 1,      //     mark this square as visited
      v - V          //     NB: V is coerced to an integer
    ) ?              //     if v is not equal to V:
      !v             //       increment n if v = 0
    :                //     else:
      f(m, V, x, y)  //       do another recursive call

```

**NB**: We do not prevent the recursion from starting when the reference square is empty. This is harmless because we simply flood-fill the empty space without updating \\$n\\$.
> 3 votes

# Answer
# 05AB1E, 37 bytes

Port of my APL answer. Really not the right language for the job but still slightly beats it.

```
˜©DδÊ®Ā^IāsнgLâDδαO2‹*ΔDøδ*OĀ}®›øOIgä

```

Try it online!
> 3 votes

# Answer
# Python3, 510 bytes:

```
E=enumerate
def S(b,x,y):
 for X,Y in[(0,1),(0,-1),(1,0),(-1,0)]:
  try:
   if(A:=x+X)>=0 and(B:=y+Y)>=0:yield(A,B,b[A][B])
  except:1
def f(b):
 a,s=[],[]
 while(o:=[(x,y,c)for x,t in E(b)for y,c in E(t)if c in['X','O']and(x,y,c)not in s]):
  q,A=[o[0]],[]
  while q:x,y,c=q.pop(0);A+=[(x,y,c)];q+=[i for i in S(b,x,y)if i[-1]==c and i not in A]
  a+=[A];s+=A
 for i in a:
  for x,y,_ in i:b[x][y]=str(len({k for X,Y,_ in i for k in S(b,X,Y)if k[-1]=='.'}))
 return '\n'.join(map(' '.join,b)).replace('.','0')

```

Try it online!
> 1 votes

# Answer
# Octave, 157 bytes

```
function E=f(B)
A=([W,k]=(l=@bwlabel)(B==1,4))+([R,n]=l(B>1,4))+k.*~~R;
E=0*B;
for x=1:n+k
E=E+(X=A==x)*nnz(conv2(X,[0 1 0;1 0 1;0 1 0],'same').*~B);
end
end

```

Try it online!

I suspect there are further improvements that can be made.
> 1 votes

# Answer
# PARI/GP, 157 bytes

```
m->matrix(#m~,#m,i,j,p=0*m;a=p[i,j]=m[i,j];while(s=0;p!=q=matrix(#m~,#m,k,l,matrix(#m~,#m,u,v,normlp([u-k,l-v],1)<2&&p[u,v])&&!if(a-b=m[k,l],b||s++)),p=q);s)
```

Attempt This Online!
> 0 votes

# Answer
# Charcoal, 88 bytes

```
ＷＳ⊞υι≔Ｅυ⟦⟧θＦＬυＦＬ§υι«≔§§υικη≔⁰ζＦ№αη«Ｅυ⭆μ⎇⁼ξηψξＪκι¤*ＦＬυＦＬ§υι«Ｊνμ≧⁺∧№ＫＶ*⁼ＫＫ.ζ»⎚»⊞§θιζ»Ｅθ⪫ιω

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings of letters (indicating a group) and `.` and outputs a list of strings of digits. Explanation:

```
ＷＳ⊞υι≔

```

Read the input array.

```
Ｅυ⟦⟧θ

```

Create an empty output array of the same height.

```
ＦＬυＦＬ§υι«

```

Loop over all of the cells in the array.

```
≔§§υικη

```

Get the current cell.

```
≔⁰ζ

```

Assume this cell is empty.

```
 Ｆ№αη«

```

If this cell is a letter, then:

```
Ｅυ⭆μ⎇⁼ξηψξ

```

Write the array to the canvas, but replacing that letter with the null character.

```
Ｊκι¤*

```

Fill the canvas with `*` starting at the current cell.

```
ＦＬυＦＬ§υι«

```

Loop over all of the cells again.

```
Ｊνμ≧⁺∧№ＫＶ*⁼ＫＫ.ζ

```

Keep a running total of any liberties found.

```
»⎚

```

Clear the canvas after counting the liberties ready for the next iteration or the output.

```
»⊞§θιζ

```

Save the result to the output array.

```
»Ｅθ⪫ιω

```

Output the final array of liberties. Note that this format smashes digits together so is only suitable for values up to `9` but the `ω` can be replaced with a separator character such as a space or comma.
> 0 votes

---
Tags: code-golf, game, board-game, go
---


title: Don't break the bridges!

text:
# Question
Title: Don't break the bridges!
## Introduction:

You are a worker, who is in charge of managing a set of bridges, connecting a square grid of "nodes":

```
N - N - N
|   |   |
N - N - N
|   |   |
N - N - N

```

(the grid here is 3 by 3, but they can be larger).

Each of the bridges has a set capacity from `1` to `10`, and each of the bridges has a number of cars over them, also from `1` to `10`.

* If a bridge has a higher capacity than the number of cars on that bridge, then it is considered "safe", and you can cross over it.
* If a bridge's capacity and number of cars going over it are equal, then it is considered "stable". It won't collapse, but you can't cross over it.
* If a bridge has a lower capacity than the number of cars on that bridge, then it is considered "collapsing", and you only have a limited amount of time to fix it.

When a bridge has `n` capacity and `m` cars, with `n` smaller than `m`, the time it takes to collapse is:

```
      m + n
ceil( ----- )
      m - n

```

You must take materials (and therefore reduce the bridge's capacity) from other bridges and arrive to those bridges on time to fix them! To get materials from a bridge, you must cross over it. For example, take this small arrangement:

```
A - B

```

The bridge between `A` and `B` (which we'll call `AB`) has `3` capacity, and let's say you're on `A`, and want to take `1` material. To take the material, simply cross from `A` to `B`.

*Note*: You don't have to cross the bridge multiple times to get multiple materials, you can take as much material as you want from a bridge in one go, as long as it doesn't cause the bridge to start to collapse.

Now, `AB` has `2` capacity, and you have `1` material on you. You may only cross over bridges that are "safe", though (or if you're fixing a bridge, which is explained in the next paragraph).

To fix a bridge, you must go over it, thereby depositing all materials needed to fix the bridge. For example, in the example above, if `AB` had `1` capacity and `2` cars currently on it, and you had `2` material on you, once you cross the bridge you will have `1` material, because that is all that's required to fix the bridge.

You must fully cross a collapsing bridge before the bridge collapses, otherwise it will break. Each crossing of a bridge takes `1` hour, and the time it takes for the bridge to collapse is shown in the formula above. For example:

```
A
|
B
|
C - D

```

In this example, if your starting node was `A`, and `CD` only had a "lifespan" of 2 hours, the bridge would collapse before you can get to it (crossing `AB` takes 1 hour, crossing `BC` takes another hour).

## Task:

Your task is to make a program that calculates, given a list of bridges, which are represented themselves as lists of two elements (first element is capacity, second element is cars on the bridge), whether or not it's possible to fix all of the bridges. The bridges work from top-to-bottom, left-to-right - so an input of

```
[[3 2] [3 2] [2 5] [5 1]]

```

means that the actual grid looks like this:

```
    3
 A --- B
 |  2  |
3|2   2|5
 |  5  |
 C --- D
    1

```

So `AB` has a capacity of `3` and `2` cars, `AC` has a capacity of `3` and `2` cars, `BD` has a capacity of `2` and `5` cars, and `CD` has a capacity of `5` and `1` car.

## Rules / Specs:

* Your program must work for, at least, `10 * 10` grids.
* Your program may accept the input as either a string with any delimiter, or a list of lists (see example I/O).
* Your program must output the same value for true for all true values, and it must output the same value for false for all false values.
* You can either submit a full program or a function.

## Example I/O:

```
[[5 5] [5 5] [1 1] [3 3]] => true
[[2 5] [2 2] [3 3] [1 2]] => false
[[3 2] [3 2] [2 5] [5 1]] => true

NOTE, you can take the input like this as well:
[[3, 2], [3, 2], [2, 5], [5, 1]] (Python arrays)
3,2,3,2,2,5,5,1                  (Comma-separated string)
3 2 3 2 2 5 5 1                  (Space-separated string)

```

This is , so shortest code in bytes wins!

# Answer
> 4 votes
# Python3, 560 bytes:

```
R=range
def V(b,x,y,X,Y):
 try:return[(b[x][y],b[x+X][y+Y])]
 except:return[]
def f(r):
 K,w=0,int(len(r)**.5);b=[[K:=K+1for _ in R(w)]for _ in R(w)];e=dict(zip([l for x in R(w)for y in R(w)for l in V(b,x,y,0,1)+V(b,x,y,1,0)],r));q=[(e,0)]
 while q:
  e,c=q.pop(0);E=e.values()
  if all(a>=b for a,b in E):return 1
  if c<min(-(-((b+a)/(b-a))//1)for a,b in E if a<b):
   for(j,k),(a,b)in e.items():
    if a>b:
     for J,K in e:
      if(j,k)!=(J,K)and{j,k}&{J,K}:
       for s in R(a-b):
        Q=eval(str(e));Q[j,k][0]-=s;Q[J,K][0]+=s;q+=(Q,c+1),
 return 0

```

Try it online!

---
Tags: code-golf, grid, decision-problem, graph-theory
---