title: The TAK function (easy mode)

text:
# Question
Title: The TAK function (easy mode)
The TAK function is defined as follows for integers \\$x\\$, \\$y\\$, \\$z\\$:

$$ t(x, y, z) = \begin{cases} y, & \text{if $x \le y$} \\ t(t(x-1,y,z), t(y-1,z,x), t(z-1,x,y)), & \text{otherwise} \end{cases} $$

It can be proved that it always terminates and evaluates to the simple function below:

$$ t(x, y, z) = \begin{cases} y, & \text{if $x \le y$} \\ z, & \text{if $x \> y$ and $y \le z$} \\ x, & \text{otherwise} \end{cases} $$

Your job is to implement the function. (As per the standard rules, it is OK to implement the simplified version, or anything else that evaluates to the same value for all inputs.)

You may assume that the three input values are nonnegative integers.

Standard rules apply. The shortest code in bytes wins.

For a harder challenge, check out "The TAK function".

## Test cases

```
(x, y, z) -> output

(10, 20, 100) -> 20
(20, 20, 100) -> 20
(20, 10, 100) -> 100
(20, 10, 10) -> 10
(20, 10, 0) -> 20

```

# Answer
> 7 votes
# JavaScript (Node.js), 25 bytes

```
f=(x,y,z)=>x>y?f(y,z,x):y

```

Attempt This Online!

Not shortest but fun

# JavaScript (Node.js), 22 bytes

```
(x,y,z)=>x>y?y>z?x:z:y

```

Attempt This Online!

# Answer
> 6 votes
# Python, 31 bytes

```
lambda x,y,z:x*(x>y>(y:=z))or y

```

Attempt This Online!

# Answer
> 3 votes
# Haskell, 23 bytes

```
(x#y)z|x>y=(y#z)x|1<2=y

```

Try it online!

I see that I4m2 found this approach before I did. Could've saved me the dozen minutes I spent trying to find a non-obvious approach. :P

# Answer
> 2 votes
# Uiua SBCS, 12 bytes

```
⊡◿3+1⊗1≤↻1..

```

Try it!

# Answer
> 2 votes
# Desmos, ~~29~~ 28 bytes

*-1 bytes thanks to @Neil*

```

f(a,b,c)=\{a<=b:b,b>c:a,c\}

```

Literally just the piecewise function given in the challenge description.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Awk, 25 bytes

```
1,$0=$1>$2?$2>$3?$1:$3:$2

```

Try it online!

# Answer
> 2 votes
# , 30 bytes

```
t=\(x,y,z)`if`(x>y,t(y,z,x),y)

```

Attempt This Online!

Port of @l4m2's JavaScript answer

# , 33 bytes

```
\(x,y,z)`if`(x>y,`if`(y>z,x,z),y)

```

Attempt This Online!

Straightforward approach.

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
Rü@2β3Bè

```

Try it online or verify all test cases.

**Explanation:**

```
R         # Reverse the (implicit) input-triplet
 ü        # For each overlapping pair:
  @       #  Do a ≥ check
          # (so we now have a pair [z≥y,y≥x])
   2β     # Convert this pair from a base-2 list to a base-10 integer
     3B   # Convert this base-10 integer to a base-3 integer
       è  # Use that to 0-based modular index into the (implicit) input-triplet
          # (after which the result is output implicitly)

```

| input | `R` | `ü@` |  | `3B` | (0-based modular index) | `è` (output) |
| --- | --- | --- | --- | --- | --- | --- |
| `[10,20,100]` | `[100,20,10]` | `[1,1]` | `3` | `10` | `1` | `20` |
| `[20,20,100]` | `[100,20,20]` | `[1,1]` | `3` | `10` | `1` | `20` |
| `[20,10,100]` | `[100,10,20]` | `[1,0]` | `2` | `2` | `2` | `100` |
| `[20,10,10]` | `[10,10,20]` | `[1,0]` | `2` | `2` | `2` | `10` |
| `[20,10,0]` | `[0,10,20]` | `[0,0]` | `0` | `0` | `0` | `20` |
| `[10,20,0]` | `[0,20,10]` | `[0,1]` | `1` | `1` | `1` | `20` |

# Answer
> 1 votes
# Perl 5 `-Mfeature+signatures`, 35 bytes

```
sub($x,$y,$z){$y<$x?$z<$y?$x:$z:$y}

```

Try it online!

# Answer
> 1 votes
# Google Sheets, 40 bytes

```
=IFS(A1<=A2,A2,(A1>A2)*(A2<=A3),A1,1,A3)

```

# Answer
> 1 votes
# PARI/GP, 27 bytes

```
t(x,y,z)=if(x>y,t(y,z,x),y)

```

Attempt This Online!

A port of @l4m2's Javascript answer.

---

# PARI/GP, 27 bytes

```
t(x,y,z)=if(x<=y,y,y>z,x,z)

```

Attempt This Online!

# Answer
> 1 votes
# Retina 0.8.2, 28 bytes

```
.+
$*
^(1*¶)??(1*)¶\2
$2
\G1

```

Try it online! Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Explanation:

```
.+
$*

```

Convert to unary.

```
^(1*¶)??(1*)¶\2
$2

```

If `x<=y` then delete `x`, otherwise if `y<=z` then delete both `x` and `y`. (The `??` is needed to prefer the `x<=y` test.)

```
\G1

```

Convert the first remaining input to decimal.

# Answer
> 1 votes
# Jelly, 6 bytes

```
>Ɲi0‘ị

```

A monadic Link that accepts a list, `[x, y, z]`, and yields the result of the TAK function.

**Try it online!**

### How?

```
>Ɲi0‘ị - Link: list of comparables, [x, y, z]
 Ɲ     - for neighbouring pairs:
>      -   greater than?         -> [x>y, y>z] == [not(x<=y), not(y<=z)]
  i0   - first 1-indexed index of 0, or 0 if not found
          -> 1 if x<=y
             2 if x>y and y<=z
             0 if x>y and y>z
    ‘  - increment
          -> 2 if x<=y
             3 if x>y and y<=z
             1 if x>y and y>z
     ị - 1-index into {[x, y, z]}
          -> y if x<=y
             z if x>y and y<=z
             x if x>y and y>z

