title: Convert numbers to dice patterns

text:
# Question
Title: Convert numbers to dice patterns
The way points are assigned on a dice follows a regular pattern, the center dot is present if and only if the number is odd. To represent the even numbers, pairs of dots on opposite sides of the center are added, which will stay present for all successive numbers.

```
1:
O

2:   3:    4:   5:    6:
O     O     O O   O O   O O
       O           O    O O
  O     O   O O   O O   O O

```

This "dice pattern" can be extended to numbers greater than 6.

* The dots are arranged in a square of size k with k being the smalest *odd* integer that satisfies k\*k\>=n
* the dots are added in layers for the center outwards
* one each layer the corners are added first
* then the midpoints of the sides, first on the vertical, then on the horizontal sides.
* for the remaining pairs of dots on each level you can choose any convenient order

*Due to there already being solutions a the time it was added, the next constraint is an optional additional requirement:*

* If the number of dots is divisible by 4 the pattern should be symmetric under reflections along the coordinate axes (through the center)

```
// one possible way to add the remaining dots
7:    8:
O O    OOO
OOO    O O
O O    OOO

10:     12:      14:      16:      18:     20:      22:      24:
O        O   O    O   O    O O O    O O O    O O O    OOO O    OOOOO
 OOO      OOO      OOO      OOO     OOOO     OOOOO    OOOOO    OOOOO
 O O      O O     OO OO    OO OO    OO OO    OO OO    OO OO    OO OO
 OOO      OOO      OOO      OOO      OOOO    OOOOO    OOOOO    OOOOO
    O    O   O    O   O    O O O    O O O    O O O    O OOO    OOOOO

26:        30:          32:          36:          40:         44:
O           O     O      O  O  O      O  O  O      OO O OO      OO O OO
 OOOOO       OOOOO        OOOOO       OOOOOOO      OOOOOOO      OOOOOOO
 OOOOO       OOOOO        OOOOO        OOOOO        OOOOO       OOOOOOO
 OO OO      OOO OOO      OOO OOO      OOO OOO      OOO OOO      OOO OOO
 OOOOO       OOOOO        OOOOO        OOOOO        OOOOO       OOOOOOO
 OOOOO       OOOOO        OOOOO       OOOOOOO      OOOOOOO      OOOOOOO
      O     O     O      O  O  O      O  O  O      OO O OO      OO O OO
46:         48:
OOOO OO      OOOOOOO
OOOOOOO      OOOOOOO
OOOOOOO      OOOOOOO
OOO OOO      OOO OOO
OOOOOOO      OOOOOOO
OOOOOOO      OOOOOOO
OO OOOO      OOOOOOO

```

Your task is to write a program of function, that given a positive integer as input outputs the dice pattern for that number.

## Rules:

* Trailing white-spaces are allowed
* Additional white-spaces at the start of each line are allowed, as long as all lines are indented by the same amount
* You can replace `O` by any non-whitespace character
* You may return a matrix of Truthy/Falsey values instead of printing the outputs
* Your program has to work for inputs at least up to 2601=51\*51, but your algorithm should work for arbitrarily large numbers
* This is the shortest solution in bytes wins

---

related

# Answer
> 6 votes
# Python 3 (194 ~~199~~ ~~210~~ bytes) -16 (- 5 thanks to Kevin)

My First golf! Returns a int, array, where `len(arr) == side ** 2`

```
def f(n):
 s=2*round(.5*n**.5-1)+3;q=s*s;d,e=[1]*q,~-s>>1;r=*({*range(s-2,0,-1)}-{0,e}),e,0;d[s*s//2]=n&1;q&=-2;b=(q-n+3)//2
 for k in*r[:b//2],*(s*~i for i in r[:~-b//2]):d[k]=d[~k]=0
 return d

```

Inputs: `n`
Output: returns 1d array containing pips

Attempt it online!

## Formatting code:

```
print(n, sum(d), *(list((map(int, d[i:(i+s)]))) for i in l(0, s*s, s)), sep="\n")

```

## Explanation:

Calculates the correct odd-square size to have a proper center

```
s=2*round(.5*n**.5-1)+3

```

Sets a variable keeping track of how many pips there are currently

```
q=s*s

```

Creates a 1D pip array, all filled with 1s, and sets e to center index

```
d,e=[1]*q,~-s>>1

```

Creates a tuple of which order to delete pips. Goes from right right-left, center, corner. (-4 bytes)

```
r=*({*range(s-2,0,-1)}-{0,e}),e,0

```

Sets the center pip based on if it's odd

```
d[s*s//2]=n&1

```

Clears the last bit of q (sets it to even)

```
q&=-2

```

Stores number of pip-pairs to remove

```
b=(q-n+3)//2

```

Clears pips over the limit in the pip-array

```
 for k in*r[:b//2],*(s*~i for i in r[:~-b//2]):d[k]=d[~k]=0

```

Returns d

```
 return d

```

# Answer
> 5 votes
# JavaScript (ES7), 180 bytes

Returns a binary matrix.

```
n=>[...Array(w=n**.5-n/~n&~1),W=w/2].map((_,y,a)=>a.map((_,x)=>x-W|y-W?(g=k=>k--?g(k)|y==W+(A=[d=k<4?W:(k&4?k:-k)/8|0,-d,W,-W])[k&=3]&x==W+A[6>>k&3]:x%w&&y%w>0)(n-w*w+2*w&~1):n&1))

```

Try it online! (with post-processing for readability)

# Answer
> 2 votes
# Charcoal, 50 bytes

```
ＮθＦ﹪θ²ＰOＷ⁻θＬＫＡ«↙≔ⅉηＦ⁸«Ｐ✳＆⁶κ×O⌊⟦η÷⁺ιＩ§4062κ⁸⟧Ｍη✳＆⁶κ

```

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

```
Ｎθ

```

Input `n`.

```
Ｆ﹪θ²ＰO

```

If `n` is odd then print an `O` at the origin.

```
Ｗ⁻θＬＫＡ«

```

Repeat while more `O`s are required.

Move to the bottom left corner of the next size of square.

```
≔ⅉη

```

Get the new offset (which is an eighth of the perimeter of this square).

```
Ｆ⁸«

```

Repeat to complete the perimeter of this square.

```
Ｐ✳＆⁶κ×O⌊⟦η÷⁺ιＩ§4062κ⁸⟧

```

Output a number of `O`s depending on how many more are needed and which part of the perimeter is being drawn, but no more than the current offset.

```
Ｍη✳＆⁶κ

```

Move to the next compass point without printing anything, which would throw off the count of `O`s written.

Example: When `n` is between `2` and `9`, the number of `O`s is added to the given digit according to the following pattern:

```
604
2 2
406

```

This means that `O`s will only be drawn on the horizontal midpoints if `n` is `8` or `9`, but will be drawn for lower values of `n` in the other positions.

---
Tags: code-golf, ascii-art, graphical-output, open-ended-function
---


title: Iterate over all non-equivalent strings

text:
# Question
Title: Iterate over all non-equivalent strings
# Input

A single positive integer \\$ 10 \geq n \geq 2\\$

# Output

A list of strings, each of length \\$2n\\$, satisfying the following properties.

* Each string will contain each of the first \\$n\\$ lowercase letters of the alphabet exactly twice.
* No letter can occur twice consecutively. That is `abbcac` is not allowed.
* No two strings that are `equivalent` can be in the list. Equivalence will be defined below.
* All non-equivalent strings satisfying the rules must be in the list.

# Equivalence

We say that two strings of the same length are equivalent if there is a bijection from the letters in the first string to the letters in the second string which makes them equal. For example, `abcbca` and `bcacab` are equivalent.

# Examples

* \\$n = 2\\$: `abab`
* \\$n = 3\\$: `abacbc abcabc abcacb abcbac abcbca`

The length of these lists is A278990.

# Answer
> 5 votes
# Charcoal, 45 bytes

```
≔⪪…βＮ¹θ⊞υωＦ⁺θθ≔ΣＥυ⁺κΦθ∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυυ

```

Attempt This Online! Link is to verbose version of code. Theoretically supports `n` up to `26`. Explanation:

```
≔⪪…βＮ¹θ

```

Get the first `n` letters of the lowercase alphabet.

```
⊞υω

```

Start with an empty string.

```
Ｆ⁺θθ

```

Loop `2n` times.

```
≔ΣＥυ⁺κΦθ∧⁻μΦ⮌κ¬π∧‹№κμ²⬤…βν№κξυ

```

For each string so far, create strings with all of the first `n` lowercase letters appended to it, but exclude those that fail to satisfy the criteria.

```
υ

```

Output the final strings.

There are three criteria that are checked when considering candidate letters to append:

* The letter must not already be the last letter of the string
* The letter must not have already appeared twice
* All previous letters must already appear in the string

# Answer
> 5 votes
# JavaScript (ES6), 107 bytes

Returns a single space-separated string.

```
f=(n,s=' ',m=1,i=m,g=q=>i?f(n,"abcdefghij"[--i]+s,+q+m)+g``:q)=>s[2*n]?/(.)(|.*\1.*)\1/.test(s)?'':s:g(m<n)

```

Try it online!

Or **106 bytes** in Node.js.

### Method

We recursively build all non-equivalent strings of length \\$2n\\$ with \\$n\\$ distinct characters. The non-equivalence is enforced by using an upper bound \\$m\\$ which is initialized to \\$1\\$ and incremented as soon as the \\$m\\$-th character has been inserted and while we have \\$m\<n\\$.

The other criteria are tested at the end of the recursion with a regular expression which should *not* be matched by a valid string:

```
/(.)(|.*\1.*)\1/

```

### Commented

```
f = (                // f is a recursive function taking:
  n,                 //   n = input
  s = ' ',           //   s = current output string
  m = 1,             //   m = upper character bound
  i = m,             //   i = counter
  g = q =>           //   g is a recursive function taking a flag q:
    i ?              //     if i is not zero:
      f(             //       1st recursive call to f:
        n,           //         pass n unchanged
        "abcdefghij" //         lookup string of letters
        [--i]        //         decrement i and append the i-th letter
        + s,         //         followed by s
        +q + m       //         increment m if q is set
      )              //       end of recursive call
      + g``          //       2nd recursive call to g with q zero'ish
    :                //     else:
      q              //       stop (at this point, we have q = [''])
) =>                 //
  s[2 * n] ?         // if s has 2n + 1 characters:
    /(.)(|.*\1.*)\1/ //   if there's any character in s immediately
    .test(s) ?       //   followed by itself or appearing 3+ times:
      ''             //     s is invalid, so append nothing
    :                //   else:
      s              //     append s
  :                  // else:
    g(m < n)         //   initial call to g with q set if m < n

```

# Answer
> 4 votes
# Retina, 69 bytes

```
.+
*
Y`\_`l
^
<$'>
/>./+Lrv$`(?(2)(\3.+))<(.+)?(\w)
$%`$1$3<$2$%'
<>

```

Try it online! Might work up to `n=26`. Explanation:

```
.+
*
Y`\_`l

```

Generate the first `n` lowercase letters.

```
^
<$'>

```

Make a duplicate set, and wrap the first set in `<` and `>`.

```
Lrv$`(?(2)(\3.+))<(.+)?(\w)
$%`$1$3<$2$%'

```