```

# Answer
> 1 votes
# TI-BASIC, 25 bytes

```
Ans(2+(Ans(1)>Ans(2))cos(π(Ans(2)≠min(Ans

```

Takes input in `Ans` as a list.

# Answer
> 0 votes
# JavaScript (Node.js), 28 bytes

```
(x,y,z)=>x<=y?y:x>y&y<=z?z:x

```

Attempt This Online!

Literal translation of the simple version.

# Answer
> 0 votes
# Python, ~~35~~ 32 bytes

-3 bytes thanks to @l4m2

```
lambda x,y,z:[y,[z,x][y>z]][x>y]

```

Attempt This Online!

---

# Python, 36 bytes

Port of l4m2's answer

```
f=lambda x,y,z:f(y,z,x)if x>y else y

```

Attempt This Online!

# Answer
> 0 votes
# Funge-98, 29 bytes

```
"HTRF"4(&&&RROO`!2j@._2P`j$.@

```

Try it online!

# Answer
> 0 votes
# Charcoal, 18 bytes

```
ＮθＮηＮζＩ⎇‹ηθ⎇‹ζηθζη

```

Try it online! Link is to verbose version of code. Explanation: Straightforward approach. For a more interesting approach, my answer to the linked question needs to perform this calculation three times in a loop so it uses array indexing arithmetic.

```
Ｎθ                  First input as a number
  Ｎη                Second input as a number
    Ｎζ              Third input as a number
         η          Second input
        ‹           Is less than
          θ         First input
       ⎇            If true then
             ζ      Third input
            ‹       Is less than
              η     Second input
           ⎇        If true then
               θ    First input
                ζ   Else third input
                 η  Else second input
      Ｉ             Cast to string
                    Implicitly print

```

# Answer
> 0 votes
# C (gcc), 26 bytes

```
f(x,y,z){x=x>y?y>z?x:z:y;}

```

Try it online!

---
Tags: code-golf, math
---


# Question
Title: 3D Hide & Seek Word Puzzle - Seeker edition
Your challenge is to find all occurences of a word in the 3d matrix. There is no restriction on I/O format. In the samples below, the word is presented, then a blank line, then the 2-dimensional layers from top to bottom, and the output, for each line, consists of a coordinate and a direction (x, then y, then z, where + is positive direction, - is negative direction, and 0 is no change). However, you may choose any other format, for instance a 3D Array, list of list of lists, pre-existing values on tape/stack, etc. Similarly, you may output the coordinate after the direction, etc. However, the format must be bijectional (always output `1` is not a valid output format) and consistent.

Sample Input

```
CODEGOLF

N Y R Z O F K G   Y G B V E T P M   O J F K Y O O K   O Z N Q F A R P   M X E T N O I Y   F H C U O F Z A   G V A V O O F B   B V K U O V L F
W Y L W U H H K   Z M Z X D R K Q   G D D A B I D F   P Y G U I D L I   J Y D O M D Q W   F H B Q Q N B B   T A C F J Q L K   H R Y R Y B Z Q
L F C D Z B Z W   L E A J O F F J   Z O X Q G A R C   W N N W Y Z S U   S G E V T A C F   K F E O R O N V   K D G Z N W O P   L I W W J L C U
K L Z Q M A G C   M R Q E F M O I   O K T K T U A U   S E X A Y K C D   N J D V G E S G   X O F P T S F I   H Z B X E X U T   X R Q G V P Q O
B H F C J P Y A   P I Z G R X N A   A W Z H A Z H V   Q X T E T B Z A   Q A V I Z H G D   E H N J L G G W   V K A O Q U S G   N K M M X R G Z
B Q K R Y O R I   O J C Q K C P F   F U D R M U J G   E K B F A A C I   K G P O B M N E   M P M B K X X T   V B V N Z O R P   K N Q N J B M D
M L R C O U C F   A O H U H R E P   M L E T B F R Y   W J S U C Y A N   M X S W E C C X   C U F U V Q U H   J C Z W Y E J S   Z D C U I R F Z
C H D I M M C W   F W G N I I Z U   C X W Q M C O N   Y O W K X E Z J   U G Y U W Q V V   C N B T A T E Z   W C X Z E O W Z   N S C J P V X X

```

Sample Output

```
0 0 7 ++-

```

Sample Input

```
AA

A A
A A

```

Sample Output

```
0 0 0 +00
0 0 0 0+0
0 0 0 ++0
1 0 0 -00
1 0 0 0+0
1 0 0 -+0
0 1 0 +00
0 1 0 0-0
0 1 0 +-0
1 1 0 -00
1 1 0 0-0
1 1 0 --0

```

Sample Input

```
SNY

Y X  N X  S X

```

Sample Output

```
0 0 0 00+

```

Sample Input

```
SNY

Y  N  S

```

Sample Output

```
0 0 0 00+

```

# Answer
# Jelly, 17 bytes

```
œẹⱮŒp_ƝỊjEƊẠƊƇQƑƇ

```

A dyadic Link that accepts a multidimensional* array of characters (the Board) on the left, and a list of characters (the Word) on the right and yields a list of lists of 1-indexed coordinates.

* Of any dimension!

**Try it online!** ("CODEGOLF" will take too long, and "ODE" is there twice, so I used the latter instead.)

### How?

```
œẹⱮŒp_ƝỊjEƊẠƊƇQƑƇ - Main Link: multidimensional array, Board; list, Word
  Ɱ               - map across {C in Word} with:
œẹ                -   get all coordinates of {C} in {Board}
   Œp             - Cartesian product
                     -> all possible coordinate lists spelling {Word}
             Ƈ    - keep if:
            Ɗ     -   last three links as a monad - f(Coordinates):
      Ɲ           -     for neighbouring pairs:
     _            -       subtract
          Ɗ       -     last three links as a monad - f(Deltas=that):
       Ị          -       {Deltas} insignificant? (vectorises) -> is 0 or 1?
         E        -       {Deltas} all equal?
        j         -       {is 0 or 1(Deltas)} join {all Deltas are equal}
           Ạ      -     all?
              QƑƇ - keep if all distinct -> remove any with repeated coordinates

```
> 1 votes

# Answer
# Charcoal, 88 bytes

```
ＵＭη⊞Ｏ⁺ιψ ⊞η ＦＬηＦＬ§ηιＦＬ§§ηικＦ³Ｆ³Ｆ³¿∨⊖μ∨⊖ν⊖ξ¿⬤θ⁼π§§§η⁺ι×ρ⊖μ⁺κ×ρ⊖ν⁺λ×ρ⊖ξ⟦⪫⟦ικλ⭆⟦μνξ⟧§-0+π⟧

```

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

```
ＵＭη⊞Ｏ⁺ιψ ⊞η

```

Add padding bytes in each dimension. (If I was using the newer version of Charcoal on ATO then I would use `ψ` consistently but unfortunately the version of Charcoal on TIO has what I would call a bug when indexing an array containing `ψ` so I use spaces instead.)

```
ＦＬηＦＬ§ηιＦＬ§§ηικ

```

Loop through every possible starting position (including the padding, but that will get filtered out later anyway).

```
Ｆ³Ｆ³Ｆ³¿∨⊖μ∨⊖ν⊖ξ

```

Loop through every possible direction except no direction (fixes the `AA` test case).

```
¿⬤θ⁼π§§§η⁺ι×ρ⊖μ⁺κ×ρ⊖ν⁺λ×ρ⊖ξ

```

If each character of the array starting at that position and working in that direction equals the target string, then...

```
⟦⪫⟦ικλ⭆⟦μνξ⟧§-0+π⟧

```

... output the position and direction in a readable form.
> 0 votes

# Answer
# Python3, 345 bytes

```
from itertools import*
D=[0,1,-1]
E=enumerate
def f(w,b):
 d={}
 for z,Z in E(b):
  for x,X in E(Z):
   for y,v in E(X):d[v]=d.get(v,[])+[(x,y,z)]
 q=[(w[1:],*i,*j,[i])for i in d[w[0]]for j in product(*[D,D,D])if any(j)]
 while q:
  w,x,y,z,X,Y,Z,p=q.pop(0)
  if''==w:yield p;continue
  if(T:=(x+X,y+Y,z+Z))in d[w[0]]:q+=[(w[1:],*T,X,Y,Z,p+[T])]

```

Try it online!
> 0 votes

---
Tags: code-golf, word-search
---


title: Print all colorings of a 3x3 grid

text:
# Question
Title: Print all colorings of a 3x3 grid
You have a 3x3 grid. Each cell can be colored black or white. Display all 512 of these colorings. Fewest bytes wins.

You can display the grids in any formation as long as they are visually separated and the spacing looks regular. You may use ASCII art or images. Any two distinct visible symbols or colors can be used for black and white. Any whitespace is fine as long as the result is visually correct.

**Example output:**

```
...
...
...

...
...
..X

...
...
.X.

...
...
.XX

...
...
X..

...
...
X.X

...
...
XX.

...
...
XXX

...
..X
...

...
..X
..X

...
..X
.X.

...
..X
.XX

...
..X
X..

...
..X
X.X

...
..X
XX.

...
..X
XXX

...
.X.
...

...
.X.
..X

...
.X.
.X.

...
.X.
.XX

...
.X.
X..

...
.X.
X.X

...
.X.
XX.

...
.X.
XXX

...
.XX
...

...
.XX
..X

...
.XX
.X.

...
.XX
.XX

...
.XX
X..

...
.XX
X.X

...
.XX
XX.

...
.XX
XXX

...
X..
...

...
X..
..X

...
X..
.X.

...
X..
.XX

...
X..
X..

...
X..
X.X

...
X..
XX.

...
X..
XXX

...
X.X
...

...
X.X
..X

...
X.X
.X.

...
X.X
.XX

...
X.X
X..

...
X.X
X.X

...
X.X
XX.

...
X.X
XXX

...
XX.
...

...
XX.
..X

...
XX.
.X.

...
XX.
.XX

...
XX.
X..

...
XX.
X.X

...
XX.
XX.

...
XX.
XXX

...
XXX
...

...
XXX
..X

...
XXX
.X.

...
XXX
.XX

...
XXX
X..

...
XXX
X.X

...
XXX
XX.

...
XXX
XXX

..X
...
...

..X
...
..X

..X
...
.X.

..X
...
.XX

..X
...
X..

..X
...
X.X

..X
...
XX.

..X
...
XXX

..X
..X
...

..X
..X
..X

..X
..X
.X.

..X
..X
.XX

..X
..X
X..

..X
..X
X.X

..X
..X
XX.

..X
..X
XXX

..X
.X.
...

..X
.X.
..X

..X
.X.
.X.

..X
.X.
.XX

..X
.X.
X..

..X
.X.
X.X

..X
.X.
XX.

..X
.X.
XXX

..X
.XX
...

..X
.XX
..X

..X
.XX
.X.

..X
.XX
.XX

..X
.XX
X..

..X
.XX
X.X

..X
.XX
XX.

..X
.XX
XXX

..X
X..
...

..X
X..
..X

..X
X..
.X.

..X
X..
.XX

..X
X..
X..

..X
X..
X.X

..X
X..
XX.

..X
X..
XXX

..X
X.X
...

..X
X.X
..X

..X
X.X
.X.

..X
X.X
.XX

..X
X.X
X..

..X
X.X
X.X

..X
X.X
XX.

..X
X.X
XXX

..X
XX.
...

..X
XX.
..X

..X
XX.
.X.

..X
XX.
.XX

..X
XX.
X..

..X
XX.
X.X

..X
XX.
XX.

..X
XX.
XXX

..X
XXX
...

..X
XXX
..X

..X
XXX
.X.

..X
XXX
.XX

..X
XXX
X..

..X
XXX
X.X

..X
XXX
XX.

..X
XXX
XXX

.X.
...
...

.X.
...
..X

.X.
...
.X.

.X.
...
.XX

.X.
...
X..

.X.
...
X.X

.X.
...
XX.

.X.
...
XXX

.X.
..X
...

.X.
..X
..X

.X.
..X
.X.

.X.
..X
.XX

.X.
..X
X..

.X.
..X
X.X

.X.
..X
XX.

.X.
..X
XXX

.X.
.X.
...

.X.
.X.
..X

.X.
.X.
.X.

.X.
.X.
.XX

.X.
.X.
X..

.X.
.X.
X.X

.X.
.X.
XX.

.X.
.X.
XXX

.X.
.XX
...

.X.
.XX
..X

.X.
.XX
.X.

.X.
.XX
.XX

.X.
.XX
X..

.X.
.XX
X.X

.X.
.XX
XX.

.X.
.XX
XXX

.X.
X..
...

.X.
X..
..X

.X.
X..
.X.

.X.
X..
.XX

.X.
X..
X..

.X.
X..
X.X

.X.
X..
XX.

.X.
X..
XXX

.X.
X.X
...

.X.
X.X
..X

.X.
X.X
.X.

.X.
X.X
.XX

.X.
X.X
X..

.X.
X.X
X.X

.X.
X.X
XX.

.X.
X.X
XXX

.X.
XX.
...

.X.
XX.
..X

.X.
XX.
.X.

.X.
XX.
.XX

.X.
XX.
X..

.X.
XX.
X.X

.X.
XX.
XX.

.X.
XX.
XXX

.X.
XXX
...

.X.
XXX
..X

.X.
XXX
.X.

.X.
XXX
.XX

.X.
XXX
X..

.X.
XXX
X.X

.X.
XXX
XX.

.X.
XXX
XXX

.XX
...
...

.XX
...
..X

.XX
...
.X.

.XX
...
.XX

.XX
...
X..

.XX
...
X.X

.XX
...
XX.

.XX
...
XXX

.XX
..X
...

.XX
..X
..X

.XX
..X
.X.

.XX
..X
.XX

.XX
..X
X..

.XX
..X
X.X

.XX
..X
XX.

.XX
..X
XXX

.XX
.X.
...

.XX
.X.
..X

.XX
.X.
.X.

.XX
.X.
.XX

.XX
.X.
X..

.XX
.X.
X.X

.XX
.X.
XX.

.XX
.X.
XXX

.XX
.XX
...

.XX
.XX
..X

.XX
.XX
.X.

.XX
.XX
.XX

.XX
.XX
X..

.XX
.XX
X.X

.XX
.XX
XX.

.XX
.XX
XXX

.XX
X..
...

.XX
X..
..X

.XX
X..
.X.

.XX
X..
.XX

.XX
X..
X..

.XX
X..
X.X

.XX
X..
XX.

.XX
X..
XXX

.XX
X.X
...

.XX
X.X
..X

.XX
X.X
.X.

.XX
X.X
.XX

.XX
X.X
X..

.XX
X.X
X.X

.XX
X.X
XX.

.XX
X.X
XXX

.XX
XX.
...

.XX
XX.
..X

.XX
XX.
.X.

.XX
XX.
.XX

.XX
XX.
X..

.XX
XX.
X.X

.XX
XX.
XX.

.XX
XX.
XXX

.XX
XXX
...

.XX
XXX
..X

.XX
XXX
.X.

.XX
XXX
.XX

.XX
XXX
X..

.XX
XXX
X.X

.XX
XXX
XX.

.XX
XXX
XXX

X..
...
...

X..
...
..X

X..
...
.X.

X..
...
.XX

X..
...
X..

X..
...
X.X

X..
...
XX.

X..
...
XXX

X..
..X
...

X..
..X
..X

X..
..X
.X.

X..
..X
.XX

X..
..X
X..

X..
..X
X.X

X..
..X
XX.

X..
..X
XXX

X..
.X.
...

X..
.X.
..X

X..
.X.
.X.

X..
.X.
.XX

X..
.X.
X..

X..
.X.
X.X

X..
.X.
XX.

X..
.X.
XXX

X..
.XX
...

X..
.XX
..X

X..
.XX
.X.

X..
.XX
.XX

X..
.XX
X..

X..
.XX
X.X

X..
.XX
XX.

X..
.XX
XXX

X..
X..
...

X..
X..
..X

X..
X..
.X.

X..
X..
.XX

X..
X..
X..

X..
X..
X.X

X..
X..
XX.

X..
X..
XXX

X..
X.X
...

X..
X.X
..X

X..
X.X
.X.

X..
X.X
.XX

X..
X.X
X..

X..
X.X
X.X

X..
X.X
XX.

X..
X.X
XXX

X..
XX.
...

X..
XX.
..X

X..
XX.
.X.

X..
XX.
.XX

X..
XX.
X..

X..
XX.
X.X

X..
XX.
XX.

X..
XX.
XXX

X..
XXX
...

X..
XXX
..X

X..
XXX
.X.

X..
XXX
.XX

X..
XXX
X..

X..
XXX
X.X

X..
XXX
XX.

X..
XXX
XXX

X.X
...
...

X.X
...
..X

X.X
...
.X.

X.X
...
.XX

X.X
...
X..

X.X
...
X.X

X.X
...
XX.

X.X
...
XXX

X.X
..X
...

X.X
..X
..X

X.X
..X
.X.

X.X
..X
.XX

X.X
..X
X..

X.X
..X
X.X

X.X
..X
XX.

X.X
..X
XXX

X.X
.X.
...

X.X
.X.
..X

X.X
.X.
.X.

X.X
.X.
.XX

X.X
.X.
X..

X.X
.X.
X.X

X.X
.X.
XX.

X.X
.X.
XXX

X.X
.XX
...

X.X
.XX
..X

X.X
.XX
.X.

X.X
.XX
.XX

X.X
.XX
X..

X.X
.XX
X.X

X.X
.XX
XX.

X.X
.XX
XXX

X.X
X..
...

X.X
X..
..X

X.X
X..
.X.

X.X
X..
.XX

X.X
X..
X..

X.X
X..
X.X

X.X
X..
XX.

X.X
X..
XXX

X.X
X.X
...

X.X
X.X
..X

X.X
X.X
.X.

X.X
X.X
.XX

X.X
X.X
X..

X.X
X.X
X.X

X.X
X.X
XX.

X.X
X.X
XXX

X.X
XX.
...

X.X
XX.
..X

X.X
XX.
.X.

X.X
XX.
.XX

X.X
XX.
X..

X.X
XX.
X.X

X.X
XX.
XX.

X.X
XX.
XXX

X.X
XXX
...

X.X
XXX
..X

X.X
XXX
.X.

X.X
XXX
.XX

X.X
XXX
X..

X.X
XXX
X.X

X.X
XXX
XX.

X.X
XXX
XXX

XX.
...
...

XX.
...
..X

XX.
...
.X.

XX.
...
.XX

XX.
...
X..

XX.
...
X.X

XX.
...
XX.

XX.
...
XXX

XX.
..X
...

XX.
..X
..X

XX.
..X
.X.

XX.
..X
.XX

XX.
..X
X..

XX.
..X
X.X

XX.
..X
XX.

XX.
..X
XXX

XX.
.X.
...

XX.
.X.
..X

XX.
.X.
.X.

XX.
.X.
.XX

XX.
.X.
X..

XX.
.X.
X.X

XX.
.X.
XX.

XX.
.X.
XXX

XX.
.XX
...

XX.
.XX
..X

XX.
.XX
.X.

XX.
.XX
.XX

XX.
.XX
X..

XX.
.XX
X.X

XX.
.XX
XX.

XX.
.XX
XXX

XX.
X..
...

XX.
X..
..X

XX.
X..
.X.

XX.
X..
.XX

XX.
X..
X..

XX.
X..
X.X

XX.
X..
XX.

XX.
X..
XXX

XX.
X.X
...

XX.
X.X
..X

XX.
X.X
.X.

XX.
X.X
.XX

XX.
X.X
X..

XX.
X.X
X.X

XX.
X.X
XX.

XX.
X.X
XXX

XX.
XX.
...

XX.
XX.
..X

XX.
XX.
.X.

XX.
XX.
.XX

XX.
XX.
X..

XX.
XX.
X.X

XX.
XX.
XX.

XX.
XX.
XXX

XX.
XXX
...

XX.
XXX
..X

XX.
XXX
.X.

XX.
XXX
.XX

XX.
XXX
X..

XX.
XXX
X.X

XX.
XXX
XX.

XX.
XXX
XXX

XXX
...
...

XXX
...
..X

XXX
...
.X.

XXX
...
.XX

XXX
...
X..

XXX
...
X.X

XXX
...
XX.

XXX
...
XXX

XXX
..X
...

XXX
..X
..X

XXX
..X
.X.

XXX
..X
.XX

XXX
..X
X..

XXX
..X
X.X

XXX
..X
XX.

XXX
..X
XXX

XXX
.X.
...

XXX
.X.
..X

XXX
.X.
.X.

XXX
.X.
.XX

XXX
.X.
X..

XXX
.X.
X.X

XXX
.X.
XX.

XXX
.X.
XXX

XXX
.XX
...

XXX
.XX
..X

XXX
.XX
.X.

XXX
.XX
.XX

XXX
.XX
X..

XXX
.XX
X.X

XXX
.XX
XX.

XXX
.XX
XXX

XXX
X..
...

XXX
X..
..X

XXX
X..
.X.

XXX
X..
.XX

XXX
X..
X..

XXX
X..
X.X

XXX
X..
XX.

XXX
X..
XXX

XXX
X.X
...

XXX
X.X
..X

XXX
X.X
.X.

XXX
X.X
.XX

XXX
X.X
X..

XXX
X.X
X.X

XXX
X.X
XX.

XXX
X.X
XXX

XXX
XX.
...

XXX
XX.
..X

XXX
XX.
.X.

XXX
XX.
.XX

XXX
XX.
X..

XXX
XX.
X.X

XXX
XX.
XX.

XXX
XX.
XXX

XXX
XXX
...

XXX
XXX
..X

XXX
XXX
.X.

XXX
XXX
.XX

XXX
XXX
X..

XXX
XXX
X.X

XXX
XXX
XX.

XXX
XXX
XXX

```

# Answer
> 16 votes
# K, 11 bytes

```
(3 3#)'!9#2

```

Output example:

```
((0 0 0
  0 0 0
  0 0 0)
 (0 0 0
  0 0 0
  0 0 1)
 (0 0 0
  0 0 0
  0 1 0)
 (0 0 0
  0 0 0
  0 1 1)
…

```

This is K's native prettyprinted representation of a list of matrices, which I think is sufficient for the problem spec. Each matrix is delimited by an enclosing set of parentheses.

And a quick sanity check to demonstrate that 512 matrices are constructed:

```
  #(3 3#)'!9#2
512

```

Very straightforward. Most of the work is in the `!`. First we generate a 9-long vector of 2s using "take" (`9#2`). Then, we make use of the "odometer" monadic form of `!`\- a few examples illustrate its behavior:

```
  !2 2
(0 0
 0 1
 1 0
 1 1)
  !2 3
(0 0
 0 1
 0 2
 1 0
 1 1
 1 2)
  !2 2 2
(0 0 0
 0 0 1
 0 1 0
 0 1 1
 1 0 0
 1 0 1
 1 1 0
 1 1 1)

```

Then simply do a 3x3 reshape (`(3 3#)`) of each (`'`) of the 9-length 0/1 vectors.

# Answer
> 35 votes
# Mathematica, 25 bytes

```
Image/@{0,1}~Tuples~{3,3}

```

Gives an array with all the grids as images, which is also directly displayed on screen:

(Cropped so as not to blow up the post unnecessarily.)

# Answer
> 14 votes
# JavaScript, 77 ~~80~~

Revised after the revision of the OP. Now we have a question, so here is an answer.

Run the snippet in any browser to test.

```
// Test: redefine console to have output inside the snippet

console = { log: function(x) { O.textContent+=x+'\n\n';} }

// Solution: 77 chars (note, distinct outputs to console are automatically separed)

for(i=511;++i<1024;)console.log(i.toString(2).slice(1).match(/.../g).join`
`)
```

```
<pre id=O></pre>
```

Old post: graphic display in a browser, with javascript and canvas. ~300 byte of code (can be made shorter).

Run the snippet below.

```
d=8, // Min block size
C.width=d*64,C.height=d*128,
T=C.getContext('2d')

for(i=0;i<512;i++)
{
  bx=4*(i/32|0)
  by=4*(i%32)
  for(b=1,j=0;j<9;j++,b+=b)
  {
    if(b&i)
      x=j/3|0, y=j%3, T.fillRect((bx+x)*d,(by+y)*d,d,d);
  }
  T.strokeRect(bx*d,by*d,d*3,d*3);
}
```

```
<canvas id=C></canvas>
```

# Answer
> 7 votes
# Matlab, 33

```
reshape(dec2bin(0:511,9)',3,3,[])

```

Was kind of fiddly to get the dimensions correct, but I am very happy with the result!

# Answer
> 6 votes
## POWERSHELL - 65

```
0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"}

```

result

```
000

000

000

000

000

001

000

000

010

000

000

011

```

confirmation

```
(0..511|%{[convert]::ToString($_,2).padleft(9,'0')-split"(.{3})"} | measure -Line).lines/3

512

```

edit inspired by the mathematica answer's display of results-617

```
Add-Type -AssemblyName System.Drawing
$a=new-object System.Drawing.Bitmap 992,496
$g=[Drawing.Graphics]::FromImage($a)
$b=@{};$y=@{};$i=$c=$d=$z=$k=$l=$m=0;
0..511|%{$y[$d++]=[convert]::ToString($_,2).padleft(9,'0')}
while($m-lt480){while($l-lt496){for($z=($m+0);$z-lt($m+32);$z++){
      $y[$z].tochararray()|%{if($_-eq"0"){$b[$i++]=[Drawing.Brushes]::Black}
        else{$b[$i++]=[Drawing.Brushes]::White}
      }
      for($j=($l+0);$j-lt($l+30);$j+=10){
        ($k+0),($k+10),($k+20)|%{$g.FillRectangle($b[$c++],$_,$j,10,10)}
      }$k+=31
    }$k=0;$l+=31;$m+=32
  }
}$a.save("$HOME/3X3_Grid.png")

```

# Answer
> 6 votes
## Python 2, 49 bytes

```
i=2048;exec"print bin(i/4)[i%4*3+3:][:3];i+=1;"*i

```

Split the binary expansion of `i`. The length-10 binary values 512 through 1023 are used, cutting off the initial 1 (and prefix `0b`). These are split into chunks of 3 as windows `[3:6]`, `[6:9]`, `[9:12]`, and `[12:15]`, with the last one blank to make a blank line. Iterating over the four slices is collapsed with the outer loop of counting through 512 numbers with the divmod trick.

# Answer
> 4 votes
# CJam, 12 bytes

```
2,9m*3f/N*N*

```

Test it here.

Uses `0` and `1` as the distinct characters.

## Explanation

```
2,  e# Push [0 1].
9m* e# Generate all 9-tuples of 0s and 1s.
3f/ e# Split each 9-tuple into 3 subarrays of length 3.
N*  e# Join all those grids with newlines.
N*  e# Put newlines between all the length-3 arrays.

```

An alternative (still 12 byte) solution is

```
2,3m*3m*N*N*

```

# Answer
> 4 votes
# Haskell, ~~57~~ 54 bytes

```
r x=sequence[x,x,x]
u=unlines
f=putStr$u$map u$r$r".X"

```

`f` gives the same output as in the challenge description, i.e. it starts with

```
...
...
...

...
...
..X

...
...
.X.

```

Edit: @Mauris found 3 bytes to save. Thanks!

# Answer
> 4 votes
## Ruby, 86 bytes

```
0.upto(511).map{|i|i.to_s(2).rjust(9,'0')}.each{|j|p j[0..2];p j[3..5];p j[6..8];puts}

```

Mine prints with quotes because `p` is shorter than `puts`, but it does still fit the rules.

# Answer
> 3 votes
# C# - 111

```
for(int i=0;i<512;i++)Console.WriteLine(Regex.Replace(Convert.ToString(i,2).PadLeft(9,'0'),"(.{3})","$1\r\n"));

```

Converts every int to its binary representation and splits every 3 chars.

# Answer
> 2 votes
# Python 2, 95 Bytes

Distinct characters are `0` and `1`, each block is separated by `\n\n`.

```
n='\n';print(n+n).join(y[:3]+n+y[3:6]+n+y[-3:]for y in[bin(x)[2:].zfill(9)for x in range(512)])

```

# Answer
> 2 votes
# Python 2, 81

```
import re
for i in range(512):print re.sub('(.{3})','\\1\n',bin(i)[2:].zfill(9))

```

# Answer
> 2 votes
## Ruby, 92 bytes

```
0.upto(511){|i|("%09d"%i.to_s(2)).scan(/.{3}/).map{|j|j.scan(/./)}.map{|j|puts j.join};puts}

```

Counts in `0`s and `1`s, and each block is separated by an empty line (`\n\n`)

# Answer
> 2 votes
# Pyth, 11 bytes

```
V^`T9jbc3Nk

```

**Try it here!**

Thanks @Jakube :)

# Answer
> 2 votes
# Ruby, 68 bytes

Prints the exact same output as the example given in the question

```
puts (0..511).map{|i|("%09b"%i).tr("01",".X").gsub(/.../){$&+$/}}*$/

```

# Answer
> 2 votes
# Python 3, 80 bytes

```
for i in range(512):print("\n".join(format(i,'09b')[j:j+3]for j in(0,3,6)),"\n")

```

I managed to outgolf someone :)

# Answer
> 2 votes
# PHP, 55 bytes

```
for(;$c<512;)echo chunk_split(sprintf("%09b ",$c++),3);

```

uses `0` and `1`. Run with `-r`.

# Answer
> 2 votes
# Python 2, 56 bytes

```
from itertools import*
print set(combinations('X.'*9,9))

```

Try it online!

Returns the 512 configurations as a set object in python. Refer to ungolfed version to make output more readable.

Ungolfed Version to make output more readable:

# Python 2, 121 bytes

```
from itertools import*
for i in set(combinations('X.'*9,9)):
	for j in range(3):print''.join(list(i))[j*3:(j*3)+3]
	print

```

Try it online!

# Answer
> 1 votes
## Swift 2, 92 bytes

Int to binary string in Swift takes up too many chars so I just use two nested loops...

```
var s="";for x in 0..<512{(0..<9).map{s+=($0%3==0 ?"\n":"")+"\(x>>$0&1)"};s+="\n-"};print(s)

```

# Answer
> 1 votes
# C - 97 bytes

```
i;main(j){for(;i++<512;)for(j=0;j++<13;)putchar(j%4&&j<13?i%(1<<j-j/4)>(1<<j-j/4-1)-1?88:46:10);}

```

Basically prints the example output from the original question.

# Answer
> 1 votes
# Python 3, 123 121 109 103 bytes

Here is my old one:

```
import itertools
[print(a+b+c,d+e+f,g+h+i,'\n',sep='\n') for a,b,c,d,e,f,g,h,i in itertools.product(['X','.'],repeat=9)]

```

And here is my new one:

```
import itertools as i
[print(a[:3],a[3:6],a[6:],'\n',sep='\n') for a in i.product(['X','.'],repeat=9)]

```

This prints extra characters but the OP said ASCII art is allowed which implies multiple characters are fine.

# Answer
> 1 votes
# Prolog (SWI), 98 bytes

Output is a list of 3x3 matrices containing the elements 0 and 1.

```
r([]).
r([H|T]):-between(0,1,H),r(T).
p(Y):-Z=[[_,_,_],[_,_,_],[_,_,_]],findall(Z,maplist(r,Z),Y).

```

Online interpreter

I feel like the matrix generation could be shorter.
It should be possible to fit the between in a forall or something similar, but I can't figure out how.

Golfing tips appreciated.

# Answer
> 1 votes
# Perl, ~~56~~ 55 bytes

```
print$_/9&1<<$_%9?1:0,$/x(!(++$_%3)+!($_%9))for+0..4607

```

Output:

```
000
000
000

100
000
000
...

```

# Answer
> 1 votes
# Jelly, 17 bytes

```
512+ḶBḊ€s€3Y€j“¶¶

```

Try it online!

Uses `01`. Because of a bug in , I had to use `“¶¶` instead of `⁾¶¶`, because otherwise, instead of two newlines, two pilcrows would have showed up in the output. As you can see, though, that didn't cost me any bytes at all.

K beats this, so this must be further golfed down.

# Answer
> 1 votes
# 05AB1E, 15 bytes

```
žAFNžA+b¦3ô»,¶?

```

Try it online!

# Answer
> 1 votes
# **Python 3, 74 bytes**

```
i=512;b="\n"
while i:i-=1;a=format(i,'09b');print(a[:3]+b+a[3:6]+b+a[6:],b)

```

Just a little shorter than Destructible Lemon's answer

# Answer
> 1 votes
## Perl 5, 32 bytes

```
$_=("{.,#}"x3 .$/)x3;say<"$_\n">

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
T3ã¶«3ãJ»

```

Uses the digits `[1,0]`. The `T` could be replaced with , , or  to use the digits `[2,6]`, `[9,5]`, or `[3,6]` respectively.

Try it online.

Outputting as an unformatted list could have been **5 bytes**: `T3ã3ã`.

**Explanation:**

```
T          # Push 10
 3ã        # Take the cartesian power of 3 with its digits:
           #  ["111","110","101",...,"000"]
   ¶«      # Append a newline to each triplet
           #  ["111\n","110\n","101\n",...,"000\n"]
     3ã    # Take the cartesian power of 3 with this list of strings:
           #  [["111\n","111\n","111\n"],["111\n","111\n","110\n"],...,["000\n","000\n","000\n"]]
       J   # Join each inner list together
           #  ["111\n111\n111\n","111\n111\n110\n",...,"000\n000\n000\n"]
        »  # And join that list by newlines
           #  "111\n111\n111\n\n111\n111\n110\n\n...\n000\n000\n000\n"
           # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Ruby, 42 bytes

```
512.times{puts ("%09b"%_1).scan(/.../),$/}

```

Attempt This Online!

# Answer
> 1 votes
# Vyxal 3 `s`, 12 8 bytes

```
₀2(3ẋ“¶+

```

Try it Online! port of the 05ab1e answer

# Answer
> 1 votes
# Uiua, 12 bytes

```
≡(↯3_3)⋯⇡512

```

Outputs an array of 512 3x3 bit matrices. Makes clever use of the `bits ⋯` primitive, which converts all numbers in an array to lists of bits.

With `&gifs`, you can make a very tiny GIF cycling every grid.

Pad, GIF version

# Answer
> 1 votes
# Vyxal `Hj`, 62 bitsv2, 7.75 bytes

```
U2(3ÞẊṅ¶+

```

```
U2(3ÞẊṅ¶+
# #H flag sets stack to 100
U          # uniquify the digits, getting a list of [1,0]. This didn't work with the builtin for 10 when I tried it
 2(        # iterate twice
   3ÞẊ     # cartesian power of 3
      ṅ¶+  # joined on nothing with a newline appended
# j flag joins top of stack on newlines
# this leads to the double newline separator

```

Created with the help of Luminespire.

Try it Online!

Bitstring:

```
01100100111011000111001100111101010001110000111111010101000100

```

Port of Kevin's 05ab1e answer, with different separators.

# Answer
> 0 votes
# Perl, 52 bytes

```
printf+("%03b
"x3).$/,$_&7,$_/8&7,$_>>6&7 for 0..511

```

or 54 bytes:

```
print map$_.$/,sprintf('%09b',$_)=~/.../g,''for 0..511

```

or Perl 5.14+, 48 bytes:

```
say sprintf('%09b',$_)=~s/.../$&\n/gr for 0..511

```

# Answer
> 0 votes
# , 27 bytes

```
echo@<"2'.X'{~_3]\"1#:i.512

```

Try it online!

# Answer
> 0 votes
# Tcl, 72 bytes

```
time {puts [regsub -all (...) [format %09b [expr [incr i]-1]] \&\n]} 512

```

Try it online!

# Answer
> 0 votes
# Japt, ~~16~~ 15 bytes

```
#f4o8³_¤Åò3 ·+R

```

Try it online!

# Answer
> 0 votes
# Python 2, 114 bytes

```
from itertools import *
for i in product(".X",repeat=9):
    i="".join(i);print i[0:3]+"\n"+i[3:6]+"\n"+i[6:]+"\n"

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 72 bytes

```
h=console.log;f=u=>h(u/4&1,u/2&1,u&1)|u/8;for(i=0;i<512;h``)f(f(f(i++)))

```

Try it online!

# JavaScript (Node.js), 64 bytes

```
for(i=0;i<512;f(f(f(i++))))f=u=>console.log(u/4&1,u/2&1,u&1)|u/8

```

Try it online!

# JavaScript (Node.js), 75 bytes

```
for(i=511;++i<1024;f(f(f(i))))f=u=>console.log(u.toString(2).slice(-3))|u/8

```

Try it online!

# Answer
> 0 votes
# Perl 5, 48 bytes

```
say((sprintf"%09b",$_)=~s%...%$&$/%gr)for 0..511

```

Try it online!

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


title: Modular Equivalence

text:
# Question
Title: Modular Equivalence
Given two numbers \\$x,y \> 2, x≠y \\$ output all integers \\$m\\$ such that $$ x + y \equiv x \cdot y \pmod m $$ $$ x \cdot y \> m \> 2 $$

## Input

Two integers

## Output

A list of integers

## Test cases

```
3, 4 -> 5
5, 8 -> 3, 9, 27
29, 9 -> 223
26, 4 -> 37, 74
13, 11 -> 7, 17, 119
6258, 571 -> 463, 7703, 3566489

```

# Answer
> 9 votes
# 05AB1E, ~~8~~ 7 bytes

```
<P<Ñʒ2›

```

Attempt This Online! or try all testcases.

-1 thanks to Kevin Cruijssen

Lists the divisors of \\$xy-x-y\\$ greater than \\$2\\$.

# Answer
> 5 votes
# MathGolf, 8 bytes

```
(ε*(─2╒-

```

Try it online.

**Explanation:**

```
(        # Decrease both values in the (implicit) input-pair: [x-1,y-1]
 ε*      # Multiply them together: (x-1)*(y-1)
   (     # Decrease that by 1 as well: (x-1)*(y-1)-1
    ─    # Get all divisors
     2╒  # Push [1,2]
       - # Remove those values from the divisors-list
         # (after which the entire stack is output implicitly as result)

```

# Answer
> 5 votes
# Thunno 2, 7 bytes

```
×__Fæ2>

```

Attempt This Online!

Based on Command Master’s idea, implemented a bit differently

```
×        # Multiply.          X * Y
 _       # Swapped subtract.  X * Y - X
  _      # Swapped subtract.  X * Y - X - Y
   F     # Factors.
    æ    # Filter by:
     2>  #   Greater than 2?

```

I chose Thunno 2 because of that swapped subtraction operator. It's the only stack golflang which has swapped versions of arithmetic operations, as far as I know.

# Answer
> 4 votes
# Raku (Perl 6) (rakudo), 41 bytes

```
{[3..($^x*$^y)].grep: 0==($x+$y-$x*$y)%*}

```

Attempt This Online!

# Answer
> 3 votes
# Python, 52 bytes

```
lambda x,y:[i for i in range(3,x*y)if(x+y)%i==x*y%i]

```

Attempt This Online!

# Answer
> 3 votes
# APL (Dyalog APL), ~~22~~ ~~17~~ 16 bytes

-5 bytes thanks to @ovs
-1 bytes thanks to @att

```
(2↓2∪∘⍸0=⍳|⊢)×-+

```

Attempt This Online!

```
(2↓2∪∘⍸0=⍳|⊢)×-+
(2↓2∪∘⍸0=⍳|⊢)     ⍝ monadic function to get factors greater than 2:
           ⊢      ⍝   arg
          |       ⍝       mod
         ⍳        ⍝           each number in range [1;arg]
       0=         ⍝   boolean vector, marking where result is 0
      ⍸           ⍝   get indices of 1s
   2∪             ⍝   prepend 2 if not in array
 2↓               ⍝   drop first two elements (i.e. 1 and 2)
             ×-+  ⍝ pass (⍺ × ⍵) - (⍺ + ⍵) to the function

```

Created with the help of Luminespire.

# Answer
> 3 votes
# Google Sheets, 58 bytes

```
=let(p,A1*B1,s,sequence(1,p,3),filter(s,0=mod(p-A1-B1,s)))

```

Put \\$x\\$ in cell `A1`, \\$y\\$ in cell `B1` and the formula in cell `C1`.

# Answer
> 3 votes
# Nekomata, 8 bytes

```
ᵋ*+-Ď~2>

```

Attempt This Online!

```
ᵋ*+-Ď~2>
ᵋ*          x * y
  +         x + y
   -        minus
    Ď       divisors
     ~      choose an element from the list
      2>    check if it is greater than 2

```

# Answer
> 3 votes
# C (gcc), 56 bytes

```
i;f(x,y){for(i=x*y;--i>2;)(x*y-x-y)%i?:printf("%d ",i);}

```

Try it online!

# Answer
> 2 votes
# JavaScript (V8), 46 bytes

```
x=>y=>{for(m=x*y,q=m-x-y;--m>2;)q%m||print(m)}

```

Try it online!

---

# JavaScript (ES6), 52 bytes

```
(x,m=2)=>g=y=>++m<x*y?((x*y-x-y)%m?"":m+" ")+g(y):""

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~38~~ 35 bytes

*-3 bytes thanks to AZTECCO.*

```
x#y=[m|m<-[3..x*y],1>mod(x*y-x-y)m]

```

Try it online!

# Answer
> 2 votes
# Go, 80 bytes

```
func(x,y int)(M[]int){for m:=3;m<x*y;m++{if(x*y-x-y)%m<1{M=append(M,m)}}
return}

```

Attempt This Online!

Uses the factors of \\$xy-x-y \gt 2\\$ method.

# Go, 81 bytes

```
func(x,y int)(M[]int){for m:=3;m<x*y;m++{if(x+y)%m==x*y%m{M=append(M,m)}}
return}

```

Attempt This Online!

Formula as verbatim, \\$xy \equiv x+y \pmod m\\$.

# Answer
> 2 votes
# Charcoal, 19 bytes

```
Ｆ²⊞υＮＩΦ…³Πυ¬﹪⁻ΠυΣυι

```

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

```
Ｆ²⊞υＮ

```

Input `x` and `y` and push them to the predefined empty list.

```
ＩΦ…³Πυ¬﹪⁻ΠυΣυι

```

Output all numbers between `3` and the product of the list that are factors of the difference between the product and the sum.

21 bytes for a faster version that can handle the last test case in a more reasonable amount of time:

```
Ｆ²⊞υＮＩ⁺³⌕Ａ﹪⁻ΠυΣυ…³Πυ⁰

```

Try it online! Link is to verbose version of code. Explanation: Vectorises the remainder check and then finds the positions of the zero remainders.

# Answer
> 2 votes
# , 32 bytes

```
\(x,y,a=x*y-x-y)which(!a%%3:a)+2

```

Attempt This Online!

Port of Command Master's 05AB1E answer.

# , 35 bytes

```
\(x,y,M=3:(p=x*y))M[p%%M==(x+y)%%M]

```

Attempt This Online!

Straightforward approach.

# Answer
> 2 votes
# Uiua SBCS, ~~19~~ 15 bytes

```
▽=⊃∩◿∘,:↘3⇡.⊃×+

```

Try it!

-4 bytes thanks to Tbw

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

```
Divisors[##-##]/. 1|2->Set@$&

```

Try it online!

Input `[x, y]`. `##-##` is not zero - it computes the sum minus the product of arguments.

# Answer
> 2 votes
# Jelly, 8 bytes

```
’P’ÆD>Ƈ2

```

Try it online!

Port of Command Master’s 05AB1E answer.

-1 byte and a bugfix thanks to @Bubbler

## Explanation:

```
’P’ÆD>Ƈ2
’         # Decrement both values in the list: [x - 1, y - 1]
 P        # Product of the list: (x - 1) * (y - 1)
  ’       # Decrement again: ((x - 1) * (y - 1)) - 1
   ÆD     # Get the divisors
      Ƈ   # Keep items that satisfy the condition below
     > 2  # Greater than 2

```

Created with the help of Luminespire.

# Answer
> 2 votes
# TI-BASIC, 25 bytes

```
For(M,3,prod(Ans)-1
If not(fPart(M⁻¹min(ΔList(Ans
Disp M
End

```

Takes input in `Ans` as a list of two integers. Add a `)` to the end of the first line to make it faster.

# Answer
> 1 votes
# Retina 0.8.2, 50 bytes

```
.+
$*
1(?=1+¶1(1+))
$1
M!&`(111+)\b(?<=^11\1+)
%`1

```

Try it online! Link is to test suite for faster test cases that splits input on non-digits and spaces the outputs apart. Explanation:

```
.+
$*

```

Convert to unary.

```
1(?=1+¶1(1+))
$1

```

Calculate `1+(x-1)(y-1)`, as that's golfier than trying to subtract `x` or `y` afterwards.

```
M!&`(111+)\b(?<=^11\1+)

```

Subtract `2` and find all factors that are greater than `2`.

```
%`1

```

Convert to decimal.

# Answer
> 1 votes
# PowerShell Core, 45 bytes

```
param($a,$b)3..($p=$a*$b)|?{!(($a+$b-$p)%$_)}

```

Try it online!

Saved two bytes using rajashekar's method, upvote their answer!

---
Tags: code-golf, math, number-theory
---


title: Can even numbers become prime?

text:
# Question
Title: Can even numbers become prime?
## The Sequence

Everyone knows the only even prime number is `2`. Ho-hum. But, there are certain even numbers `n` where, when concatenated with `n-1`, they *become* a prime number.

For starters, `1` isn't in the list, because `10` isn't prime. Similarly with `2` (`21`), and `3` (`32`). However, `4` works because `43` is prime, so it's the first number in the sequence `a(1) = 4`. The next number that works (neither `6` (`65`) nor `8` (`87`) work) is `10`, because `109` is prime, so `a(2) = 10`. Then we skip a bunch more until `22`, because `2221` is prime, so `a(3) = 22`. And so on.

Obviously all terms in this sequence are even, because any odd number `n` when concatenated with `n-1` becomes even (like `3` turns into `32`), which will never be prime.

This is sequence A054211 on OEIS.

## The Challenge

Given an input number `n` that fits somewhere into this sequence (i.e., `n` concatenated with `n-1` is prime), output its position in this sequence. You can choose either 0- or 1-indexed, but please state which in your submission.

## Rules

* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given in any convenient format.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Examples

The below examples are 1-indexed.

```
n = 4
1

n = 100
11

n = 420
51

```

# Answer
> 11 votes
# Jelly,  ~~8~~  7 bytes

```
ḊżṖVÆPS

```

A monadic link taking a sequence member and returning its index in the sequence.

**Try it online!**

### How?

```
ḊżṖVÆPS - Link: number, n
Ḋ       - dequeue (implicit range) = [ 2   , 3   , 4   ,... ,              n         ]
  Ṗ     - pop (implicit range)     = [   1 ,   2 ,   3 ,... ,                  n-1   ]
 ż      - zip                      = [[2,1],[3,2],[4,3],... ,             [n , n-1]  ]
   V    - evaluate as Jelly code   = [ 21  , 32  , 43  ,... ,         int("n"+"n-1") ]
    ÆP  - is prime? (vectorises)   = [  0  ,  0  ,  1  ,... , isPrime(int("n"+"n-1"))]
      S - sum

```

# Answer
> 8 votes
# Haskell, ~~80~~ ~~75~~ 70 bytes

*5 bytes save thanks to Laikoni*

```
p x=all((>0).mod x)[2..x-1]
g n=sum[1|x<-[4..n],p$read$show=<<[x,x-1]]

```

Try it online!

# Answer
> 6 votes
# Jelly, ~~12, 10~~, 8 bytes

```
;’VÆPµ€S

```

Try it online!

1-2 bytes saved thanks to @nmjmcman101, and 2 bytes saved thanks to @Dennis!

Explanation:

```
     µ€   # For N in range(input()):
;         #   Concatenate N with...
 ’        #   N-1
  V       #   And convert that back into an integer
   ÆP     #   Is this number prime?
       S  # Sum that list

```

# Answer
> 5 votes
# 05AB1E, ~~9~~ ~~8~~ 7 bytes

### Code

```
ƒNN<«pO

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
ƒ          # For N in [0 .. input]..
 NN<«      #   Push n and n-1 concatenated
     p     #   Check for primality
      O    #   Sum the entire stack (which is the number of successes)

```

# Answer
> 5 votes
# Japt, ~~15~~ ~~14~~ ~~12~~ ~~11~~ ~~9~~ 8 bytes

1-indexed.

```
ÇsiZÄÃèj

```

Try it

```
Ç            :Map each Z in the range [0,input)
 s           :  Convert to string
  i          :    Prepend
   ZÄ        :    Z+1
     Ã       :End map
      è      :Count
       j     :  Primes

```

# Answer
> 5 votes
# Husk, ~~13~~ ~~11~~ 10 bytes

`1`-indexed solution:

```
#ȯṗdS¤+d←ḣ

```

Try it online!

### Ungolfed/Explanation

```
         ḣ -- in the range [1..N]
#          -- count the number where the following predicate is true
        ←  --   decrement number,
    S  d   --   create lists of digits of number and decremented
     ¤+    --   concatenate,
   d       --   interpret it as number and
 ȯṗ        --   check if it's a prime number

```

Thanks @Zgarb for `-3` bytes!

# Answer
> 4 votes
# Python 2, 87 bytes

*-2 bytes thanks to @officialaimm*. 1-indexed.

```
lambda n:sum(all(z%v for v in range(2,z))for i in range(4,n+1)for z in[int(`i`+`i-1`)])

```

**Test Suite.**

# Answer
> 4 votes
# Pyth, 12 bytes

```
smP_s+`d`tdS

```

**Try it online! or Verify all Test Cases.**

---

# How?

```
smP_s+`d`tdSQ  -> Full Program. Takes input from Standard Input. Q means evaluated input
                  and is implicit at the end.

 m         SQ  -> Map over the Inclusive Range: [1...Q], with the current value d.
    s+`d`td    -> Concatenate: d, the current item and: td, the current item decremented.
                  Convert to int.
  P_           -> Prime?
s              -> Sum, counts the occurrences of True.

```

# Answer
> 3 votes
# Röda, 73 bytes

```
{seq 3,_|slide 2|parseInteger`$_2$_1`|{|i|[1]if seq 2,i-1|[i%_!=0]}_|sum}

```

Try it online!

1-indexed. It uses the stream to do input and output.

Explanation:

```
{
seq 3,_| /* Create a stream of numbers from 3 to input */
slide 2| /* Duplicate every number except the first and the last
            to create (n-1,n) pairs */
parseInteger`$_2$_1`| /* Concatenate n and n-1 and convert to integer */
{|i| /* For every i in the stream: */
    [1]if seq 2,i-1|[i%_!=0] /* Push 1 if i is a prime
                                (not divisible by smaller numbers) */
}_|
sum /* Return the sum of numbers in the stream */
}

```

# Answer
> 2 votes
# Pyth, 14 bytes

```
lfP_Tms+`d`tdS

```

Try it online!

**Explanation**

```
              Q    # Implicit input
             S     # 1-indexed range
     m             # For d in range [1, Q]...
      s+`d`td      # Concatenate d and d - 1
 fP_T              # Filter on primes
l                  # Return the length of the list

```

# Answer
> 2 votes
# C, ~~99~~ 94 bytes

1 indexed. It pains me to write primality tests that are so computationally wasteful, but bytes are bytes after all.

If we allow some really brittle stuff, compiling on my machine without optimizations with GCC 7.1.1 the following 94 bytes works (thanks @Conor O'Brien)

```
i,c,m,k;f(n){c=i=1;for(;++i<n;c+=m==k){for(k=m=1;m*=10,m<i;);for(m=i*m+i-1;++k<m&&m%k;);}n=c;}

```

otherwise these much more robust 99 bytes does the job

```
i,c,m,k;f(n){c=i=1;for(;++i<n;c+=m==k){for(k=m=1;m*=10,m<i;);for(m=i*m+i-1;++k<m&&m%k;);}return c;}

```

---

Full program, a bit more readable:

```
i,c,m,k;
f(n){
    c=i=1;
    for(;++i<n;c+=m==k){
        for(k=m=1;m*=10,m<i;);
        for(m=i*m+i-1;++k<m&&m%k;);
    }
    return c;
}

int main(int argc, char *argv[])
{
    printf("%d\n", f(atoi(argv[1])));
    return 0;
}

```

# Answer
> 2 votes
# Perl 6, 45 bytes

```
{first :k,$_,grep {is-prime $_~.pred},1..∞}

```

Try it online!

The `grep` produces the sequence of qualifying numbers, then we look for the key (`:k`) (ie, the index) of the `first` number in the list that equals the input parameter `$_`.

# Answer
> 2 votes
## JavaScript (ES6),  ~~49 48~~  47 bytes

1-indexed. Limited by the call stack size of your engine.

```
f=n=>n&&f(n-2)+(p=n=>n%--x?p(n):x<2)(x=n+[--n])

```

Try it online!

# Answer
> 2 votes
# Tidy, 33 bytes

```
index({n:prime(n.n-1|int)}from N)

```

Try it online!

## Explanation

The basic idea is to create a sequence of the valid numbers then return a curried index function.

```
index({n:prime(n.n-1|int)}from N)
      {n:                }from       select all numbers `n` from...
                               N     the set of natural numbers, such that:
               n.n-1                     `n` concatenated with `n-1`
                    |int                 ...converted to an integer
         prime(         )                ...is prime
index(                          )    function that returns index of input in that sequence

```

# Answer
> 1 votes
# Mathematica, 77 bytes

```
Position[Select[Range@#,PrimeQ@FromDigits[Join@@IntegerDigits/@{#,#-1}]&],#]&

```

# Answer
> 1 votes
# Ruby, 42+9 = 51 bytes

Uses the `-rprime -n` flags. 1-indexed.

Works by counting all numbers equal to or below the input that fulfill the condition (or more technically, all numbers that fulfill the `n-1` condition). Since the input is guaranteed to be in the sequence, there's no risk of error from a random input like `7` that doesn't "become prime".

```
p (?3..$_).count{|i|eval(i.next+i).prime?}

```

Try it online!

# Answer
> 1 votes
# Ruby, 62 bytes

```
->g{(1..g).count{|r|(2...x=eval([r,r-1]*'')).none?{|w|x%w<1}}}

```

Try it online!

1-indexed

# Answer
> 1 votes
# Vyxal 3 `L`, 6 bytes

```
Ωv&“⌊Ṅ

```

Try it Online!

1-indexed

```
Ωv&“⌊Ṅ
Ω       # filter from the range [0... input]
 v&“⌊   # concatenate n+1 and convert to integer
     Ṅ  # prime?
# L flag gets the length of the top of the stack

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Vyxal, 6 bytes

```
'‹Jæ;L

```

Try it Online!

```
     L # Number of values
'   ;  # Between (implicit) 1 and n
 ‹J    # Where n ++ (n-1)
   æ   # Is prime

```

# Answer
> 0 votes
# QBIC, 25 bytes

```
[:|p=p-µa*z^_l!a$|+a-1}?p

```

## Explanation

```
[:|     FOR a = 1 to <n>
p=p-    Decrement p (the counter) by
µ       -1 if the following is prime, or 0 if not
        For the concatenating, we multiply 'a' by 10^LENGTH(a), then add a-1$┘p
        Example 8, len(8) = 1, 8*10^1 = 80, add 8-1=7, isPrime(87) = 0
a*z^_l!a$|+a-1
}       Close the FOR loop - this also terminates the prime-test
?p      Print p, the 0-based index in the sequence.

```

This uses some pretty involved math-thing with a cast-to-string slapped on for good measure. Making a version hat does solely string-based concatenation is one byte longer:

```
[:|A=!a$+!a-1$┘p=p-µ!A!}?p

```

# Answer
> 0 votes
# PHP, 203 bytes

```
<?php $n=($a=$argv[1]).($a-1);$p=[2];$r=0;for($b=2;$b<=$n;$b++){$x=0;if(!in_array($b,$p)){foreach($p as $v)if(!($x=$b%$v))break;if($x)$p[]=$b;}}for($b=1;$b<=$a;$b++)if(in_array($b.($b-1),$p))$r++;die $r;

```

Try it online!

Uses a 1-based index for output. TIO link has the readable version of the code.

# Answer
> 0 votes
## Python 2**, 85 bytes**

1-indexed

```
lambda n:sum(all(z%v for v in range(2,z))for i in range(3,n)for z in[int(`i+1`+`i`)])

```

Test

Improvement to Mr. Xcoder's answer

# Answer
> 0 votes
# Java 8, 108 bytes

```
n->{for(long r=0,q=1,z,i;;){for(z=new Long(q+""+~-q++),i=2;i<z;z=z%i++<1?0:z);if(z>1)r++;if(q==n)return r;}}

```

0-indexed

**Explanation:**

Try it online.

```
n->{                             // Method with integer parameter and long return-type
  for(long r=0,                  //  Result-long, starting at 0
      q=1,                       //  Loop integer, starting at 1
      z,i;                       //  Temp integers
      ;){                        //  Loop indefinitely
    for(z=new Long(q+""+~-q++),  //   Set z to `q` concatted with `q-1`
        i=2;i<z;z=z%i++<1?0:z);  //   Determine if `z` is a prime,
      if(z>1)                    //   and if it indeed is:
        r++;                     //    Increase the result-long by 1
      if(q==n)                   //   If `q` is now equal to the input integer
        return r;}}              //    Return the result

```

# Answer
> 0 votes
# Stax, 10 bytes

1- Indexed

```
Äm▬á┌╕|°φ♦

```

Run and debug it **Explanation**

```
Rxr\{$e|pm|+         #Full program, unpacked, implicit input  (Example (4))
R                    #Create [1 to input] range  (ex [1,2,3,4] )
 x                   #Copy value from x register (ex (4) )
  r                  #Create [0 to input-1] range (ex [0,1,2,3)
   \                 #Create array pair using the range arrays (ex [[1,0],[2,1],[3,2],[4,3]])
    {    m           #Map block
     $e|p            #To string, eval string (toNum), isPrime (ex [1,0] => "10" => 10 => 0)
          |+         #Sum the array to calculate number of truths (ex [0,0,0,1] => 1)

```

---
Tags: code-golf, sequence, arithmetic, primes
---


title: Targeted duplicate removal

text:
# Question
Title: Targeted duplicate removal
## The task

In this challenge, you are given a number and a list. Your task is to remove from the list all occurrences of the given number except the first (leftmost) one, and output the resulting list. The other elements of the list should be left intact.

* The number will be a positive integer below 1000, and the list will only contain positive integers below 1000.
* The list is not guaranteed to contain any occurrences of the given number. It may even be empty. In these cases you should output the list as-is.
* Input and output formats are flexible within reason. You can output by modifying the list in place.
* The lowest byte count wins.

## Test cases

```
5 [] -> []
5 [5] -> [5]
5 [5,5] -> [5]
10 [5,5] -> [5,5]
10 [5,5,10,10,5,5,10,10] -> [5,5,10,5,5]
2 [1,2,3,1,2,3,1,2,3] -> [1,2,3,1,3,1,3]
7 [9,8,7,6,5] -> [9,8,7,6,5]
7 [7,7,7,7,7,7,7,3,7,7,7,7,7,7,3,7,1,7,3] -> [7,3,3,1,3]
432 [432,567,100,432,100] -> [432,567,100,100]

```

# Answer
# Husk, ~~5~~ 4 bytes

```
üoEė

```

Try it online!

* Saved 1 byte thanks to Razetime
* Saved 2 bytes thanks to Jo King

Thanks to Razetime for suggesting `ü` and Jo King for letting me know I could leave the superscript arguments out, saving me 2 bytes. It removes duplicates with a custom predicate that makes sure both arguments are equal to the number to be removed.

Explanation:

```
üoEė
ü     Remove duplicates by binary function (implicit second argument)
 o    Compose 2 functions
   ė  Make a list of 3 elements (first element is implicitly added)
  E   Are they all equal?

```
> 10 votes

# Answer
# , 30 bytes

```
function(l,d)unique(l,l[l!=d])

```

Try it online!

`unique()` has the signature `unique(x,incomparables = FALSE,...)`; this sets `incomparables` to the elements that aren't equal to `d`, so only `d` is uniquified.
> 9 votes

# Answer
# Python 2, 50 bytes

```
l,n=input()
for x in l:
 if~n-x:print x;n^=-(x==n)

```

Try it online!

Prints output one entry per line.

The idea is to store whether we have already encountered the entry-to-remove `n` in the sign of `n` rather than a separate Boolean variable. When we see a list entry that equals `n`, we negate `n`. To decide whether to print the current entry `x`, we check if it equals `-n`, which checks that it equals the original `n` and that we've already negated `n` due to an earlier match. Note that since `n` and list entries are positive, there's no way to get `x==-n` before `n` is negated.

Well, actually, instead of negating `n`, it's shorter to bit-complement it to `~n`, which is `-n-1`. To do the conditional complementing, we note that we can convert `[x,~x][b]` to `x^-b` (as in this tip), using that bitwise xor `^` has `x^0==x` and `x^-1==~x`. So, we do `n^=-(x==n)`.
> 8 votes

# Answer
# JavaScript (ES6),  ~~32~~  30 bytes

Expects `(x)(list)`.

```
x=>a=>a.filter(v=>v^x||a[a=0])

```

Try it online!

### How?

All values `v` that are not equal to `x` are preserved thanks to `v^x`. The first value that is equal to `x` is kept as well because `a[0]` is guaranteed to be a positive integer (except if `a` is empty, but then we don't enter the `.filter()` loop to begin with). For the next values that are equal to `x`, we have `a = 0` and `a[0] === undefined`, so they are rejected. This test doesn't throw an error because Numbers are Objects, so it's legal to access the (non-existent) property `'0'` of `0`.
> 7 votes

# Answer
# Haskell, 43 bytes

```
a%(b:c)|a==b=b:filter(/=a)c|1<2=b:a%c
_%x=x

```

Try it online!

Ungolfed:

```
dedupl v (x:xs)
  | x == v = x : filter (/= v) xs
  | otherwise = x : dedupl v xs
dedupl _ [] = []

```

---

# Haskell, 40 bytes

This version takes a (negative) predicate for input instead.

```
f%(b:c)|f b=b:f%c|1<2=b:filter f c
_%x=x

```

Try it online!
> 6 votes

# Answer
# APL (Dyalog Unicode), ~~18~~ ~~15~~ 10 bytes

Thanks to Adám for -8 bytes!!!

```
∊⊢⊆⍨≠∨<\⍤=

```

Try it online!

Example inputs: left argument `3`, right argument `1 2 3 4 3 4`.

`=` does element-wise not-equal comparison. `=> 0 0 1 0 1 0`
`<\` Scans with less-than. This keeps just the first `1`, all other places are `0`. `=> 0 0 1 0 0 0`
`≠∨` does element-wise *OR* with the  mask. `=> 1 1 1 1 0 1`.
`⊢⊆` partitions the input based on the vector, including positions with positive integers. `=> (1 2 3 4) (4)`  flattens the nested array. `=> 1 2 3 4 4`
> 5 votes

# Answer
# Jelly,  ~~6~~  5 bytes

-1 thanks to Sisyphus's suggestion to use  in place of `W€`

```
Ẇi¦⁹ḟ

```

A full program accepting the list and the value which prints the Jelly representation of a list with all but the first occurrence of the value removed (empty lists print nothing, lists with one element print that element).

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

### How?

```
Ẇi¦⁹ḟ - Link: list, A; value V
  ¦   - sparse application...
 i ⁹  - ...to indices: first occurrence of V in A  ([0] if no V found)
W     - ...action: all non-empty sublists (since ¦ zips, the element, z, at any
                                           given index of A will be [z])
    ḟ - filter discard occurrence of V (leaves the [z] as is)
      - implicit print

```

---

I thought `ḟẹḊ¥¦` would work for 5, but it fails with a divide by zero error with `[5,5]` and `5`.
> 5 votes

# Answer
# C (gcc), 60 bytes

Saved 2 bytes thanks to ceilingcat!!!
Saved 2 bytes thanks to ErikF!!!

```
t;f(d,l)int*l;{for(t=0;*l;++l)*l==d&&t++||printf("%d ",*l);}

```

Try it online!

Inputs a number and a pointer to a null terminated array (as there's no way to know the length of an array passed into a function in C) and outputs the filtered array to `stdout`.

### Explanation

```
f(d,                        // function taking the duplicate number d,
    l)int*l;{               // a null terminated array of int l
  for(                      // loop...
      t=0;                  //   init test flag t to 0, this will mark the
                            //   1st (if any) occurance of d
          *l;               // ...over the array elements
              ++l)          // bumping the array pointer each time
      *l==d                 // if the array element isn't d...
           &&t              //   or it's the 1st time seeing d
               ++           //   unmark t by making it non-zero
      ||printf("%d ",*l);   // ...then print that element
}

```
> 5 votes

# Answer
# Japt, ~~10~~ 7 bytes

```
kÈ¶V©T°

```

Try it

-3 bytes thanks to caffeine!

```
kÈ¶V©T°     :Implicit input of array U and integer V
k           :Remove the elements in U that return true
 È          :When passed through the following function
  ¶V        :Is equal to V?
    ©       :Logical AND with
     T°     :Postfix increment T (initially 0)

```
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
Ê0X.;Ï

```

Integer as first input, list as second input.

Try it online or verify all test cases.

**Explanation:**

```
Ê      # Check for each value in the second (implicit) input-list whether it's NOT equal
       # to the first (implicit) input-integer (1 if NOT equal; 0 if equal)
 0X.;  # Replace the first 0 with a 1
     Ï # And only keep the values in the (implicit) input-list at the truthy (1) indices
       # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~26~~ 24 bytes

```
#2/.(a=#)/;a++>#:>Set@$&

```

Try it online!

The pattern `(a=#)` to be matched is only evaluated once, at the very start. Then, the condition `a++>#` is only evaluated when the pattern is matched - so `a` will have been incremented on subsequent matches.
> 3 votes

# Answer
# Bash \+ sed, 49 bytes

```
sed "s/\b$1\b/_/;s/\b$1\b \?//g;s/_/$1/"<<<${*:2}

```

Try it online!

Takes the first argument as the duplicate and the rest as the array.
> 3 votes

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

Translation of Galen Ivanov's J solution.

Anonymous tacit infix function, taking number as left argument and list as right argument (though argument order can be switched by changing the s into s).

```
∊⊢⊆⍨≠∨∘≠⊢

```

Try it online!

on the right argument

`∘≠` apply nub-sieve (Boolean list with Trues where unique elements occur first), then:

… element-wise OR that with:

Boolean list with Trues where elements in the list are different from the number

`⊆⍨` corresponding to runs of Trues in that, extract runs in:

the list

**ϵ**nlist (flatten)
> 3 votes

# Answer
# PowerShell Core, ~~50~~ 31 bytes

```
param($a,$b)$b|?{$_-$a-or!$o++}

```

-19 bytes thanks to mazzy!

Try it online!

Iterates on the array passed as the second parameter and ignores the duplicate occurrence of the first parameter.
> 3 votes

# Answer
# Python 3, 62 bytes

```
f=lambda n,l:l.count(n)>1and f(l.pop(~l[::-1].index(n)),l)or l

```

Try it online!

This function will recursively pop the last instance of the given value until no more than one instance is present. Then it returns the list.

or, for the same byte count

```
lambda n,l:[j for i,j in enumerate(l)if j!=n or i==l.index(n)]

```

Try it online!

This is just a simple filter.
> 2 votes

# Answer
# Red, 46 bytes

```
func[n b][try[replace/all find/tail b n n[]]b]

```

Try it online!
> 2 votes

# Answer
# Husk, ~~13~~ 12 bytes

```
F+ṀΓ·:f≠⁰↕≠⁰

```

Try it online!

user's answer.(-3 bytes, then -1 byte.)

# Husk, 16 bytes

```
J²fI§e←of≠²→↕≠²⁰

```

Try it online!

~~Can probably be shortened with `Γ`.~~

~~There may be an extremely short solution with `ü` as well.~~user's answer

+2 bytes after supporting numbers not in the list.
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
ʒÊD¾ms_½

```

Try it online!

**Commented**:

```
ʒ          # filter the first input on ...
 Ê         #   not equal to the second input (n)?
  D        #   duplicate this value
   ¾       #   push the counter variable initially 0
    m      #   power (value != n)**(counter)
           #   this is only 0 if value==n and counter is positive
     s     #   swap to (value != n)
      _    #   negate this
       ½   #   increment the counter variable if this is truthy (value == n)

```
> 2 votes

# Answer
# , ~~15~~ 10 bytes

-5 bytes thanks to xash!

```
]#~=<:~:@]

```

Try it online!

## My initial solution:

# , 15 bytes

```
[#~~:+i.@#@[=i.

```

Try it online!
> 2 votes

# Answer
# Perl 5, 36 bytes

```
sub{$n=pop;$i=0;grep$n-$_||!$i++,@_}

```

Try it online!

Pop last input value from @\_ into $n. The remaining @\_ is the input list. Filter (grep) @\_ for the values that either isn't equal to $n (`$n-$_` is truthy when $n and current list value $\_ is different) or is the first equal to $n since `!$i++` is truthy for the first and not for the rest.
> 2 votes

# Answer
# APL+WIN, 19 bytes

Prompts for vector followed by element to be removed:

```
((v≠n)+<\v=n←⎕)/v←⎕

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Haskell, 55 bytes

```
f n=foldl(\a x->if x==n&&x`elem`a then a else a++[x])[]

```

Try it online!

* Previous answer was complicated and not so good so I decided to try a more expressive approach inspired by @Caagr98 answer, mine is still longer but I feel better now =)

---

\# Previous 72 bytes
```
g b n(h:t)
 |h/=n=h:g b n t
 |b>0=g 1n t
 |1>0=h:g 1n t
g b n _=[]
f=g 0

```

Try it online!
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 42 bytes

```
a=>b=>a.Where((x,i)=>x!=b|i==a.IndexOf(b))

```

Try it online!
> 2 votes

# Answer
# Scala, ~~62~~ ~~61~~ 58 bytes

```
a=>s=>{val(c,d)=s splitAt s.indexOf(a)+1;c++d.filter(a!=)}

```

Try it online!

* Thanks to Galen for -1 character
* Thanks to user for -3 characters
> 2 votes

# Answer
# JavaScript (Node.js), 117 113 93 bytes

```
function x(i,j){var d,e,o=[];for(x in i){e=i[x]==j;!(e&&d)?o.push(i[x]):0;e?d=1:0;}return o;}

```

Try it online!
> 2 votes

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

```
{y_/|1_&x=y}

```

Try it online!

* `1_&x=y` identify indices of duplicates, ignoring the first
* `y_/|` drop values at the specified indices, in reverse order
> 2 votes

# Answer
# Python 2, ~~55~~ 52 bytes

Thanks to xnor for -3 bytes!

Output is newline-separated.

```
n,l=input()
x=1
for d in l:
 if x|d-n:print d;x*=d-n

```

Try it online!
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ＩΦη∨⁻ιθ⁼κ⌕ηι

```

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

```
  η             Input list
 Φ              Filtered where
     ι          Current element
    ⁻           Subtract (i.e. does not equal)
      θ         Input integer
   ∨            Logical Or
        κ       Current index
       ⁼        Equals
         ⌕      First index of
           ι    Current element in
          η     Input list
Ｉ               Cast to string
                Implicitly print

```

The last character could also be `θ` of course since the two variables are equal at that point.
> 1 votes

# Answer
# K (Kona), 21 bytes

```
{y@&(~x=y)+(!#y)=y?x}

```

Try it online!
> 1 votes

# Answer
# Stacked, 28 bytes

```
[@y:0@b[b\y=:b+@b*¬]"!keep]

```

Try it online!

## Explanation

```
[@y:0@b[b\y=:b+@b*¬]"!keep]
[                         ]   anonymous function (expects 2 args)
 @y                           save top as y
    0@b                       initialize b = 0
   :   [           ]"!        for each element E in the input array:
        b\                      save the current value of b for later computation
          y= b+@b               b = max(b, y == E)
        b y=:    *¬             not both (old b) and (y == E) are true
                                for y != E, and for the first y == E, this is 1, else 0
                              this generates a mask of 1s and 0s
                      keep    keep only the elements in the input which correspond to a 1

```

## Other Solutions

**51 bytes:** `[@y()@z{e:[z e push][z y∈¬*]$!e y=ifelse}map@.z]`

**41 bytes:** `[@y::inits[:y index\#'1-=]map\y neq+keep]`

**36 bytes:** `[@y:0@b[b\:y=b\max@b y=*¬]map keep]`

**33 bytes:** `[@y:0@b[b\:y=b+@b y=*¬]map keep]`
> 1 votes

# Answer
# T-SQL, 49 bytes

Input is an integer and a temporary table

```
SELECT v FROM # GROUP BY v,i*(v-@)ORDER BY min(i)

```

**Try it online**
> 1 votes

# Answer
# PHP 63 Bytes

Number provided in $n, list provided in $a,

```
$p=explode($n,$a,2);echo$p[0].$n.str_replace("$n,", '', $p[1]);

```

# Ungolfed:

```
$p = explode($n,$a,2);
echo $p[0].$n.str_replace("$n,", '', $p[1]);

```

e.g.

```
$n=432;
$a="[432,567,100,432,100]";
$p = explode($n,$a,2);
echo $p[0].$n.str_replace("$n,", '', $p[1]);

```

(I'm unsure if it's ok not to count the input into the bytes, or the opening '\<?php' for that matter...)
> 1 votes

# Answer
# Google Sheets, 72

* Column A is input array. Name range `A`.
* B1 is target value. Name range `B`.
* C1 is `=IFNA(MATCH(B,A,`
* D1 is `=ArrayFormula(IF((ROW(A)>C1)*(A=B),,A`. Name range `D`.
* E1 is `=IFNA(FILTER(D,D`

+3 total for named ranges.

## How

* C1 looks for the index of the occurrence. If none is found, return blank (0-like).
* D1 filters out values if **1)** Row is greater than the first occurrence's index and **2)** if the value matches.
* E1 Removes blanks. If D is empty, it's NA, so just output a blank.
> 1 votes

# Answer
# Uiua SBCS, 6 bytes

```
▽↥⊃◰≠,

```

Try it!
> 1 votes

# Answer
# jq, 58 bytes

```
def r(x):index(x)as$i|if$i then.[:$i+1]+(.[$i+1:]-[x])end;

```

Works with jq (the C implementation) and with gojq (the Go implementation).

Note that but for Code Golf, one would normally write `$x` instead of `x`.

Try it online: https://jqplay.org/s/pKEk1AdpPaB
> 1 votes

# Answer
# Wolfram Language (Mathematica), 50 bytes

```
Insert[DeleteCases@##,#2,#&@@Position@##]~Check~#&

```

Try it online!
> 0 votes

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


title: Double-reduce a sequence of integers

text:
# Question
Title: Double-reduce a sequence of integers
Consider a function \\$r\\$ where

$$ r(i,k)= \begin{cases} L\_{i+1}-L\_i, & \text{if}\ k =0\ \text{ (1st reduction)} \\ r(i,0)-r(\lfloor \log\_2{k} \rfloor,k-2^{\lfloor \log\_2{k} \rfloor}) & \text{if}\ k \geq 1\ \text{ (2nd reduction)} \end{cases} $$

where \\$k\<2^i\\$ and \\$L\\$ is a finite sequence of integers.

For example, assuming that \\$L = \\{0, 1, 1, 2, 3, 5\\}\\$,

for \\$i=0\\$,

* \\$r(0,0) = L\_1-L\_0 = 1-0 = 1\\$.

for \\$i=1\\$,

* \\$r(1,0) = L\_2-L\_1 = 1-1 = 0\\$.
* \\$r(1,1) = r(1,0)-r(0,0) = 0-1 = -1\\$.

for \\$i=2\\$,

* \\$r(2,0) = L\_3-L\_2 = 2-1 = 1\\$.
* \\$r(2,1) = r(2,0)-r(0,0) = 1-1 = 0\\$.
* \\$r(2,2) = r(2,0)-r(1,0) = 1-0 = 1\\$.
* \\$r(2,3) = r(2,0)-r(1,1) = 1+1 = 2\\$.

The **double-reduction of \\$L\\$** is created by concatenating results from \\$i=0\\$, \\$i=1\\$, ..., until every consecutive pair of elements of \\$L\\$ are visited.

In layperson's terms, this function subtracts two consecutive terms of \\$L\\$, and then subtract every previous-calculated subtraction from that result. Note that every call of \\$r(i,k)\\$, for \\$i\>0\\$ and \\$k\>0\\$, is already computed.

## Input

A list of integers `L`. You can assume its size will be always greater or equal to 3.

## Output

A representing the double-reduction of `L`.

> * **Indexing:** Both \\$0\\$\- and \\$1\\$-based indexing are allowed, and the following rules can be applied with both these types of indexing.
> * **Format:** The answers can use one of the following output methods:
>     + Given some index \\$n\\$, it can return the \\$n\\$-th entry of the list.
>     + Given some index \\$n\\$, it can return all entries up to the \\$n\\$-th one in the sequence.
>     + Without taking any index, it can output *all* entries by printing them one by one or by returning a list.

### Test cases

Here's the test cases for positive numbers, even numbers, prime numbers, Fibonacci numbers, power-of-2 numbers, lucky numbers and signed Fibonacci numbers, respectively:

```
[1, 2, 3] -> [1, 1, 0]
[2, 4, 6, 8] -> [2, 2, 0, 2, 0, 0, 2]
[2, 3, 5, 7, 11] -> [1, 2, 1, 2, 1, 0, 1, 4, 3, 2, 3, 2, 3, 4, 3]
[0, 1, 1, 2, 3, 5] -> [1, 0, -1, 1, 0, 1, 2, 1, 0, 1, 2, 0, 1, 0, -1, 2, 1, 2, 3, 1, 2, 1, 0, 1, 2, 1, 0, 2, 1, 2, 3]
[1, 2, 4, 8, 16, 32] -> [1, 2, 1, 4, 3, 2, 3, 8, 7, 6, 7, 4, 5, 6, 5, 16, 15, 14, 15, 12, 13, 14, 13, 8, 9, 10, 9, 12, 11, 10, 11]
[1, 3, 7, 9, 13, 15, 21] -> [2, 4, 2, 2, 0, -2, 0, 4, 2, 0, 2, 2, 4, 6, 4, 2, 0, -2, 0, 0, 2, 4, 2, -2, 0, 2, 0, 0, -2, -4, -2, 6, 4, 2, 4, 4, 6, 8, 6, 2, 4, 6, 4, 4, 2, 0, 2, 4, 6, 8, 6, 6, 4, 2, 4, 8, 6, 4, 6, 6, 8, 10, 8]
[0, 1, -1, 2, -3, 5, -8] -> [1, -2, -3, 3, 2, 5, 6, -5, -6, -3, -2, -8, -7, -10, -11, 8, 7, 10, 11, 5, 6, 3, 2, 13, 14, 11, 10, 16, 15, 18, 19, -13, -14, -11, -10, -16, -15, -18, -19, -8, -7, -10, -11, -5, -6, -3, -2, -21, -20, -23, -24, -18, -19, -16, -15, -26, -27, -24, -23, -29, -28, -31, -32]

```

Your solution should be implemented with fewest bytes as possible.

Brownie points for beating or matching my 70-bytes Python answer.

# Answer
> 6 votes
# Charcoal, 24 bytes

```
⊞υ⁰ＦＥΦθκ⁻ι§θκ≔⁺υ⁻ιυυＩΦυκ

```

Try it online! Link is to verbose version of code. Explanation: Adapted from both @Arnauld's and @loopywalt's answers.

```
⊞υ⁰

```

Start with a list of just `0`.

```
ＦＥΦθκ⁻ι§θκ

```

Loop over the list of differences of the input array.

```
≔⁺υ⁻ιυυ

```

Subtract all of the elements of the output array from the current difference and then concatenate the result onto the output array.

```
ＩΦυκ

```

Output all but the first element of the output array.

# Answer
> 5 votes
# Python, 63 bytes

```
f=lambda l,*L,a=[]:L and f(*L,a=a+[L[0]-l-b for b in[0]+a])or a

```

Attempt This Online!

Takes splatted input. Returns the entire double-reduction.

## How?

Once one all but ignores the confusing double indexing there is an obvious rather simple recursion.

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

An implementation of what the function *really* does, as described in the *layman's terms* paragraph of the challenge.

```
a=>a.map(v=>a=[0,...b].map(k=>1/a&&b.push(v-a-k))&&v,b=[])&&b

```

Try it online!

### Commented

```
a =>              // a[] = input
a.map(v =>        // for each value v in a[]:
  a =             //   update a:
    [0, ...b]     //     for 0 and each value in b[]
    .map(k =>     //     loaded in k:
      1 / a       //       do nothing if this is the 1st iteration,
      &&          //       i.e. a is still the input array (*)
      b.push(     //       otherwise, push in b[]:
        v - a - k //         the current value, minus the previous one,
      )           //         minus k
    )             //     end of inner map()
    && v,         //     save v in a
  b = []          //   start with b[] = empty array
)                 // end of outer map()
&& b              // return b[]

```

*(\*) The input is guaranteed to contain at least 3 integers, as per the challenge rules. So it can't be coerced to a number.*

---

# JavaScript (V8), 92 bytes

This was an attempt at implementing the definition literally.

```
L=>{for(n=1;L[-~(g=Math.log2)(n)];)print((r=k=>~(k-=2**(i=~~g(k)))&&L[i+1]-L[i]-r(k))(n++))}

```

Try it online!

# Answer
> 2 votes
# Haskell, 48 bytes

```
r a[_]=a
r a(x:y:l)=r(a++[y-x-z|z<-0:a])$y:l
r[]

```

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
Î¥vDyα‚˜}¦

```

Inspired by *@Neil*'s Charcoal answer.

Try it online or verify all test cases.

**Explanation:**

```
Î         # Push 0 and the input-list
 ¥        # Get the deltas/forward-differences of the input-list
  v       # Loop over each of its integers `y`:
   D      #  Duplicate the current list,
          #  which is the 0 in the first iteration
    yα    #  Get the absolute difference of each value with integer `y`
      ‚   #  Pair this list together with the duplicated list (or the 0)
       ˜  #  Flatten it to a single list
  }¦      # After the loop: remove the leading 0
          # (after which the list is output implicitly as result)

```

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


title: Custom Games of Life

text:
# Question
Title: Custom Games of Life
There's a lot of questions about *Conway's* Game of Life, but nothing about customization (Related: 2-Player Life). Given an input, determine the result on a 100x100 grid after some iterations. The input is given as a string. For example:

```
Using the character #, follow the following rules:
If there are 2 or 3 neighboring nothing, turn into #.

Using nothing, follow the following rules:
If there are 3 neighboring #, turn into #.

Output the result after 100 iterations for the cells:
[Lots of cells here]

```

As you might be able to tell, this is Conway's Game of Life, where a cell is alive if there are three live neighbors, and a live cell with less than two or more than three neighbors dies. You may use any kind of input, but I'll be doing it like this for simplicity.

### Input

* For simplicity, a character can *also* be the phrase "**nothing**."
* Each rule is separated by two newlines. Each rule starts with, "**Using the character `X`, follow the following rules:**" where `X` represents a character.
* Then, it says "**If there are `[amount]` neighboring `X`, turn into `Y`.**" The amount is some numbers, separated by `or`, where `X` and `Y` represent characters. It may say this multiple times.
* Then it says, "Output the result after `N` iterations for the cells:" Your job is to return the result after N iterations.
* Then, decode the cells given. The cells are stored with a space for empty cells, and a single character for all the other characters. Newlines separate the rows.

Also, the last rule is always for `nothing`, and instead starts with "**Using nothing, follow the following rules:**" A cell will never turn into itself. (So, for `#`, "If there are 2 $, turn into #." will not happen.)

Simply render "nothing" with a space, and all other characters normally. The other characters are ASCII and not a space.

For the iterating, follow the instructions for each character. When it says "neighboring," it means the cells next to it (including diagonals).

For the borders, "wrap around" the cells. One way to think of wrapping around is to pretend that there are 8 identical grids surrounding the current one, then updating the current ones with the new neighbors. (Sorry if my explanation was weird.)

## Test case (replace \n with a newline):

```
Using the character #, follow the following rules:
If there are 0 or 1 #, turn into $.
If there are 4 or 5 or 6 or 7 or 8 #, turn into nothing.

Using the character $, follow the following rules:
If there are 4 nothing, turn into #.
If there are 4 or 5 or 6 or 7 or 8 $, turn into #.

Using nothing, follow the following rules:
If there are 3 #, turn into #.

Output the result after 25 iterations for the cells:
                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                             $$$$$$$$$$                                             \n                                             $$$$$$$$$$                                             \n                                             #        #                                             \n                                             #        #                                             \n                                             $$$ $$$ $$                                             \n                                              $$$ $$$ $                                             \n                                             $ $$$ $$$                                              \n                                             ####  ####                                             \n                                             ##      ##                                             \n                                             $#$#$#$#$#                                             \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n                                                                                \n

```

## Result:

<sup>(This code golf is inspired by this thingy, and of course, Conway's Game of Life.)</sup>

# Answer
# Python 3.8, 597 bytes

```
from copy import deepcopy as p
def f(r):
 u,g,b,e={},0,[],' '
 for l in r:
  if g:b+=[list(l)];z=len(l);continue
  j=l[:1]
  if'T'<j:c=[e,l[20]][l[6]>'n'];u[c]=[]
  if'I'==j:
   n=[]
   for s in l[13:].split(' or '):
    n+=[int(s[0])]
    if s[3:]:v=[s[2],e][','<s[3:4]]
   u[c]+=[[v,n,[l[-2],e][l[-3]>e]]]
  if'O'==j:i=int(l.split()[4]);g=1
 for _ in e*i:
  h=p(b)
  for k in range(len(b)*z):
   r,c=k//z,k%z;v={k:0 for k in u}
   for j in range(9):x,y=j//3-1,j%3-1;v[b[(r+y)%len(b)][(c+x)%z]]+=1
   a=b[r][c];v[a]-=1
   for w in u[a]:
    if v[w[0]]in w[1]:h[r][c]=w[2];break
  b=p(h)
 return b

```

Try it online!

Online custom game of life simulator: Emoji Simulator!

---

*Commented code*

```
from copy import deepcopy as p

def f(r):
    """Takes as input a list of lines"""

    # dictiornary of rules of the grid
    u = {}
    # flag to extract lines of the grid
    g = 0
    # the grid, as a list of lists of characters
    b = []
    # space used to represent nothing
    e = ' '

    # PART 1
    # parse the rules

    # loop on the input lines
    for l in r:

        if g:
            # extract lines of the grid
            b += [list(l)]
            # extract the lenght of the row of the grid
            # used for the loop n the grid
            z = len(l)

            # skip other checks
            continue

        # extract the first character for each line
        # not [0] since it can be an empty line
        j = l[:1]

        if 'T' < j:

            # line "Using the character ..."

            # extract the character
            # checking if the character is nothing
            c = [e, l[20]][l[6] > 'n']

            # initialize an empty list for the rules associated to the character
            u[c] = []

        if 'I' == j:

            # line "If there are ..."

            # initialize list of repetitions
            n = []

            # the number of repetitions are split by or
            for s in l[13:].split(' or '):

                # extract the number
                # always the first element of the split
                n += [int(s[0])]

                # extract the character associated with the repetitions
                # the number is followed by the character
                # this means that the split string is longer
                if s[3:]:

                    # character associated with the repetitons
                    # checking if the character is nothing
                    v = [s[2], e][',' < s[3:4]]

            # add the rule
            u[c] += [[
            # character associated with the repetitons
            v,
            # list of number of repetitions
            n,
            # extract the new character to substitute
            # checking if the character is nothing
            [l[-2], e][l[-3] > e]
            ]]

        if 'O' == j:

            # line "Output the result ..."

            # extract the number of steps
            i = int(l.split()[4])
            # set flag to extract the lines of the grid
            g = 1

    # PART 2
    # evaluate the steps on the grid

    # loop for i steps
    # e*i is an auxiliary string of length i to evaluate i steps
    for _ in e * i:

        # copy the previous grid state
        h = p(b)

        # loop on each cell of the grid
        # loop on height*width
        for k in range(len(b)*z):

            # extract the index of row, column from the "total" loop index
            r, c = k//z, k%z

            # initialize dictionary of count of neighbouring characters
            v = {k: 0 for k in u}

            # loop on the 3x3 square around the actual cell
            for j in range(9):

                # scale to range [-1, 0, 1]
                x, y = j//3 - 1, j%3 - 1

                # update the count of neighbour
                # extracting the corresponding character in the grid
                v[b[(r+y)%len(b)][(c+x)%z]] += 1

            # current character
            a = b[r][c]

            # remove the current cell from the count of neighbours
            v[a] -= 1

            # check rules
            for w in u[a]:

                # if count of neighbour is in list of number of repetitions
                if v[w[0]] in w[1]:

                    # substituite actual character in the grid with the new one
                    h[r][c] = w[2]

                    # rule found, skip others
                    break

        # update the actual grid
        b = p(h)

    # return the grid after the steps
    return b

```
> 0 votes

---
Tags: code-golf, ascii-art, cellular-automata, game-of-life
---


# Question
Title: Binary representation of a number is palindrome or not?
Write a full program to find whether the binary representation of a number is palindrome or not?

```
Sample Input
5

Sample Output
YES

```

Print `YES` if binary representation is palindrome and `NO` otherwise.

# Answer
## Golfscript -- 22 chars

```
~2base.-1%="YES""NO"if

```
> 5 votes

# Answer
## Python - 46 chars

```
n=bin(input())[2:]
print'YNEOS'[n!=n[::-1]::2]

```
> 34 votes

# Answer
# Vyxal, 85 bitsv1, 10.625 bytes

*-6 bits thanks to @lyxal*

*-3 bits thanks to @the-thonnu*

```
bḂ≠`∨ȯno`½iN

```

Try it Online!

```
b            # binary of input
 Ḃ≠          # is not equal to its reverse (essentially: is not a palindrome?)
   `∨ȯno`    # compressed string `yesno`
         ½   # split into two strings of equal length
          i  # index that inequality (0/1) into that
           N # case swapped to uppercase

```
> 5 votes

# Answer
**C 84 81 74 Characters**

```
r;main(v,x){for(scanf("%d",&v),x=v;v;v/=2)r=r*2|v&1;puts(r-x?"NO":"YES");}

```

It does not use any function like string reverse.
> 4 votes

# Answer
## Ruby, 41 39

```
$><<%w(YES NO)[(n="%b"%$*)<=>n.reverse]

```

Thanks to Michael Kohl's "%b"%gets trick.
> 4 votes

# Answer
## Javascript - 79 77 chars

```
alert((a=(prompt()*1).toString(2))-a.split("").reverse().join("")?"NO":"YES")

```

**More information**

`prompt()*1` : Quick trick to convert string to number.

`.toString(2)` : That's how you convert to binary in javascript.

`a.split("").reverse().join("")` : There is no native support to reverse string, so you have to convert string to array and array to string.

`("[part1]" - "[part 2]")?"YES":"NO"` : `-` is a replacement for `!=` to save 1 char.
> 3 votes

# Answer
# PHP - 41

```
<?=strrev($n=decbin(`cat`))==$n?@YES:@NO;

```

Test:

```
php 713.php <<< 5
YES
php 713.php <<< 6
NO

```
> 2 votes

# Answer
# Perl, 45 characters

```
$_=sprintf'%b',shift;
print reverse==$_?YES:NO

```
> 2 votes

# Answer
**Ruby, 43 characters**

```
puts((n="%b"%gets)==n.reverse ? "YES":"NO")

```
> 2 votes

# Answer
## Windows PowerShell, 67

```
('NO','YES')[($a=[Convert]::ToString("$input",2))-eq-join$a[64..0]]

```
> 2 votes

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

```
‘NO…Ü‘#EbÂQè

```

*-5 bytes thanks to Adnan.*

Try it online!
> 2 votes

# Answer
# JavaScript, 75 bytes 69 bytes

```
alert((a=[...(+prompt()).toString(2)]).some(x=>x-a.pop())?"NO":"YES")

```

Try it online!

A different approach from HoLyVieR's solution

**Explanation**

`+prompt()` : Converts string to number

`[...s]` : converts a string `s` to an array of chars

`.some((x) => x - a.pop())` : checks whether there is one element in the array that does not equal the last element of the array

**Edit**

69 chars, thanks to the suggestions by Shaggy
> 2 votes

# Answer
# Arturo, 47 bytes

```
print(=reverse<=as.binary do arg\0)?->'YES->'NO

```
> 2 votes

# Answer
## Python (51)

```
n=bin(input())[2:]
print'YES'if n==n[::-1]else'NO'

```
> 1 votes

# Answer
# Perl (73)

No string reverse:

```
print f(split//,sprintf'%b',shift);
sub f{@_<=1?YES:shift!=pop()?NO:f(@_)}

```
> 1 votes

# Answer
# Perl (127)

This one constructs all palindromes up to 2^32.

```
sub f{
    my($x,$l)=@_;
    $l+=2,f(($x<<$_)+1+(1<<$l-1),$l)?return 1:0 for 1..15-$l/2;
    $x-$ARGV[0]?0:1
}
print f(0,1)+f(0,0)+f(1,1)?YES:NO

```
> 1 votes

# Answer
## Bash, 55 chars

```
C=`dc<<<$1\ 2op`;[ $C = `rev<<<$C` ]&&echo YES||echo NO

```
> 1 votes

# Answer
## Haskell (79)

```
0?k=n;n?k=div n 2?(n`mod`2+k*2);f x|x==x?0="YES"|True="No";main=interact$f.read

```
> 1 votes

# Answer
## J - 33 characters

```
13 : ';(]-:|.)#:y{''YES'';''NO'''

```
> 1 votes

# Answer
## J: 24

```
((-:|.)#:x){2 3$'NO YES'

```

eg:

```
   ((-:|.)#:5){2 3$'NO YES'
YES
   ((-:|.)#:12){2 3$'NO YES'
NO
   ((-:|.)#:125){2 3$'NO YES'
NO
   ((-:|.)#:63){2 3$'NO YES'
YES

```
> 1 votes

# Answer
## C (77 bytes)

```
r,t;main(n){for(t=n=atoi(gets(&n));n;r*=2,r|=n%2,n/=2);puts(r-t?"NO":"YES");}

```

TEST
> 1 votes

# Answer
## Pyth, 18 bytes

```
%2>"YNEOS"!qJ.BQ_J

```

Also 18 bytes:

```
@,"NO""YES"qJ.BQ_J

```
> 1 votes

# Answer
# PHP, not competing

I wanted to do it without using strings at all.

iterative solution, 78 bytes

```
for($x=log($n=$argv[1],2);$i<$x&($n>>$i^$n>>$x-$i^1);$i++);echo$i<$x/2?NO:YES;

```

recursive solution, 113 bytes

```
function p($n,$x=0){return$n<2?$n:is_pal(($n&(1<<$x=log($n,2)/2)-1)^$n>>$x+!is_int($x));}echo p($argv[1])?YES:NO;

```

If `n` is a binary palindrome, the upper half xor the lower half is also a binary palindrome and vice versa.

---

a port of the excellent C answer from fR0DDY, 58 bytes

```
for($x=2*$v=$argv[1];$x/=2;$r=$r*2|$x&1);echo$r-$v?NO:YES;

```

a binary reverse. Columbus´ egg.
> 1 votes

# Answer
# Retina, ~~80~~ 78 bytes

Byte count assumes ISO 8859-1 encoding.

```
.+
$*
+`(1+)\1
${1}0
01
1
^((.)*?).??((?<-2>.)*$)
$1¶$3
O$^`.(?=.*¶)

^(.*)¶\1

```

**Try it online**

Convert to unary. Convert that to binary. Cut the number in half and remove a middle digit if there is one. Reverse the first half. Match if both halves are equal.
> 1 votes

# Answer
# Jelly, 12 bytes (non-competing)

```
BṚ⁼Bị“YES“NO

```

Try it online!

Explanation:

```
BṚ⁼Bị“YES“NO Main link. Arguments: z.
B            Binary representation of z.
 Ṛ           Reversed.
   B         Binary representation of z.
  ⁼          Check if x is equal to y.
     “YES“NO [['Y', 'E', 'S'], ['N', 'O']]
    ị        xth element of y (1-indexed).

```

Before printing, Python's `str` function is mapped through a list, and then the elements are concatenated, so you see `YES` or `NO`.
> 1 votes

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

```
'NO' 'YES'⊃⍨≡∘⌽⍨2⊥⍣¯1⊢⎕

```

-3 bytes from Bubbler, after fitting the question requirements.

Instead of performing an if-else like below, this program uses APL's representation of true as 1 and false as 0 to select from an array, where 'NO' is in the 0th index and 'YES' is in the first index.

Try it online!

# APL (Dyalog Unicode), 26 bytes (SBCS)

```
{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}

```

## Explanation

```
{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}
{                        } function wrapper
             ⍵             take the right argument
      2(⊥⍣¯1)              convert to base 2, and split into -1 groups(gets all digits)
 (⌽≡⊢)                     reverse equals right expression?
              :'YES'⋄'NO'} if the above is true, display 'YES', otherwise 'NO'

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 46 bytes

```
If[PalindromeQ@IntegerDigits[#,2],"YES","NO"]&

```

Try it online!
> 1 votes

# Answer
# Arn, 16 bytes

```
±î«Áýãf©¯tvf–É‰2

```

Try it!

# Explained

Unpacked: `"YES"^(=\|:;b)||"NO`. Man that yes/no required output really killed my byte count

```
    "YES"         String
  ^               Repeated
    (             Begin expression
        \         Fold with...
      =           ...equality
          |:      Bifurcate
              _   Variable initialized to STDIN; implied
            ;b    Binary representation
    )             End expression
||                Boolean OR
  "NO             String, ending quote implied

```

This works because empty strings are falsey.
> 1 votes

# Answer
# Pyth, 16 bytes

```
?q_K.BQK"YES""NO

```

Try it online!

```
?q_K.BQK"YES""NO
   K.BQ          // Assign binary input to K
?q_K   K         // Evaluate whether K and reversed K are equal
        "YES""NO // Ternary output.

```
> 1 votes

# Answer
# Nibbles, ~~11.5~~ 11 bytes (22 nibbles)

*Edit: -1 nibble thanks to xigoi*

```
?==;``@$\@"YES" "NO"

```

```
    ``@                 # get binary representation of
       $                # input
   ;                    # and save it;
 ==                     # is this equal to
        \               # reverse of
         @              # itself?
?                       # if so:
           "YES"        #   output "YES"
                        # otherwise:
                 "NO"   #   output "NO"

```
> 1 votes

# Answer
# Japt, 13 bytes

```
¢è¬?`y`u:"NO

```

Try it
> 1 votes

# Answer
# Thunno 2, 12 bytes

```
ḃḲQ"YESNO"½i

```

Attempt This Online!

Unfortunately, the Thunno 2 dictionary only holds words which are 4 letters or more, so neither `YES` nor `NO` can be compressed.

#### Explanation

```
ḃḲQ"YESNO"½i  # Implicit input
ḃ             # Convert to binary
 ḲQ           # Not equal to its reverse?
              # (i.e. 0 if palindrome, 1 otherwise)
   "YESNO"    # String "YESNO"
          ½   # Halve to get ["YES", "NO"]
           i  # Index into the list
              # Implicit output

```
> 1 votes

# Answer
## Haxe, 164 bytes

Works only with system platforms (php, neko, cpp, etc.). Takes input through command line arguments.

```
class T{static function main(){var r:Dynamic=Std.parseInt(Sys.args()[0]);var s=r.toString(2);trace(s==[for(i in-s.length+1...1)s.charAt(-i)].join('')?"YES":"NO");}}

```
> 0 votes

# Answer
# Matlab, 71 bytes

```
function paly(n)
v=de2bi(n);
if v==v(numel(v):-1:1)
'YES'
else
'NO'
end

```
> 0 votes

# Answer
# 05AB1E, 13 bytes

```
bÂQi'…Üë'€¸}u

```

Try it online!

```
bÂQi'…Üë'€¸}u  # full program
   i           # if...
 Â             # implicit input...
b              # in binary...
  Q            # is equal to...
 Â             # implicit input...
b              # in binary...
 Â             # reversed...
    '…Ü        # then push "yes"
       ë       # else...
        '€¸    # push "no"
           }   # exit if statement
            u  # convert to uppercase
               # implicit output

```
> 0 votes

# Answer
# Python, 84 Bytes

```
f=lambda x:['NO','YES'][int(bin(x)[2:]==(bin(x)[2:])[-1::-1])]
print(f(int(input())))

```

Try online on TIO

### If just a pure function was allowed:

Try pure function online (60 Bytes)
> 0 votes

# Answer
# Uiua SBCS, 22 bytes

```
&p⊡≍⇌.⋯⋕&sc{"NO""YES"}

```

Try it!
> 0 votes

---
Tags: code-golf, binary, palindrome
---