For each string, make new strings by either a) moving the first character from the first set or b) moving a character from the second set that was moved from the first set but not in the immediately previous iteration.

```
/>./+`

```

Repeat until the second set is empty for all strings.

```
<>

```

Remove the `<>` markers.

# Answer
> 4 votes
# Jelly,  ~~18~~  15 bytes

```
Øaḣx2Œ!Q⁼Ɲ;QƊÐṂ

```

A monadic Link that accepts \\$n\\$ and yields a list of lists of characters.

**Try it online!**

### How?

```
Øaḣx2Œ!Q⁼Ɲ;QƊÐṂ - Link: n
Øa              - alphabet
  ḣ             - head to index {n}
   x2           - times two
     Œ!         - all permutations
       Q        - deduplicate
             ÐṂ - keep those {P in those permutations} minimal under:
         Ɲ      -   to neighbouring pairs {P}:
        ⁼       -     equal?
           Q    -   deduplicate {P}
          ;     -   concatenate ...e.g. 'accbab' -> [0,1,0,0,0,'a','c','b']
                          (minimal entries would be [0,0,0,..,0,'a','b','c',...])

```

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

```
f=(n,z=[],L)=>[...n?f(n-1,[c=(n+9).toString(36),...z],c+[L]):z+z?[]:[L],...z.flatMap(t=>t==L[0]?[]:f(n,z.filter(y=>y!=t),t+L))]

```

Try it online!

Its `print` version is 116 bytes

# Answer
> 3 votes
# Python3, 323 bytes:

```
def B(a,b):
 d={}
 for a,b in zip(a,b):
  if b not in(T:=d.get(a,[])):d[a]={*T,b}
 return d
def F(n):
 r,q=[],[['abcdefghijklmnopqrstuvwxyz'[:n]*2,'']]
 for s,k in q:
  if''==s:
   if all(any(len(K)>1for K in B(j,k).values())for j in r):r+=[k]
  for i,a in enumerate(s):q+=[[s[:i]+s[i+1:],k+a]]*(k==''or a!=k[-1])
 return r

```

Try it online!

# Answer
> 3 votes
# Nekomata, 18 bytes

```
r:,↕ũ∆Zç∫:ux=¿97+H

```

Attempt This Online!

```
r:,↕ũ∆Zç∫:ux=¿97+H
r:,↕ũ               Find a list of length 2n that contains each number from 0 to n exactly twice
r                       Range from 0 to input
 :                      Duplicate
  ,                     Join
   ↕ũ                   Permutation
     ∆Zç∫           Check that no two adjacent values are equal
     ∆                  Delta
      Z                 Check no values are 0
       ç                Prepend 0
        ∫               Cumsum to get back to the original list
         :ux=¿      Check that the list is in the standard order
         :              Duplicate
          u             Uniquify
           x=           Check that the result is [0, 1, 2, ..., n]
             ¿          If so, get back to the original list
              97+H  Convert to string
              97+       Add 97
                 H      Convert from codepoints to string

```

# Answer
> 3 votes
# Python 3.10, 204 bytes

```
from itertools import*
def f(n):z,F='abcdefghij'[:n],frozenset;q=F();return[x for x in permutations(z*2)if all(a!=b for a,b in pairwise(x))and q!=(q:=q|{F(F(I for I,c in enumerate(x)if c==d)for d in z)})]

```

Testable as `f(n)`, outputs list of tuples. Each tuple contains "characters" (strings of length 1) and is thus equivalent to a string.

# Python 3.8 (pre-release), 205 bytes

`itertools.pairwise` was added in 3.10 and is not supported by TIO, so here's another version:

```
from itertools import*
def f(n):z,F='abcdefghij'[:n],frozenset;q=F();return[x for x in permutations(z*2)if all(a!=b for a,b in zip(x,x[1:]))and q!=(q:=q|{F(F(I for I,c in enumerate(x)if c==d)for d in z)})]

```

Try it online!

Works by simple bruteforce, will likely time out for \\$n \ge 6\\$.

# Answer
> 2 votes
# 05AB1E, 17 (or 16) bytes

```
L€DœÙʒDüÊ*ÙāQ}.bl

```

Output as a list of lists.

: Could be -1 byte removing the trailing `l` by outputting in uppercase.

Try it online or verify both test cases.

**Explanation:**

```
L        # Push a list in the range [1, (implicit) input-integer]
 €D      # Duplicate each value within the list
   œ     # Get all permutations of this list
    Ù    # Uniquify it
ʒ        # Filter this list of lists by:
 D       #  Duplicate the current list
  ü      #  For each overlapping pair:
   Ê     #   Check that they are NOT equal
    *    #  Multiply the values in the lists at the same positions
         #  (removing the trailing item, but this doesn't matter)
     Ù   #  Uniquify it
      ā  #  Push a list in the range [1,length] (without popping)
       Q #  Check whether the two lists are the same
}.b      # After the second filter: convert all integers to their 1-based alphabetic
         # uppercase letters
   l     # Convert those to lowercase
         # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Perl 5, 161 bytes

```
sub{$_=substr(abcdefghij,0,pop)x2;my%r;1while s/^(.*)(.)(.*)(.)(??{($t="$1$4$3$2$'")=~m,(.)(\1|.*(.).*\3(??{$1lt$3})),||$r{$t}++;$s{$t}++||''})/$1$4$3$2/;keys%r}

```

Try it online!

```
$f=
sub{
  $_=substr(abcdefghij,0,pop)x2;         #set $_ to first n chars times 2
  my%r;                                  #init %r where results are collected
  1 while                                #repeat while untested perms exists
    s/                                   #permute $_ by swap of two random chars
    ^(.*)(.)(.*)(.)
       (??{
        $t="$1$4$3$2$'";                 #test new permutation in $t
        $t=~
        m,(.)(\1|.*(.).*\3(??{$1lt$3})), #two of same not neighbors and
                                         #no higher char before two equal lower
        ||                               #if no error then tests passed and...
        $r{$t}++;                        #register current perm $t as a result
        $s{$t}++||''                     #register current perm as seen/done
       })
    /$1$4$3$2/x;                         #if not seen change $_ to new perm
  keys%r                                 #return registered results
}
;

```

# Answer
> 1 votes
# Scala, ~~528~~ 521 bytes

Port of @Ajax1234's Python answer in Scala.

**521 bytes, it can be golfed much more.**

---

Golfed version. Try it online!

```
def b(a:String,b:String)=(Map.empty[Char,Set[Char]]/:a.zip(b)){(d,p)=>d+(p._1->(d.getOrElse(p._1,Set.empty)+ p._2))}
def f(n:Int)={val q=scala.collection.mutable.Queue[(String,String)]((Array.fill(2)("abcdefghijklmnopqrstuvwxyz".substring(0,n)).mkString,""));var r=List[String]();while(q.nonEmpty){val(s:String,k:String)=q.dequeue;if(s.isEmpty){if(r.forall(S=>b(S,k).values.exists(_.size>1))){r=k::r}}else{for(i<-s.indices){if(k.isEmpty||s(i)!=k.last){q.enqueue((s.substring(0,i)+s.substring(i+1),k+s(i)))}}}};r.reverse;}

```

Ungolfded version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(findSequences(2))
    println(findSequences(3))
    println(findSequences(4))
  }

  def buildDictionary(a: String, b: String): Map[Char, Set[Char]] = {
    a.zip(b).foldLeft(Map.empty[Char, Set[Char]]) { (dict, pair) =>
      dict + (pair._1 -> (dict.getOrElse(pair._1, Set.empty) + pair._2))
    }
  }

  def findSequences(n: Int): List[String] = {
    var initialString = Array.fill(2)("abcdefghijklmnopqrstuvwxyz".substring(0,n)).mkString
    val queue = scala.collection.mutable.Queue[(String, String)]((initialString, ""))
    var result = List[String]()

    while(queue.nonEmpty) {
      val (s: String, k: String) = queue.dequeue()

      if(s.isEmpty) {
        if(result.forall(sub => buildDictionary(sub, k).values.exists(_.size > 1))) {
          result = k :: result
        }
      } else {
        for(i <- s.indices) {
          if(k.isEmpty || s(i) != k.last) {
            queue.enqueue((s.substring(0, i) + s.substring(i+1), k + s(i)))
          }
        }
      }
    }

    result.reverse
  }
}

```

---
Tags: code-golf
---


title: Decode Chess Move

text:
# Question
Title: Decode Chess Move
As the title says, given a valid chess move in algebraic notation, produce the string describing the move.

**Example:**

```
fxg8=Q+  -> Pawn takes g8 promotes to Queen check
Bb7#     -> Bishop to b7 mate

```

Here is a list of all the keywords and their respective notation

```
R     -> Rook             x   -> takes
N     -> Knight           +   -> check
B     -> Bishop           #   -> mate
Q     -> Queen            =   -> promotes to
K     -> King             0-0 -> short castle
0-0-0 -> long castle

```

---

*Note: Long and short castle can be represented with either number `0` or letter `O` uppercase. You can choose any you'd like.*

***From wiki:** Both algebraic notation and descriptive notation indicate kingside castling as 0-0 and queenside castling as 0-0-0 (using the digit zero). Portable Game Notation and some publications use O-O for kingside castling and O-O-O for queenside castling (using the letter O) instead*

---

Piece moves format follows `{Piece name} to {square}` Moves without a piece are consider pawn moves. Example:

```
g4  -> Pawn to g4
Nh7 -> Knight to h7

```

For ambiguous moves, input will specify both departure rank and file. Example:

```
Rh8b8 -> Rook h8 to b8
Qb3e6 -> Queen b3 to e6

```

---

## Input

String with a valid chess move in algebraic notation

## Output

String describing the move (Upper case or Lower case is ok)

---

## Test Cases

```
fxg8=Q+  -> Pawn takes g8 promotes to Queen check
Bb7#     -> Bishop to b7 mate
0-0      -> short castle
0-0+     -> short castle check
0-0-0#   -> long castle mate
Rxg8     -> Rook takes g8
fxe6     -> Pawn takes e6
Ra8g8    -> Rook a8 to g8
Nb3#     -> Knight to b3 mate
a8=B     -> Pawn to a8 promotes to Bishop
Ra8xg8   -> Rook a8 takes g8

```

# Answer
# JavaScript (ES6), 206 bytes

Takes some inspiration from Neil's Retina answer. But in the end, this is quite different.

```
s=>[/O-O-/,/O-/,/.\d/g,/to (?=.*o)/,/x to/,..."=+#ORKBQN",/^.? /].map((r,j)=>s=s.replace(r,`long/short/ to $&// takes/ promotes to / check/ mate/ castle/Rook/King/Bishop/Queen/Knight/Pawn `.split`/`[j]))&&s

```

Try it online!

### Decoding examples

```
e4
 to e4
Pawn to e4

```

```
fxg8=Q+
fx to g8=Q+
f takes g8=Q+
f takes g8 promotes to Q+
f takes g8 promotes to Q check
f takes g8 promotes to Queen check
Pawn takes g8 promotes to Queen check

```

```
Ra8g8
R to a8 to g8
R a8 to g8
Rook a8 to g8

```

---

# Retina 0.8.2, 144 bytes

*-4 bytes thanks to @Neil*

The same logic back-ported to Retina.

```
O-O-
long
O-
short
.\d
 to $&
-2`to

x to
 takes
=
 promotes to
\+
 check
#
 mate
O
 castle
R
Rook
K
King
B
Bishop
Q
Queen
N
Knight
^.?
Pawn

```

Try it online!
> 6 votes

# Answer
# Ruby `-p`, 249 bytes

`-p` flag loops over input, modifies it with these two fat regex functions, and spits it back out.

```
sub(/(^[a-g]?)?(.\d)?(x)?(?=.\d)|O(-O)+/){$4?%w(short long)[~/$//5]+' castle':"#{$1&&?P}#{' '+$2if$2} #{$3?:takes:'to'} "}
gsub(/[#+=B-R]/){|m|m[/\W/]?' '+%w(mate promotes\ to\  _ check)[m.ord%5]:%w(King Queen Rook Bishop Pawn).find{_1[m]}||:Knight}

```

Attempt This Online!

### Partially ungolfed

sub(/(^[a-g]?)?(.\d)?(x)?(?=.\d)/) { # Replace the part that says which piece moves where
 "#{
    $1&&?P                           # 'P' (Pawn) if group 1 is present
                                     #  (matches if input starts with /[a-g]x/ or /.\d/)
   }#{
    ' '+$2if$2                       # Group 2 with leading space if present
                                     #  (for Qb3e6 -> Queen b3 to e6 etc.)
   } #{
    $3?:takes:'to'                   # 'takes' if group 3 (x) is present, else 'to'
                                     #  (uses label notation :takes to save bytes)
   } "
}
sub(/O(-O)+/) { # Replace castling notation (original program checks for group 4)
   %w(short long)                    # ['short', 'long']
                 [
                  ~/$/               # Index of end of input (3-4 if O-O, 5-6 if O-O-O)
                      /5]            # Divide by 5 to get correct index for short vs long
    + ' castle'                      # Add the ' castle' part
}
gsub(/[#+=B-R]/) {|m|                # Match checkmate, check, promotes, pieces
   m[/\W/]?                          # If non-letter (checkmate, check, promote)
    ' '+                             # Leading space
    ['mate','promotes to ', nil, 'check'][m.ord%5]
                                     # Match the corresponding phrase by using mod 5
                                     # '#' -> 0, '=' -> 1, '+' -> 3

  :                                  # Otherwise (if letter)
    %w(King Queen Rook Bishop Pawn).find{_1[m]}
                                     # Find the piece that has that letter
    ||:Knight                        # If none found, it's a Knight (N can't match)
}
```
</code></pre>
> 5 votes

# Answer
# Charcoal, ~~165~~ 146 bytes

```
ＦＳ≡ιx≔⊞ＯΦυ⊖Ｌκtakesυ-≔⟦⎇⊖Ｌυlong¦short⟧υ¿№βι≔⊞Ｏ⁺∨⁻υ⟦to⟧⟦Pawn⟧…⟦to⟧¬№υtakesιυ¿Σι⊞υ⁺⊟υι⊞υ§⪪”↶.⭆～»¤πη‽q∕¶lj,⊙↥⟲Qmº5σ¡²JＮ¤εlθw(LθΦG▶⁵@W｜]”¶⌕KQRBNO+#ι⪫υ

```

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

```
ＦＳ≡ι

```

Loop over the characters of the input string.

```
x≔⊞ＯΦυ⊖Ｌκtakesυ

```

For `x`, push `takes` to the result, but remove any bare letters (which will be the source file of a pawn capture).

```
-≔⟦⎇⊖Ｌυlong¦short⟧υ

```

For `-`, change `castle` to `short` but `short castle` to `long`. (The `castle` comes from the `O` below.)

```
¿№βι≔⊞Ｏ⁺∨⁻υ⟦to⟧⟦Pawn⟧…⟦to⟧¬№υtakesιυ

```

For other lower case letters, this might be the source or the destination file. Remove any existing `to` and add a new `to`, unless there is a `takes` in the string. Then push the file to the result.

```
¿Σι⊞υ⁺⊟υι

```

For digits, append the rank to the file.

```
⊞υ§⪪”↶.⭆～»¤πη‽q∕¶lj,⊙↥⟲Qmº5σ¡²JＮ¤εlθw(LθΦG▶⁵@W｜]”¶⌕KQRBNO+#ι

```

For other characters, push the piece name or notation to the result.

```
⪫υ

```

Join the collected words on spaces.
> 3 votes

# Answer
# Retina 0.8.2, ~~176~~ ~~172~~ 171 bytes

```
(([A-Z])(..)?|(.?))(x)?(.\d)
$2$#4$*P $3$#3$* to$5 $6
ox
akes
O-O-
long
O-
short
O
 castle
#
 mate
\+
 check
=
 promotes to
K
King
Q
Queen
R
Rook
B
Bishop
N
Knight
P
Pawn

```

Try it online! Link includes test cases. Explanation:

```
(([A-Z])(..)?|(.?))(x)?(.\d)
$2$#4$*P $3$#3$* to$5 $6

```

Identify the piece or pawn being moved, whether there is a disambiguation square for the piece, and its destination.

```
ox
akes

```

Fix up the case of a capture.

```
O-O-
long
O-
short
O
 castle

```

Process castling.

```
#
 mate
\+
 check
=
 promotes to

```

Process other symbols.

```
K
King
Q
Queen
R
Rook
B
Bishop
N
Knight
P
Pawn

```

Expand the piece names.

Edit: Saved 4 bytes thanks to @Arnauld. Saved 1 byte thanks to @ValueInk.
> 2 votes

# Answer
# C# .NET console app, 333 bytes

Assumes `using System; using System.Text.RegularExpressions;`

```
string m=Regex.Replace(args[0],"(?<!x)[a-h](?!.*[x|a-h])","t${0}"),r=m[0]>96?"Pawn ":m[0]<49?(m.Length>4?"long":"short")+" castle ":"";foreach(var c in m){int i="-0RNBQKx+#=t".IndexOf(c);r+=",,,Rook ,Knight ,Bishop ,Queen ,King ,takes ,check,mate,promotes to ,to ".Split(',')[i+1];if(c!=m[0]&i<0)r+=c+(c<57?" ":"");}Console.Write(r);

```

## Commented

```
// add a 't' to the move string wherever "to" is needed
string m = Regex.Replace(args[0], "(?<!x)[a-h](?!.*[x|a-h])", "t${0}"),

// start with 'Pawn' if the first character is a file, to or takes
    r = m[0] > 96 ? "Pawn "

// decode castles now so we can ignore -,0 later
    : m[0]<49 ? (m.Length>4 ? "long" : "short") + " castle " : "";

// iterate through the move string
foreach (var c in m)
{
    // map each code to a word, with space where needed
    // 0,- map to empty string
    int i = "-0RNBQKx+#=t".IndexOf(c);
    r += ",,,Rook ,Knight ,Bishop ,Queen ,King ,takes ,check,mate,promotes to ,to ".Split(',')[i + 1];

    // anything that doesn't map is assumed to be a square reference and added to the result
    // except if it's the first character because if it's not x or t then it must be a file with no rank.
    // also add a space if it's a digit
    if (c != m[0] & i < 0)
        r += c + (c < 57 ? " " : "");
}

Console.Write(r);

```
> 0 votes

---
Tags: code-golf, chess
---


title: Check if words are isomorphs

text:
# Question
Title: Check if words are isomorphs
Two words are *isomorphs* if they have the same pattern of letter repetitions. For example, both `ESTATE` and `DUELED` have pattern `abcdca`

```
ESTATE
DUELED

abcdca

```

because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching `E <-> D, S <-> U, T <-> E, A <-> L`.

Write code that takes two words and checks whether they are isomorphs. Fewest bytes wins.

**Input:** Two non-empty strings of capital letters `A..Z`. If you wish, you can take these as a collection of two strings or as a single string with a separator.

**Output:** A consistent Truthy value for pairs that are isomorphs, and a consistent Falsey value if they are not. Strings of different lengths are valid inputs that are never isomorphs.

**Test cases:**

*True:*

```
ESTATE DUELED
DUELED ESTATE
XXX YYY
CBAABC DEFFED
RAMBUNCTIOUSLY THERMODYNAMICS
DISCRIMINATIVE SIMPLIFICATION

```

*False:*

```
SEE SAW
ANTS PANTS
BANANA SERENE
BANANA SENSES
AB CC
XXY XYY
ABCBACCBA ABCBACCAB
ABAB CD

```

Feel free to add more test cases you find useful.

**Leaderboard**

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
var QUESTION_ID=50472;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```

# Answer
# J, 4 bytes

```
-:&=

```

Usage

```
   'THERMODYNAMICS' (-:&=) 'RAMBUNCTIOUSLY'  NB. parens are optional
1

```

Explanation

* `=` with 1 argument creates an equality-table comparing the elements of the input and its nub.

```
='ESTATE' gives the binary matrix

= | E S T A T E
--+------------
E | 1 0 0 0 0 1
S | 0 1 0 0 0 0
T | 0 0 1 0 1 0
A | 0 0 0 1 0 0

```
* `-:` with 2 arguments checks their equality (like `==` generally does). This works for different size matrices (or even different types) too.
* `f&g` applies g to both input separately and then applies f to the two results together so `x f&g y == f(g(x), g(y))`.
* So in our case we compare the two equality-tables.

Try it online here.
> 98 votes

# Answer
# K, 5 bytes

This has a delightfully elegant solution in K!

```
~/=:'

```

The "group" operator (monadic `=`) creates precisely the signature we want for word isomorphism; gathering vectors of the indices of each element of a vector, with the groups ordered by appearance:

```
  ="ABBAC"
(0 3
 1 2
 ,4)

  ="DCCDF"
(0 3
 1 2
 ,4)

```

Taking a pair of strings as a vector, we just need to apply group to each element (`=:'`) and then reduce with "match" (`~`), the deep-equality operator:

```
  ~/=:'("RAMBUNCTIOUSLY";"THERMODYNAMICS")
1
  ~/=:'("BANANA";"SERENE")
0

```
> 38 votes

# Answer
# Python 2, 41 bytes

```
f=lambda a,b:map(a.find,a)==map(b.find,b)

```
> 21 votes

# Answer
# CJam, 9 bytes

```
r_f#r_f#=

```

Prints `1` if the words are isomorphs and `0` if they're not.

Try it online in the CJam interpreter.

### How it works

```
r    e# Read a whitespace separated token from STDIN.
_    e# Push a copy.
f#   e# Get the indexes of all characters from the first copy in the second.
r_f# e# Repeat for the second word.
=    e# Check for equality.

```
> 13 votes

# Answer
# JavaScript, ES7, ~~62 55 54 52~~ 51 bytes

```
f=(x,y,g=z=>[for(i of z)z.search(i)]+0)=>g(x)==g(y)

```

The logic is simple. I simply convert both the inputs into their corresponding character index values, convert that array into string and compare.

```
f=(x, y,                  // Create a function named f which takes two arguments x and y
   g=                     // There is a third default argument to f which equals to
     z=>                  // and arrow function which takes argument z
     [                    // Return this array which is created using array comprehension
      for(i of z)         // For each character of z
      z.search(i)         // Use the index of that character in z in place of the character
     ]+0                  // And finally type cast that array to a string
                          // Here, the array elements are automatically joined by a ','
                          // and appended by a 0.
                          // Its funny how JS type casts Array + Number to a string
   )=>                    // Now the body of function f starts
      g(x)==g(y)          // It simply returns if index map of x equals index map of y

```

Try the above code using the snippet below.

```
f=(x,y,g=z=>[for(i of z)z.search(i)]+0)=>g(x)==g(y)

// for cross browser testing, here is a slightly modified ES5 version of above function

if (!f) {
  function f(x, y) {
    function g(z) {
      var Z = [];
      for (var i = 0; i < z.length; i++) {
        Z[i] = z.search(z[i])
      }
      return Z + 0;
    }
    return g(x) == g(y);
  }
}

B.onclick=function() {
  O.innerHTML = f(D.value, E.value);

};
```

```
<pre>f(<input id=D />,<input id=E />)</pre><button id=B >Run</button>
<br>
<output id=O />
```

*2 bytes saved thanks to @edc65*
> 10 votes

# Answer
# Bash + coreutils, 38

```
[ `tr $@<<<$1``tr $2 $1<<<$2` = $2$1 ]

```

Note we are using the usual shell idea of truthy/falsy here - zero means SUCCESS or TRUE and non-zero means error or FALSE:

```
$ for t in "ESTATE DUELED" "DUELED ESTATE" "XXX YYY" "CBAABC DEFFED" "RAMBUNCTIOUSLY THERMODYNAMICS" "DISCRIMINATIVE SIMPLIFICATION" "SEE SAW" "ANTS PANTS" "BANANA SERENE" "BANANA SENSES" "AB CC" "XXY XYY" "ABCBACCBA ABCBACCAB"; do
> ./isomorph.sh $t
> echo $t $?
> done
ESTATE DUELED 0
DUELED ESTATE 0
XXX YYY 0
CBAABC DEFFED 0
RAMBUNCTIOUSLY THERMODYNAMICS 0
DISCRIMINATIVE SIMPLIFICATION 0
SEE SAW 1
ANTS PANTS 1
BANANA SERENE 1
BANANA SENSES 1
AB CC 1
XXY XYY 1
ABCBACCBA ABCBACCAB 1
$

```
> 9 votes

# Answer
# Haskell, ~~33~~ 29

# EDIT:

this is way too late, but i found this improvement using applicatives, that were added to prelude only in march 2015.

```
s%k=g s==g k
g s=(==)<$>s<*>s

```

Old version:

```
s%k=g s==g k
g s=[a==b|a<-s,b<-s]

```

the checking function is `(%)`

this works by generating for each string its "equality record": for each two indices i j, it records whether they have equal characters. the record is ordered so that the record for two indices i, j is always in the same place\* and therefore checking the equality of the records would return whether or not the strings have the same pattern.

for example, the equality record of "ABC" is `[1,0,0,0,1,0,0,0,1]` (1 for true, 0 for false) - there is `True` where any index is compared with itself. anywhere else is a false. (skipping these checks might be more efficient, but is harder in terms of golfng)

*if the strings are of the same length. otherwise it returns false just because the records are of different lengths
> 8 votes

# Answer
# Haskell, ~~45~~ 41 bytes

```
h l=map(`lookup`zip l[1..])l
x!y=h x==h y

```

Returns `True` or `False`, e.g `"ESTATE" ! "DUELED"` -\> `True`.

Uses the map-char-to-first-index method as seen in many other answers. Association lists come in handy, because earlier entries trump. `"aba"` becomes `[(a,1),(b,2),(a,3)]` where `lookup` always fetches `a` -\> `1`.

Edit: @Mauris found 4 bytes to save.
> 6 votes

# Answer
## R, 78

```
function(x,y)identical((g=function(z)match(a<-strsplit(z,"")[[1]],a))(x),g(y))

```

De-golfed:

```
word_to_num <- function(word) {
   chars <- strsplit(word,"")[[1]]
   match(chars, chars)
}
are_isomorph <- function(word1, word2) identical(word_to_num(word1),
                                                 word_to_num(word2))

```
> 6 votes

# Answer
# Brainfuck, ~~169~~ ~~168~~ ~~162~~ ~~144~~ ~~140~~ ~~131~~ 130

Compatible with Alex Pankratov's bff (brainfuck interpreter used on SPOJ and ideone) and Thomas Cort's BFI (used on Anarchy Golf).

The expected input is two strings separated by a tab, with no newline after the second string. The output is `1` for isomorphs and `0` for non-isomorphs, which is convenient for checking results visually, although not the shortest option. (**Update:** shorter version with `\x01` and `\x00` as output and `\x00` as separator at the bottom of the answer.)

Demonstration on ideone.

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

```

This problem turns out to be very nice for brainfuck.

The basic idea with indexing is to go backwards from the end of the current string prefix. If the character has not previously occurred, we can take the length of the string prefix. For example:

```
STATES
123255

```

The indexing in the code is actually slightly different but uses the same principle.

The memory layout is in blocks of 5:

```
0 0 0 0 0 0 c 0 i p 0 c 0 i p 0 c 0 i p 0 0 0 0

```

`c` stands for character, `i` for index, and `p` for previous (index). When the first string is being processed, all the `p` slots are zero. The cell to the left of `c` is used to hold a copy of the current character that we are trying to find the index of. The cell to the left of the current `i` is used to hold a `-1` for easy pointer navigation.

There are many conditions that need to be considered carefully. At the end, we check for isomorphs by comparing the `(i,p)` pairs, and we reach the cluster of zero cells to the left of the leftmost `(i,p)` pair if and only if the strings are isomorphs. Here is a commented version of the code to make it easier to follow:

```
,+
[                       while there is input
  -
  ---------
  >+<                   increment char (adjust later)
  [                     if not tab
    >>-<                set navigation flag
    [                   loop to find index
      <                 travel to copy
      [
        >+<             restore char
        <<<<-<+>>>>>-   compare chars and create copy
      ]
      ++[->+]           travel between navigation flags
      ->+[+<-]          increment index by 2 and go back
      >[<<<<]           proceed if not fallen off string
      <                 compare chars
    ]
    <[>+<-]             restore char (or no op)
    +[->+]              go back to navigation flag
    <->                 adjust char
    >>>                 alignment
  ]
  >
  [                     if tab
    [[-]<<<<<]          erase chars and go to beginning
    >>>>                alignment
  ]
  <,+
]
>>>+>+                  check string lengths and start loop
[
  [<->-]                compare indices
  <[>>>>>]              realign if not equal
  <<<<                  proceed
]
-<[>]                   cell to left is zero iff isomorphs
+++++++[<+++++++>-]
<.

```

**Update:**

Here is a version that prints `\x01` for isomorphs and `\x00` for non-isomorphs. This is arguably a more accurate interpretation of Truthy and Falsey for brainfuck, because of the way `[` and `]` work. The only difference is at the very end.

Additional: Now using `\x00` as a separator to save 10 bytes.

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

```
> 6 votes

# Answer
# Ruby, 83 bytes

```
t=->x{y=0;z=?`;x.gsub!(y[0],z.succ!)while y=x.match(/[A-Z]/);x};f=->a,b{t[a]==t[b]}

```

It's a function `f` that takes two arguments and returns `true` or `false`.

Explanation:

```
test = -> str {
    y = nil  # we're just initializing this; it doesn't matter to what
             # this is the variable we use to store the `match' result
    z = '`'  # backtick is the ASCII character before `a'
    while y = str.match(/[A-Z]/) do  # while there is an uppercase letter in str
        str.gsub!(y[0], z.succ!)  # replace all instances of the uppercase letter
                                  # with the next unused lowercase letter
    end
    str  # return the new string
}
# self-explanatory
f=->a,b{test[a]==test[b]}

```
> 5 votes

# Answer
# JavaScript (ES6), 62

Using an aux function `h` that maps each word to an array containing the position of each letter in the word, for instance: PASS -\> \[1,2,3,3\]. Return true if the function `h` applied the two words gives the same result.

```
f=(a,b,h=w=>0+[for(c of(n=k=[],w))k[c]=k[c]||++n])=>h(b)==h(a)

// TEST

;[
// True
 ['ESTATE','DUELED']
,['DUELED','ESTATE']
,['XXX','YYY']
,['CBAABC','DEFFED']
,['RAMBUNCTIOUSLY','THERMODYNAMICS']
,['DISCRIMINATIVE','SIMPLIFICATION']

// False:

,['SEE','SAW']
,['ANTS','PANTS']
,['BANANA','SERENE']
,['BANANA','SENSES']
,['XXY','XYY']
,['ABCBACCBA','ABCBACCAB']
]
.forEach(t=>(f(t[0],t[1])?OK:KO).innerHTML+=t+'\n')
```

```
Ok<br>
<pre id=OK></pre><br>
KO<br>
<pre id=KO></pre>
```
> 5 votes

# Answer
# Java, 107

```
(s,t)->java.util.Arrays.equals(s.chars().map(s::indexOf).toArray(),t.chars().map(t::indexOf).toArray())

```

Maps each character of `s` and `t` to its location, and checks for equality.

Expanded:

```
class Isomorphs {
    public static void main(String[] args) {
        java.util.function.BiFunction<String, String, Boolean> f =
            (s, t) -> java.util.Arrays.equals(
                                              s.chars().map(s::indexOf).toArray(),
                                              t.chars().map(t::indexOf).toArray()
                                             )
           ;
        System.out.println(f.apply("XXY", "XYY"));
    }
}

```
> 5 votes

# Answer
# Python 3, 85 bytes

```
f=lambda a,b:''.join(map(lambda g:dict(zip(a,b))[g],a))==b
g=lambda a,b:f(a,b)&f(b,a)

```
> 4 votes

# Answer
# Pyth, 9 bytes

```
qFmmxdkdQ

```

Takes input in the following form:

```
"ESTATE", "DUELED"

```

If that is not acceptable, the following code is 10 bytes:

```
qFmmxdkd.z

```

and uses this input form:

```
ESTATE
DUELED

```

Uses the index of char in string representation.
> 4 votes

# Answer
# Matlab, 50 bytes

```
f=@(s,t)isequal(bsxfun(@eq,s,s'),bsxfun(@eq,t,t'))

```

The function is defined as anonymous to save some space.

Example:

```
>> f=@(s,t)isequal(bsxfun(@eq,s,s'),bsxfun(@eq,t,t'));
>> f('ESTATE','DUELED')
ans =
     1
>> f('ANTS','PANTS')
ans =
     0

```
> 4 votes

# Answer
# Octave, 26 bytes

```
@(s,t)isequal(s==s',t==t')

```
> 4 votes

# Answer
# Ruby, 31 bytes

```
->a{!!a.uniq!{|s|s.tr s,'a-z'}}

```

A Proc that takes an array of strings and checks whether any are isomorphic to each other. `tr s,'a-z'` with these arguments normalizes a string `s` by replacing each letter with the nth letter in the alphabet, where `n` is the greatest index with which that letter appears in the string. For example, `estate` becomes `fbedef`, as does `dueled`.
> 4 votes

# Answer
# APL (Dyalog), ~~5~~ 4 bytes

-1 thanks to ngn's hint.

Anonymous tacit prefix function which takes a list of two strings as argument.

```
≡.⍳⍨

```

Try it Online!

This is an inner product, but instead of the usual `+` and `×` it uses

identicalness

`.` and

the **ɩ**ndex (the first occurrence of each element)

with the entire two-element list of words used as both arguments

If we call the words `A` and `B`, then we can derive the previous solution as follows:

`≡.⍳⍨ A B`
`A B ≡.⍳ A B`
`(A⍳A) ≡ (B⍳B)`
`(⍳⍨A) ≡ (⍳⍨B)`
`≡/ ⍳⍨¨ A B`

### Previous solution

Anonymous tacit prefix function which takes a list of two strings as argument.

```
≡/⍳⍨¨

```

Try it online!

identicalness

`/` across

the **ɩ**ndex (the first occurrence of each element…)

selfie (…in itself)

`¨` of each
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
εæδË}Ë

```

Try it online!

Takes input as a list: `['ESTATE', 'DUELED']`

**Explanations:**

```
    εæδË}Ë   Full program
    ε        Apply on each
     æ         Powerset
      δË       For each generated substring: 1 if all equal, 0 otherwise
        }    End for each
         Ë   1 if all equal, 0 otherwise

```
> 4 votes

# Answer
# Mathematica, 46 bytes

```
Equal@@Values@*PositionIndex/@Characters@{##}&

```
> 3 votes

# Answer
# Ruby, 50 bytes

30 bytes shorter ruby code. Written before I took a look at the solutions, checks for each character of both strings whether the index of that character's first occurence matches; ie. transforms a string to its normalized form `01121` etc and compares those.

```
->x,y{g=->z{z.chars.map{|c|z=~/#{c}/}};g[x]==g[y]}

```

Test cases on ideone As an additional bonus, this breaks ideone's code highlighting.
> 3 votes

# Answer
## PCRE, 84 bytes

```
^((.)(?=.+ (\3.|)(.))(?=((?=(\2|)?+.* \3\4(\7?(?(?=.*+\6)(?!\4).|\4))).)+ ))+. \3..$

```

Subject should be two space-separated words, as in the OP. Here's a cursory explanation:

> For each letter X in the first word:
>
> > Look ahead to the second word and establish back references to recall how far along we are as well as the letter Y in the second word corresponding to X.
> >
> > For each letter Z past the current position in the first word:
> >
> > > Establish similar back references as above.
> > >
> > > Look ahead to the corresponding letter in the second word and check if Z = X then match a Y, otherwise match a letter that isn't Y.
>
> This iteration can end once we've matched up until the penultimate letter in the first word. At this point, since no further validation is necessary, all that remains is to test that the words are of equal length (the back reference containing accumulating substrings of the second word is always behind by 1 letter).
> 3 votes

# Answer
# Jelly, 4 bytes

```
ĠṢ)E

```

Try it online!

Another 4 byte version

## How they work

```
ĠṢ)E - Main link. Takes [A, B] on the left
  )  - Over each string S in the input:
Ġ    -   Group the indices of S by it's values
 Ṣ   -   Sort the lists of indices
   E - Are both equal?

ẹⱮ)E - Main link. Takes [A, B] on the left
  )  - Over each string S in the input:
 Ɱ   -   For each character C in S:
ẹ    -     Get the indices of C in S
   E - Are both equal?

```
> 3 votes

# Answer
# Vyxal, 7 bytes

```
ƛUẊv≈;≈

```

Try it Online!

```
ƛ    ;≈ # Same upon...
  Ẋ     # Cartesian product of...
 U      # Uniquified value
        # And (implicit) value
   v≈   # For each, same?

```
> 3 votes

# Answer
# BQN, 3 bytesSBCS

```
≡○⊐

```

Run online!

The builtin *Classify*  gets the pattern of letter repetitions for a given string as a vector of non-negative integers. All that's left to do is to compare the two results for equality.

```
⊐ "ESTATE"
# ⟨ 0 1 2 3 2 0 ⟩
⊐ "DUELED"
# ⟨ 0 1 2 3 2 0 ⟩
(⊐ "ESTATE") ≡ (⊐ "DUELED")
# 1
"ESTATE" ≡○⊐ "DUELED"
# 1

```
> 3 votes

# Answer
# Husk, 5 bytes

```
¤=´×=

```

Try it online!

### Explanation

```
       -- implicit input A, B (strings aka character lists)       | "ab" "12"
¤=     -- apply the following function to A & B, then compare:    | [1,0,0,1] == [1,0,0,1] -> 1
  ´×   --   Cartesian product with itself under                   | ["aa","ba","ab","bb"] ["11","21","12","22"]
    =  --   equality                                              | [ 1  , 0  , 0  , 1  ] [ 1  , 0  , 0  , 1  ]

```
> 2 votes

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

```
Ë´Ṫ=

```

Try it online!

-1 byte from Leo using ბიმო's answer.

## Explanation

```
Ë´Ṫ=
Ë    check if all the elements are equal by the following predicate:
 ´Ṫ  cartesian product with self
   = by equality

```
> 2 votes

# Answer
# Thunno 2, 6 bytes

```
ıʠ€ạ;ạ

```

Try it online!

#### Explanation

```
ıʠ€ạ;ạ  # Implicit input
ı   ;   # Map:
 ʠ      #  Powerset of the string
  €     #  For each one:
   ạ    #   Check if all equal
     ạ  # Check if all equal
        # Implicit output

```
> 2 votes

# Answer
# Nekomata \+ `-e`, 5 bytes

```
ŤuŤᵐů

```

Attempt This Online!

Takes input as a list of two strings.

```
ŤuŤᵐů
Ť       Transpose; ["ESTATE","DUELED"] -> ["ED","SU","TE","AL","TE","ED"]
 u      Uniquify; ["ED","SU","TE","AL","TE","ED"] -> ["ED","SU","TE","AL"]
  Ť     Transpose; ["ED","SU","TE","AL"] -> ["ESTA","DUEL"]
   ᵐů   Check that neither string contains duplicate characters

```
> 2 votes

# Answer
# Vyxal, 4 bytes

```
¨£β≈

```

Try it Online!

```
¨£   # Zipwith...
  β  # Convert <str> from custom base <str>
   ≈ # All equal?

```
> 2 votes

# Answer
# Julia 1.0, 67 bytes

```
^,~=Set∘zip,length
!x=allunique(first.(x))
a\b=!a^b&&!b^a&&~a==~b

```

Try it online!

Checks that characters map uniquely in both directions, and that both strings are the same length.

-10 bytes thanks to MarcMush: no need to use splat operator inside `zip`
> 2 votes

# Answer
# Python 3, 75 bytes

```
def C():s=input();return' '.join(str(s.index(c))for c in s)
print(C()==C())

```

Try it online!
> 1 votes

# Answer
# Cobra, 72 bytes

```
do(a='',b='')=(for i in a get a.indexOf(i))==for i in b get b.indexOf(i)

```
> 1 votes

# Answer
# JavaScript (ES5), ~~142~~ 98

Quite a big one, but I didn't saw an ES5 version yet.

`for(l=j=2;j--;){c=prompt();for(i=c.length;i--;)c=c.replace(RegExp(c[i],"g"),i);b=l==c;l=c}alert(b)`

Simply replaces every occurence of the first letter with it's reverse index value. Repeats this for every character.

It does the same for both inputs and compares the generated pattern.

The comparison is quite ugly, but i din't wan't to use an array to store and compare it.
> 1 votes

# Answer
# Perl, 38 bytes

```
($_,$a)=@ARGV;eval"y/$_/$a/";say$_~~$a

```

Run as `perl -E '($_,$a)=@ARGV;eval"y/$_/$a/";say$_~~$a' RAMBUNCTIOUSLY THERMODYNAMICS`

Prints 1 if true, nothing if false.
> 1 votes

# Answer
# Common Lisp, 76 bytes

```
(lambda(a b)(equal #1=(map'list(lambda(x)(position x a))a)(setf a b a #1#)))

```

Try it online!
> 1 votes

# Answer
## C++, ~~213~~ ~~196~~ 162 bytes

-51 bytes thanks to Zacharý

```
#include<map>
#define F(X,x)for(auto&e:X){if(x.end()==x.find(e))x[e]=65+x.size();e=x[e];}
auto i=[](auto a,auto b){std::map<int,int>c,d;F(a,c)F(b,d)return a==b;};

```

To call the lambda, you need to pass 2 arguments that are `std::string` data type

Code to test :

```
std::initializer_list<std::pair<std::string, std::string>> test{
    {"ESTATE","DUELED"},
    {"DUELED","ESTATE"},
    {"XXX","YYY"},
    {"CBAABC","DEFFED"},
    {"RAMBUNCTIOUSLY","THERMODYNAMICS"},
    {"DISCRIMINATIVE","SIMPLIFICATION"},
    {"SEE","SAW"},
    {"ANTS","PANTS"},
    {"BANANA","SERENE"},
    {"BANAnA","SENSES"},
    {"AB","CC"},
    {"XXY","XYY"},
    {"ABCBACCBA","ABCBACCAB"},
    {"ABAB","AC"}
};

for (const auto& a : test) {
    std::cout << "Test with " << a.first << " and " << a.second <<
        " outputs : " << (i(a.first, a.second)?"TRUE":"FALSE") << '\n';
}

```

for the code that tests, including `iostream` and `string` header file is required
> 1 votes

# Answer
# JavaScript (ES6), ~~52~~ ~~51~~ 50 bytes

This version doesn't use array comprehension, and takes input using currying syntax.

```
a=>b=>(f=x=>0+[...x].map(c=>x.search(c)))(a)==f(b)

```

```
const isomorph = a=>b=>(f=x=>0+[...x].map(c=>x.search(c)))(a)==f(b);
const tests = [
  {input: ["ESTATE", "DUELED"], expected: true},
  {input: ["DUELED", "ESTATE"], expected: true},
  {input: ["XXX", "YYY"], expected: true},
  {input: ["CBAABC", "DEFFED"], expected: true},
  {input: ["RAMBUNCTIOUSLY", "THERMODYNAMICS"], expected: true},
  {input: ["DISCRIMINATIVE", "SIMPLIFICATION"], expected: true},
  {input: ["SEE", "SAW"], expected: false},
  {input: ["ANTS", "PANTS"], expected: false},
  {input: ["BANANA", "SERENE"], expected: false},
  {input: ["BANANA", "SENSES"], expected: false},
  {input: ["AB", "CC"], expected: false},
  {input: ["XXY", "XYY"], expected: false},
  {input: ["ABCBACCBA", "ABCBACCAB"], expected: false},
  {input: ["ABAB", "CD"], expected: false}
];

for(const { input: [str1, str2], expected } of tests) {
  console.log(`isomorph("${str1}")("${str2}") = ${isomorph(str1)(str2)}, expected = ${expected}`);
}
```
> 1 votes

# Answer
# Japt, 9 bytes

```
®¬m!âZÃre

```

Try it online!

Takes an array of two strings.

### Unpacked & How it works

```
UmZ{Zq m!âZ} re

UmZ{     Map with...
Zq m       Split into chars and map...
!âZ          X=>Z.â(X)
             char=>str.search(char); First index of the char
}
re       Reduce with Array equality

```
> 1 votes

# Answer
# C (gcc), ~~93~~ 92 bytes

* Saved a byte thanks to ceilingcat; performing an index shift.

```
m,o;r(char*p,char*h){for(o=0;*p;p++,++h)for(m=0;p[m];)o|=(p[m]==*p)^(h[m++]==*h);o|=*p!=*h;}

```

Try it online!
> 1 votes

# Answer
# , 62 bytes

```
function(x,y,`[`=chartr)x[z<-Reduce(paste0,LETTERS),x]==y[z,y]

```

Try it online!

Translates (`chartr`) the characters or each string in order of occurrence into `ABC...XYZ`. After this, isomorphic strings are identical.

To save bytes (at the expense of readability), we redefine the  index operator `[` as an alias of the `chartr` function, and we define `z` as a string containing the uppercase alphabet.
Without these golfs, the (readable) function would be:

```
function(x,y) chartr(x,"ABCDEFGHIJKLMNOPQRSTUVWXYZ",x)==chartr(y,"ABCDEFGHIJKLMNOPQRSTUVWXYZ",y)

```
> 1 votes

# Answer
# Factor \+ `math.extras`, 32 bytes

```
[ [ unique-indices nip ] same? ]

```

Try it online!

`unique-indices` is a word that produces output like this:

```
                ! "ESTATE"
unique-indices  ! "ESTA" { 0 1 2 3 2 0 }

```

We don't need the elements, only the indices, so we `nip` them to get rid of them.
> 1 votes

# Answer
# Raku, 39 bytes

```
{[eq] map {map {.index($^a)},.comb},@_}

```

Try it online!
> 1 votes

# Answer
# Ruby, 49 bytes

```
a.map{|s|s.chars.map{|c|s.index(c)}}.uniq.size==1

```

This is a function which takes in variable arguments which are stored into the 'a' variable. The algorithm is to map the characters in each word to the index of their first occurrence in the word. Once this is done, if there is only 1 unique element (aka both mappings are the same) then they are isomorphs.
> 0 votes

# Answer
# C#, 265 bytes

```
using System;using System.Linq;class I{static void Main(string[]a){var x=a[0].ToCharArray();var y=a[1].ToCharArray();Func<char[],char[],bool> l=(s,t)=>s.Select(i=>Array.IndexOf(s,i)).SequenceEqual(t.Select(i=>Array.IndexOf(t,i)));Console.WriteLine(l.Invoke(x,y));}}

```
> 0 votes

# Answer
# PHP, 99 Bytes

```
for(;$ß=$argv[1][$±++];)$×.=$$ß?"\\".$$ß:"(.)".!$$ß=++$µ;echo preg_match("#^$×$#",$argv[2]);

```

old but no PHP solution and I have solve together with @Christoph and @Titus a similar task
> 0 votes

# Answer
## Clojure, 49 bytes

```
#(apply =(for[s %&](for[a s b s](= a b))))

```

Hey it works on any number of arguments!
> 0 votes

# Answer
# Japt, 6 bytes

Takes input as an array of 2 strings.

```
®ï¥Ãre

```

Try it

```
®          :Map input array
 ï         :  Cartesian product of each string with itself
  ¥        :  Reduce each pair of characters by testing for equality
   Ã       :End map
    r      :Reduce by
     e     : Array equality

```
> 0 votes

# Answer
# Powershell, 71 bytes

```
param($a,$b)filter i{($s=$_)|% t*y|%{$s|% i*f $_}}"$($a|i)"-eq"$($b|i)"

```

Less golfed test script:

```
$f = {

param($a,$b)
filter i{
    ($s=$_)|% toCharArray|%{$s|% indexOf $_}  # returns an array of first position of each char
}
"$($a|i)"-eq"$($b|i)"                         # returns equality of two array.toString()

}

@(
    ,("ESTATE", "DUELED", $true)
    ,("DUELED", "ESTATE", $true)
    ,("XXX", "YYY", $true)
    ,("CBAABC", "DEFFED", $true)
    ,("RAMBUNCTIOUSLY", "THERMODYNAMICS", $true)
    ,("DISCRIMINATIVE", "SIMPLIFICATION", $true)
    ,("SEE", "SAW", $false)
    ,("ANTS", "PANTS", $false)
    ,("BANANA", "SERENE", $false)
    ,("BANANA", "SENSES", $false)
    ,("AB", "CC", $false)
    ,("XXY", "XYY", $false)
    ,("ABCBACCBA", "ABCBACCAB", $false)
    ,("ABAB", "CD", $false)
) | % {
    $a,$b,$expected = $_
    $result = &$f $a $b
    "$($result-eq$expected): $result"

}

```

Output:

```
True: True
True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False
True: False
True: False
True: False

```
> 0 votes

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

```
a=>b=>a.Select(c=>a.IndexOf(c)).SequenceEqual(b.Select(c=>b.IndexOf(c)))

```

Try it online!

This is a port of @ygramul answer...

My original answer is below:

# C# (Visual C# Interactive Compiler), 84 bytes

```
a=>b=>a.Length==b.Length&&!a.Where((x,i)=>b.IndexOf(b[i++],i)!=a.IndexOf(x,i)).Any()

```

Try it online!

Less golfed...

```
// a and b are strings to compare
a=>b=>
  // ensure equal lenghts
  a.Length==b.Length&&
  // iterate over characters in a
  !a.Where((x,i)=>
    // find next occurrence of current
    // char in b
    b.IndexOf(b[i++],i) !=
    // compare to next occurrence
    // of corresponding char in a
    a.IndexOf(x,i)
  // check for any mismatches
  // and negate the result
  ).Any()

```
> 0 votes

# Answer
# Japt, 8 bytes

```
®m!bZÃr¥

```

Try it online!
> 0 votes

---
Tags: code-golf, decision-problem, word-puzzle
---


title: The forbidden built-in

text:
# Question
Title: The forbidden built-in
In the standard loopholes, the following is forbidden:

> Claiming that your answer is written in "MyOwnLanguage", where the command `x` means "read a sequence of numbers, split them into groups of three, and print the last numbers of those groups where the second number is less than the first"

Here, we are going to do the exact same thing.

# Task

Given a sequence of positive integers, whose length is divisible by 3, split them into groups of three, and print the last numbers of those groups where the second number is less than the first.

# Testcases

```
Input               Output
[]                  []
[1,2,3,4,5,6,7,8,9] []
[2,1,3,5,4,6,8,7,9] [3,6,9]
[3,1,4,1,5,9,2,6,5] [4]
[100,99,123]        [123]
[123,123,456]       []
[456,123,789]       [789]

```

# Scoring

This is . Shortest answer in bytes wins.

Standard loopholes apply, so remember not to have a built-in command `x` that does this task.

# Answer
> 16 votes
# Octave, 32 bytes

```
@(L)L(x=3:3:end)(diff(L)(x-2)<0)

```

Try it online!

or

Verify test cases!

```
L3 = L(3:3:end)  %extract last elements of groups
d= diff(L)       % first difference of the list
y=d(1:3:end)     %extract first elements of each subgroup of the difference
idx = y<0        %check for negative numbers
result = L3(idx)

```

# Answer
> 14 votes
# Haskell, 30 29 bytes

```
x(a:b:c:l)=[c|b<a]++x l
x d=d

```

My first attempt at golfing Haskell, so I may have missed an optimization or two

-1 byte thanks to @JulianWolf

# Answer
> 13 votes
# Jelly, ~~9~~ 8 bytes

```
>Ḋm3T×3ị

```

Try it online!

### How it works

```
>Ḋm3T×3ị  Main link. Argument: A (array)

 Ḋ        Dequeue; yield A without its first element.
>         Compare the elements of A with the elements of the result.
  m3      Select each third element, starting with the first.
    T     Truth; get all indices of truthy elements.
     ×3   Multiply those indices by 3.
       ị  Unindex; retrieve the elements at the redulting indices.

```

# Answer
> 11 votes
# Mathematica, 37 bytes

*Assuming this does satisfy the spec, ngenisis gets credit for this approach leading to a 1-byte saving!*

```
BlockMap[If[#>#2,Print@#3]&@@#&,#,3]&

```

Pure function. `BlockMap[...,#,3]&` splits the input list into sublists of length 3 and then operates on each sublist with the function `If[#>#2,Print@#3]&@@#&`. The result is that each qualifying last number is printed. The function also returns a value (namely a list of `Null`s a third as long as the input list), which seems to be allowed behavior.

## Mathematica, ~~42~~ 38 bytes

*Thanks to Martin Ender for saving 4 bytes!*

```
Cases[#~Partition~3,{a__,b_}/;a>0:>b]&

```

Pure function. `#~Partition~3` does what you think. `Cases[X,P:>Q]` selects all the elements of `X` matching the pattern `P`, and returns the result of the transformation rule `:>Q` applied to each instance. Here, the pattern being matched is `{a__,b_}/;a>0`: `b_` will match the last element of the list and `a__` all the other elements (in this case, the first two); call them `y` and `z` for now. The sneaky `a>0` then expands to `y>z>0`, which is the test we want to apply (valid because the spec says everything will be a positive integer). And the transformation rule is `:>b`, which simply replaces each matching ordered triple with its last element.

Original submission:

```
Last/@Select[#~Partition~3,#.{1,-1,0}>0&]&

```

Pure function; pretty much a straightforward implementation, other than `#.{1,-1,0}` which calculates the difference between the first and second elements of each 3-element sublist.

# Answer
> 9 votes
# R, 35 bytes

```
(x=matrix(scan(),3))[3,x[2,]<x[1,]]

```

# Answer
> 8 votes
# Pyth, 10 bytes

```
eMf>FPTcQ3

```

Test suite

```
eMf>FPTcQ3
       cQ3    Chop the input into groups of size 3
  f           Filter on
     PT       All but the last element
   >F         Apply the greater than function
eM            Map to the last element

```

# Answer
> 6 votes
# Brachylog (2), 14 bytes

```
~c{Ṫ}ᵐ{k>₁&t}ˢ

```

Try it online!

Brachylog rather struggles with this sort of problem. Note that this program has horrible computational complexity, as it brute-forces splitting the input into groups of 3 (having no "split into groups" builtin); it runs quickly with four groups but very slowly with five.

## Explanation

```
~c{Ṫ}ᵐ{k>₁&t}ˢ
~c              Split into groups
  { }ᵐ          such that each group
   Ṫ            has three elements
      {     }ˢ  then on each element, skipping that element on error:
       k          with the list minus its last element
        >₁        assert that it's strictly decreasing
          &       and with the original list
           t      keep only its last element

```

# Answer
> 5 votes
# JavaScript (ES6), ~~46~~ ~~44~~ ~~42~~ ~~41~~ 39 bytes

```
a=>a.filter((_,y)=>y%3>1&a[y-1]<a[y-2])

```
* Saved 2 bytes thanks to Neil.

---

## Try It

Input a comma separated list of numbers, without any spaces.

```
f=
a=>a.filter((_,y)=>y%3>1&a[y-1]<a[y-2])
i.oninput=_=>o.innerText=JSON.stringify(f(i.value.split`,`.map(eval)))
console.log(JSON.stringify(f([])))                  // []
console.log(JSON.stringify(f([1,2,3,4,5,6,7,8,9]))) // []
console.log(JSON.stringify(f([2,1,3,5,4,6,8,7,9]))) // [3,6,9]
console.log(JSON.stringify(f([3,1,4,1,5,9,2,6,5]))) // [4]
console.log(JSON.stringify(f([100,99,123])))        // [123]
console.log(JSON.stringify(f([123,123,456])))       // []
console.log(JSON.stringify(f([456,123,789])))       // [789]
```

```
<input id=i><pre id=o>
```

---

## Explanation

```
a=>              :Anonymous function taking the input array as an argument via parameter a
a.filter((_,y)=> :Filter the array by executing a callback function on each element,
                  with the index of the current element passed through parameter y.
                  If the function returns 0 for any element, remove it from the array.
y%3>1            :Check if the modulo of the current index is greater than 1.
                  (JS uses 0 indexing, therefore the index of the 3rd element is 2; 2%3=2)
&                :Bitwise AND.
a[y-1]<a[y-2]    :Check if the element at index y-1 in array a
                  is less than the element at index y-2
)                :End filtering method

```

# Answer
> 4 votes
## , 14 bytes

```
_3&(>`[/\#]/\)

```

This evaluates to a monadic verb. Try it online!

## Explanation

```
_3&(>`[/\#]/\)  Input is y.
_3&(    \    )  For each non-overlapping 3-element chunk of y,
    >`[/        check if first element is greater than second.
                Call the resulting array x.
_3&(        \)  For each non-overlapping 3-element chunk of y,
          ]/    take the last element.
         #      Keep those where the corresponding element of x is 1.

```

# Answer
> 4 votes
# 05AB1E, 8 bytes

Code:

```
3ôʒR`‹i,

```

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

# Answer
> 4 votes
## Alice, ~~12~~ 11 bytes

*Thanks to Leo for saving 1 byte.*

```
I.h%I-rI~$O

```

Try it online!

Uses the code points of a string as the input list and outputs the character corresponding to the outputs that should be kept.

### Explanation

```
I      Read x. Pushes -1 on EOF.
.h%    Compute x%(x+1). This terminates the program due to division by zero at EOF,
       but does nothing for non-negative x.
I      Read y.
-      Compute x-y. We only want to output z is this is positive.
r      Range. Pushes 0 1 ... n for positive n, and -n ... 1 0 for negative n
       (and simply 0 for n = 0). So this results in a positive number on top
       of the stack iff x-y is positive.
I      Read z.
~      Swap it with x-y > 0.
$O     Output z iff x-y > 0.
       Then the IP wraps to the beginning of the program to process the next triplet.

```

# Answer
> 4 votes
## Husk, 8 bytes

```
ṁΓȯΓ↑<C3

```

Try it online!

## Explanation

This program is a bit involved, so bear with me.

```
ṁΓȯΓ↑<C3  Implicit input (list of integers).
      C3  Split into slices of length 3.
ṁ         Map over slices and concatenate results
 ΓȯΓ↑<    of this function, explained below.

```

The function `ΓȯΓ↑<` takes a list of length 3, `x = [a,b,c]`. The first `Γ` splits `x` into `a` and `[b,c]`, and feeds them as arguments to the function `ȯΓ↑<`. This should be equivalent to `((Γ↑)<)`, but due to a bug/feature of the interpreter, it's actually equivalent to `(Γ(↑<))`, interpreted as a composition of `Γ` and `↑<`. Now, `a` is fed to the latter function using partial application, the resulting function `↑<a` is given to `Γ`, which deconstructs `[b,c]` into `b` and `[c]`. Then `b` is fed to `↑<a`, resulting in a function that takes the first `b<a` elements from a list. This function is finally applied to `[c]`; the result is `[c]` if `a>b`, and `[]` otherwise. These lists are concatenated by  to form the final result, which is printed implicitly.

Without the "feature", I would have 9 bytes:

```
ṁΓoΓo↑<C3

```

# Answer
> 3 votes
# Jelly, 10 bytes

```
s3µṪWx>/µ€

```

Try it online!

or

Verify test cases

*-3 bytes thanks to @LeakyNun*

**Explanation**

```
s3µṪWx>/µ€
s3         - split into groups of three
  µ     µ€ - on each group, do:
   ṪW      - return the third element as the only element of a list
     x     - repeat each element in that list the number of times
      >/   - corresponding to 1 if the second element of the group is greater than the first; 0 otherwise.

```

# Answer
> 3 votes
# Python 3, ~~43~~ 42 bytes

1 byte thanks to xnor.

```
f=lambda a,b,c,*l:(b<a)*(c,)+(l and f(*l))

```

Try it online!

# Answer
> 3 votes
# dc, 30 bytes

```
[???sAz1[[lAps.]s.<.dx]s.<.]dx

```

I/O: one number per line.

# Answer
> 3 votes
# Perl 5, 31 bytes

30 bytes of code + `-p` flag.

```
s/\d+ (\d+) (\d+)/$2if$1<$&/ge

```

Try it online!

Replaces each group of 3 numbers (`\d+ (\d+) (\d+)`) by the third (`$2`) if the second (`$1`) is less than the first (`$&`), and nothing otherwise.

# Answer
> 3 votes
## R, 31 bytes

Thanks to @Giuseppe again -1 byte:

```
f=\(x)x[!2:0][x[!-1:1]<x[!0:2]]

```

Thanks to @Giuseppe again -2 bytes:

```
f=\(x)x[!-2:0][x[!-1:1]<x[!0:2]]

```

With the R 4.1 it is a new game play (34 bytes). ;)

```
f=\(x)x[(i<--1:1)>0][x[!i]<x[i<0]]

```

where `\(x)` is a shorthand for the `function(x)`.

37 bytes version with `scan()` which I do not like, but it makes it shorter.

```
x=scan();x[(i<--1:1)>0][x[!i]<x[i<0]]

```

Version with `function()` which is easier to test (41 byte)

```
f=function(x)x[(i<--1:1)>0][x[!i]<x[i<0]]

```

Thanks to the @Giuseppe! Nice idea to use recycling of index.

Test:

```
f(c())
f(c(1,2,3,4,5,6,7,8,9))
f(c(2,1,3,5,4,6,8,7,9))
f(c(3,1,4,1,5,9,2,6,5))
f(c(100,99,123))
f(c(123,123,456))
f(c(456,123,789))

```

Output:

```
> f(c())
NULL
> f(c(1,2,3,4,5,6,7,8,9))
numeric(0)
> f(c(2,1,3,5,4,6,8,7,9))
[1] 3 6 9
> f(c(3,1,4,1,5,9,2,6,5))
[1] 4
> f(c(100,99,123))
[1] 123
> f(c(123,123,456))
numeric(0)
> f(c(456,123,789))
[1] 789

```

# Answer
> 3 votes
# CJam, 15 bytes

```
{3/{)\:>{;}|}%}

```

Anonymous block which expects argument on the stack, and leaves the result on the stack.

Try it online! (Runs all test cases)

**Explanation**

```
3/             e# Split the list into length-3 chunks.
  {            e# For each chunk:
   )           e#  Remove the last element.
    \:>        e#  Reduce the first 2 elements by greater than.
       {;}|    e#  If the first is not larger than the second, delete the third.
           }%  e# (end for)

```

# Answer
> 3 votes
# Brain-Flak, 82 bytes

```
{([({}[{}()]<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}((<({}<>)<>>))}{}{}}<>

```

Try it online!

```
# Until the stack is empty (input is guaranteed to not contain 0)
{

  # Push 1 for greater than or equal to 0
  ([({}[{}()]<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
  #  ^------^  This part is Top - (Second + 1)

  # If the second number was less than the first...
  {{}

     # Get ready to push 2 zeros
     ((<

       # Move the next number to the other stack
       ({}<>)<>

     # Push those 2 zeros
     >))}

     # Pop 2 values.
     # This is either 2 zeros, or a 0 and a "last number" that shouldn't be printed
     {}{}

# End loop
}

# Switch to the stack where we stored the numbers to be printed
<>

```

# Answer
> 2 votes
# C#, 126 Bytes

```
using System.Linq;i=>Enumerable.Range(0,i.Length/3).Select(u=>3*u).Where(u=>i[u]>i[u+1]).Select(u=>i[u+2]);

```

If you want a whole program with the method it'd be **175 Bytes**:

```
using System.Linq;namespace S{class P{static System.Collections.IEnumerable X(int[]i)=>Enumerable.Range(0,i.Length/3).Select(u=>3*u).Where(u=>i[u]>i[u+1]).Select(u=>i[u+2]);}}

```

*Saved 7 Bytes with the help of TheLethalCoder*

# Answer
> 2 votes
# Java 7, ~~86~~ 85 bytes

```
void c(int[]a){for(int i=-1;++i<a.length;)if(a[i++]>a[i++])System.out.println(a[i]);}

```

-1 byte thanks to *@PunPun1000*

**Explanation:**

Try it here.

```
void c(int[]a){                  // Method with integer-array parameter and no return
  for(int i=-1;++i<a.length;)    //  Loop over the array in steps of three at a time
    if(a[i++]>a[i++])            //   If the value of the current index is larger than the next:
      System.out.println(a[i]);  //    Print the value on the third index
                                 //  End of loop (implicit / single-line body)
}                                // End of method

```

# Answer
> 2 votes
# Python 2, 57 bytes

```
lambda i:[i[c+2]for c in range(0,len(i),3)if i[c+1]<i[c]]

```

Try it online!

# Answer
> 2 votes
# MATL, 10 bytes

```
IeI&Y)d0<)

```

The result is displayed as numbers separated by spaces.

Try it online!

Or verify all test cases. This displays a string representation of the output, so that an empty array is actually seen as `[]`. Note that in MATL a number is the same as a singleton array, so `[4]` is shown as `4`.

### Explanation

```
Ie    % Implicit input. Reshape as a 3-row matrix (column-major order)
I&Y)  % Split into the third row and a submatrix with the other two rows
d     % Consecutive difference along each column of the submatrix
0<    % True for negative values
)     % Use as logical index into the original third row. Implicitly display

```

# Answer
> 2 votes
# Röda, 15 bytes

```
{[_3]if[_2<_1]}

```

Röda is nearly as short as the golfing languages...

This takes three values from the stream, and pushes the third (`_3`) back, if the second (`_2`) is less than the first (`_1`).

The underscores are syntax sugar for `for` loops, so the program could be written as `{{[a]if[b<c]}for a,b,c}` or even `{[a]for a,b,c if[b<c]}`.

No TIO link, because it doesn't work on TIO for some reason (although works with the latest version of Röda that predates the challenge).

# Answer
> 2 votes
# Awk, 27 bytes

```
{a[b=NR%3]=$0}!b&&a[2]<a[1]

```

# Answer
> 2 votes
# Vyxal, 8 bytes

```
3ẇR∩÷<Tİ

```

Try it Online!

There are a ton of 8-byters but I haven't been able to find a single 7-byter.

```
3ẇ       # Cut into chunks of length 3
  R      # Reverse each chunk
   ∩÷    # Transpose and push each row to the stack
     <   # For each, check if second > first
      Tİ # Only keep third elements where ^ is truthy

```

# Answer
> 1 votes
## JavaScript, ~~108~~ ~~107~~ 108 bytes

This is a valid JS anonymous (lambda) function. Add `x=` at the beginning and invoke like `x([5,4,9,10,5,13])`. Outputs as function `return`.

```
a=>(y=[],a.map((c,i)=>(i+1)%3?0:y.push(a.slice(i-2,i+1))),y.map(v=>v[1]<v[0]?v[2]:null).filter(c=>c|c==0))

```

The snippet takes in the input as a list of comma separated integers.

```
x=a=>(y=[],a.map((c,i)=>(i+1)%3?0:y.push(a.slice(i-2,i+1))),y.map(v=>v[1]<v[0]?v[2]:null).filter(c=>c|c==0))
martin.oninput = e => { dennis.innerHTML = x(martin.value.split`,`.map(c=>parseInt(c,10))) }
```

```
<input type=text id=martin><pre id=dennis>
```

# Answer
> 1 votes
# CJam, 16 bytes

```
q~3/{~@@>S{;}?}%

```

The output is shown as numbers separated by spaces.

Try it online!

### Explanation

```
q~               e# Read input list
  3/             e# List of sublists of length 3
   {         }%  e# Apply this to each sublist
    ~            e# Push sublist contents: 3 numbers
     @@          e# Rotate twice. This moves first two numbers to top
       >         e# Greater than?
        S{;}?    e# If so: push space (used as separator). Else: pop the third number
                 e# Implicitly display

```

# Answer
> 1 votes
# PHP, 89 Bytes

```
<?print_r(array_filter($_GET,function($v,$k){return $k%3>1&&$_GET[$k-1]<$_GET[$k-2];},1));

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~37~~ 35 bytes

```
->a{a.map{x,y,z,*a=a;z&&x>y&&p(z)}}

```

Try it online!

## How it works:

```
->a{
    a.map{                          -> Loop [a.size] times
          x,y,z,*a=a;               -> get and remove 3 elements from a
                     z&&x>y&&p(z)   -> print z if not null and x>y
                                 }}

```

# Answer
> 1 votes
# Retina, ~~42~~ 36 bytes

```
\d+
$*
M!`1+ 1+ 1+
A`^(1+) \1
%r`1\G

```

Try it online! Takes input as a space-separated list of numbers and outputs a newline-separated list of numbers. Edit: Saved 6 bytes thanks to @MartinEnder. Explanation:

```
\d+             Match input numbers
$*              Convert to unary
M!`1+ 1+ 1+     Capture groups of three numbers
A`^(1+) \1      Filter out if the first is less than or equal to the second
%r`1\G          Convert the third to decimal

```

# Answer
> 1 votes
# C, 65 bytes

**Try Online**

```
i;f(s,l)int*l;{for(;i+2<s;i++)l[i]>l[i+1]&&printf(" %d",l[i+2]);}

```

# Answer
> 1 votes
# Perl5.8.9, ~~73~~ 60 bytes

```
while(@F){@b=splice@F,0,3;$b[1]<$b[0]&&print$b[2]}print"-"

```

(58+2 for the 'n' flag to read the whole file and a to autosplit). Assumes the input is lines of space separated numbers

Reduction thanks to Dada. Including the print at the end for visibility, that'd save 8 bytes if not.

# Answer
> 1 votes
## Clojure, 43 bytes

```
#(for[[a b c](partition 3 %):when(< b a)]c)

```

Boring :/

# Answer
> 1 votes
# Bash, 61 bytes

```
a=($@)
for((t=0;t<$#;t+=3)){((a[t+1]<a[t]))&&echo ${a[t+2]};}

```

Try it online!

# Answer
> 1 votes
## Mathematica, 42 39 bytes

*Edit: Saved 3 bytes thanks to Greg Martin*

`BlockMap[Apply[If[#>#2,#3,Nothing]&],#,3]&`

```
BlockMap[If[#>#2,#3,Nothing]&@@#&,#,3]&

```

Not shorter than Greg Martin's answer, but I couldn't resist the opportunity to finally use `BlockMap`. Partitions the input list `#` into sublists of size `3` and `Apply`s the functions `If[#>#2,#3,Nothing]&` to each sublist.

## Questionable solution, 38 bytes

```
BlockMap[If[#>#2,Print@#3]&@@#&,#,3]&

```

Same as above, except it prints the desired elements and returns `{Null,...Null}`.

# Answer
> 1 votes
# Scala, 74 66 bytes

### Edit: Lost 8 bytes thanks to @AlecZorab

The suggestion was to use `collect()` instead of the equivalent `filter()` followed by `map()` (which my for comprehension is equivalent to) and a pattern match, kind of like:

```
(_:Seq[Int]).grouped(3).collect{case(Seq(a,b,c))if(a>b)=>c}.toList

```

Another suggestion was to drop the parameter name as it was only used once.

The character/byte count can be dropped to 59 bytes if an iterator is an acceptable output. Usage is similar to the old version.

## Old version:

```
(s:Seq[Int])=>(for(l<-s.grouped(3)if l.size>2&l(0)>l(1))yield l(2)).toList

```

Straightforward. The `toList` at the end is to consume the iterator produced - `toSeq` produces a `Stream` in my tests, which shows only the first element. If the iterator itself is legal as output, this version comes in at 64 bytes:

```
(s:Seq[Int])=>for(l<-s.grouped(3)if l.size>2&l(0)>l(1))yield l(2)

```

Scala allows Unicode operators, so I could lower the character count to 62 at the cost of increasing the byte count to 66:

```
(s:Seq[Int])⇒for(l←s.grouped(3)if l.size>2&l(0)>l(1))yield l(2)

```

Lambda, the parameter type is required in the REPL. Enter into the REPL and call the `res0` or whatever function object it shows with the `Seq[Int]` to test with. For ease of testing, you can consider the following function which converts a test case `String` into a proper `Seq[Int]`:

```
def testCaseAsSeq(input: String): Seq[Int] =
    input.drop(1).dropRight(1)
         .split(",")
         .filter(! _.isEmpty)
         .map(_.toInt).toSeq

```

Prettified version with some obfuscations removed to make it more standard Scala:

```
(sequence: Seq[Int]): List[Int] =>
                    (for(group <- s.grouped(3)
                    if group.size == 3 && group(0) > group(1))
                        yield group.last)
                    .toList

```

# Answer
> 1 votes
# \>\<\>, 19 + 3 for -v = 22 bytes

```
rl?!;(?\~r
naaao~ \

```

# Answer
> 1 votes
# Japt, ~~18~~ 12 bytes

```
ò3 f_v >ZvÃc

```

Try it online

Or 10 bytes if returning a nested array is permitted, e.g. `[[3],[6],[9]]`

```
ò3 f_v >Zv

```

# Answer
> 1 votes
# GolfScript, 17 bytes

```
~3/{~@@>{}{;}if}%

```

Try it online!

# Explanation

```
~                 # Evaluate the input
 3/               # Split the input into chunks of 3
   {           }% # Map every item in the input
    ~@@>          # Is the 1st item < second item?
        {}{;}if   # If false, discard the current item

```

# Answer
> 1 votes
# Python 3, 50 bytes

```
lambda l:[c for a,b,c in zip(*(iter(l),)*3)if b<a]

```

Try it online!

# Answer
> 1 votes
# Ly, 17 bytes

```
0&n[spG[rlr!]pp]p

```

Try it online!

This is a pretty much a direct mapping of the rules to code... After reading all the numbers onto the stack, each iteration of the loop processes the top three numbers on the stack. If the 2nd is less than the 1st, the third is appended to the end of the stack.

Once the `0` delimiter is hit on the stack, the program exits and the default action to print everything on the stack as numeric takes care of the output.

```
0                  - add a "0" delimiter to stop the loop
 &n                - read all the numbers into the stack (expects one per line)
   [         pp]   - loop to process three nums ("pp" pops a work var and the 1at num)
    sp             - save the 3rd number and pop it from the stack
      G            - compare the 1st and 2nd
       [   !]      - true if 2nd is less than 1st
        rlr        - reverse the stack, load 3rd char, reverse again
                p  - pop the "0" delimiter, leaving just the answers

```

# Answer
> 1 votes
# Pip `-xp`, 14 bytes

```
_@2M$>H_FIa<>3

```

Takes the list as a command-line argument. Attempt This Online!

### Explanation

```
          a     ; First command-line argument
           <>3  ; Grouped into sublists of length 3
        FI      ; Filtered on this function:
      H_        ;   Prefix (all but the last item)
    $>          ;   Folded on > (in this case, truthy iff the first item > the second)
   M            ; Map this function to each remaining sublist:
_@2             ;   Get the item at index 2

```

---

## No flags, 14 bytes

Here's a recursive solution without flags:

```
Ib<aPcIgfVg@>3

```

Takes the numbers as separate command-line arguments. Attempt This Online!

### Explanation

```
Ib<a            ; If the second argument is less than the first:
    Pc          ;   Print the third argument
      Ig        ; If the arglist is truthy (not empty):
        fV      ;   Call the current function again with arglist...
          g@>3  ;   ... current arglist without the first three elements

```

When `g` is empty, all of `a`, `b`, and `c` are set to nil. Since nil is not less than nil, `b<a` is false and the first if statement is not executed.

# Answer
> 1 votes
# Thunno 2, 8 bytes

```
3ẇ{rẸ<?£

```

Try it online!

#### Explanation

```
3ẇ{rẸ<?£  # Implicit input
3ẇ        # Split into threes
  {       # Loop over them:
   rẸ     #  Reverse and dump
     <    #  Check if less than
      ?£  #  If true, print

```

# Answer
> 1 votes
# janet, 60 bytes

```
(fn[l](map last(filter(fn[x](<(x 1)(x 0)))(partition 3 l))))

```

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~38~~ ~~29~~ 25 bytes

```
{((0=3|⍳⍴⍵)^⍵>1⌽⍵)/2⌽⍵}

```

The index origin is set to 0 (⎕IO←0).

Try it on TryAPL.org!

# Answer
> 1 votes
# Julia 0.6, 29 bytes

```
~a=(!x=a[x:3:end])(3)[!2.<!1]

```

Try it online!

In Julia 1.0, a space is required to disambiguate the period, which could be either a decimal or part of a dot operator.

-2 bytes thanks to MarcMush: use return value from function definition

# Answer
> 0 votes
## Mathematica 65 bytes

```
{K={};Cases[Partition[#,3],{a_,b_,c_}->If[b<a,AppendTo[K,c]]];K}&

```

# Answer
> 0 votes
# Factor, 44 bytes

```
[ 3 group [ first2 > ] [ last ] filter-map ]

```

Try it online!

# Answer
> 0 votes
# Nibbles, 7.5 bytes (15 nibbles)

```
.|`/3$`/<<$-/\

```

Attempt This Online!

```
.|`/3$`/<<$-/\
  `/3$          # split into chunks of 3
 |              # and filter these for positive results of
      `/        #   folding over
        <<$     #   the group without the 3rd (last) element
           -    #   by subtraction
.               # now map over the remaining groups of 3
             \  #   reverse each
            /   #   and now get the first element

```

# Answer
> 0 votes
# Go, 87 bytes

```
func(A[]int)(O[]int){for i:=0;i<len(A);i+=3{if A[i]>A[i+1]{O=append(O,A[i+2])}}
return}

```

Attempt This Online!

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