title: Alternested numbers

text:
# Question
Title: Alternested numbers
Consider the array of positive integers:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ...

```

Then, concatenate them:

```
1234567891011121314151617181920212223242526...

```

And then split them into chunks of variable length, each length being equal to the **N**th positive integer:

```
[1][23][456][7891][01112][131415][1617181][92021222][324252627][2829303132] ...
---------------------------------------------------------------------------
 1  2    3     4     5       6       7        8          9          10      ...

```

# Task

Given an integer **N** (positive for 1-indexing or non-negative for 0-indexing), your task is to output the sum of the deltas of the digits in the **N**th chunk (the differences between consecutive digits).

# Examples & Test cases

1-indexed test cases. If you want 0-indexed ones, just decrement N.

```
N, Chunk, Deltas, Sum

1  -> 1          -> []                               -> 0
2  -> 23         -> [1]                              -> 1
3  -> 456        -> [1, 1]                           -> 2
4  -> 7891       -> [1, 1, -8]                       -> -6
5  -> 01112      -> [1, 0, 0,1]                      -> 2
6  -> 131415     -> [2, -2, 3, -3, 4]                -> 4
7  -> 1617181    -> [5, -5, 6, -6, 7, -7]            -> 0
8  -> 92021222   -> [-7, -2, 2, -1, 1, 0, 0]         -> -7
9  -> 324252627  -> [-1, 2, -2, 3, -3, 4, -4, 5]     -> 4
10 -> 2829303132 -> [6, -6, 7, -6, -3, 3, -2, 2, -1] -> 0

```

<sub>**Puzzle 2 on CodeGolf-Hackathon (I am the original author there too, so I am allowed to repost). Related, Inspiration. Related.**</sub>

# Answer
> 6 votes
# Husk, 9 bytes

```
ΣẊ-!SCṁdN

```

Try it online!

My solution to the Hackathon.

Explanation:

```
ΣẊ-!SCṁdN⁰
    S      (x -> y -> z):f -> (x -> y):g -> x:x :: return f(x, g(x))
     C      f= [num]:x -> [x]:y -> [x] :: cut y in pieces where each piece has its respective length in x
      ṁ     g= (x -> [y]):f -> ([x]:x -> [y]) :: maps f over x then concatenate
       d     f= num:x -> [num] :: return decimal digits of x
        N   x= sequence of natural numbers [1..]
   !     ⁰ [x]:x -> num:y -> x :: get yth (impl. input) element of x (above result)
 Ẋ         (x -> x -> y):f -> [x]:x -> [y] :: map f over overlapping pairs of x (above result)
  -         f= num:x -> num:y -> num :: return y - x
Σ          [num]:x -> num :: return sum of x (above result)

```

# Answer
> 5 votes
# JavaScript (ES6), ~~54~~ ~~53~~ ~~51~~ 50 bytes

*Saved 1 byte thanks to @tsh*

0-indexed.

```
k=>-(n=1,g=s=>s[x=k*-~k/2]-s[x+k]-n||g(s+n++))``-n

```

### Test cases

```
let f =

k=>-(n=1,g=s=>s[x=k*-~k/2]-s[x+k]-n||g(s+n++))``-n

for(i = 0; i < 10; i++) {
  console.log('a(' + i + ') = ' + f(i));
}
```

# Answer
> 4 votes
# APL (Dyalog), 32 bytes

```
{+/2-⍨/⍎¨⍵↑(+/⍳⍵-1)↓' '~⍨⍕⍳+/⍳⍵}

```

Try it online!

**How?**

`+/⍳⍵` \- sum of `1` to `n`

\- make range of that

`' '~⍨⍕` \- into string, without spaces

`(+/⍳⍵-1)↓` \- drop first (sum of `1` to `n-1`) chars

`⍵↑` \- keep the next `n` chars

`⍎¨` \- make every char into integer

`2-⍨/` \- differences list (backward subtraction for every 2 items)

`+/` \- sum it up.

# Answer
> 4 votes
# Haskell, ~~61~~ 60 bytes

```
l=fromEnum<$>(show=<<[1..])
f n|t<-sum[2..n]=l!!t-l!!(t-n+1)

```

Try it online!

### Explanation:

The sum of the deltas of a list is the same as the difference between the last and the first element.

The last element (zero-indexed) is `t`, `triangle(n)-1 = sum[2..n]`. The first element, then is `t-n+1`, as the list has `n` elements.

# Answer
> 4 votes
# Python 2, 80 bytes

```
n=input()
s=map(int,''.join(map(str,range(2**n))))
print s[n*-~n/2]-s[~-n*n/2+1]

```

Try it online!

`2**n` is way overkill, of course, but it’s a byte shorter than something like `n*n+1`.

# Answer
> 3 votes
# Mathematica, 71 bytes

```
Tr@Differences[TakeList[Join@@IntegerDigits[Range[#^2]],Range@#][[#]]]&

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
∞LJā£è¥O

```

0-indexed.

Try it online!

# Answer
> 3 votes
## JavaScript (ES6), ~~60~~ ~~57~~ 53 bytes

```
f=(n,s=i='',m=n*-~n/2)=>s[m]?s[m]-s[m-n+1]:f(n,s+i++)
```

```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```

1-indexed. Previous 60-byte nonrecursive version:

```
f=
(n,s=[...Array(n*n+1).keys()].join``)=>s[m=n*-~n/2]-s[m-n+1]
```

```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```

# Answer
> 2 votes
# Python 2, 87 bytes

```
n=input()
a=map(int,''.join(map(str,range(1,n*n))))[n*~-n/2:][:n]or[0]
print a[-1]-a[0]

```

Try it online!

# Answer
> 2 votes
# Vyxal `s`, 11 bytes

```
²ɾṅ?ʀʀÞṁi⌊¯

```

Try it Online!

0-indexed

## Explained

```
²ɾṅ?ʀʀÞṁi⌊¯
²ɾ           # the range [1...input**2]
  ṅ          # joined into a single integer - call it x
   ?ʀ        # the range [0...input]
     ʀ       # [range [0...n] for n in that]
      Þṁ     # reshape x to the shape of that
        i    # get the input(th) item of that
         ⌊   # convert each item to integer
          ¯  # and take the deltas of that
             # the -s flag sums that

```

# Answer
> 1 votes
# Python 2, 104 bytes

```
def f(N):A=map(int,"".join(map(str,range(1,N*N)))[~-N*N/2:][:N]);return sum(a-b for a,b in zip(A[1:],A))

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~58~~  55 bytes

```
{[+] ($_=(1..*).map(|*.comb).rotor(1..*)[$^a])[1..*]Z-@$_}

```

Test it

```
{[+] ($_=(1..*).map(|*.comb)[^$^a+[+] ^$a])[1..*]Z-@$_}

```

Test it

## Expanded:

```
{ # bare block lambda with placeholder parameter ｢$a｣
  [+]  # reduce using &infix:«+» the following

    (
      $_ =                # store into ｢$_｣ for later use

        ( 1 .. * )        # Range of all positive integers
        .map( | *.comb )\ # split into digits and flatten into single list

        [                 # index into the sequence (1 based)

          ^$^a            # Range up to (and excluding) the input
                          # ｢0 ..^ $a｣ or ｢0 .. $a-1｣

          +               # shift it up by
          [+] ^$a         # the sum of the values up to (and excluding) the input

        ]

    )[ 1 .. *]            # skip the first value

    Z-                    # zip using &infix:«-»

    @$_                   # ｢$_｣ used as a List
}

```

# Answer
> 1 votes
# PHP, ~~163~~ 147 bytes

```
$v=$argv[1];for($i=1;$i<=$v*$v;$i++){$s.=$i;$j+=$i<$v?$i:0;}$s=array_slice(str_split($s),$j,$v);for($i=0;$i<$v-1;$i++){$k+=$s[$i+1]-$s[$i];}echo$k;

```

Try it online!

My first attempt at code golfing... have a feeling that this can be shorter

Edit: saved 16 bytes by removing several instantiations

# Answer
> 0 votes
# Perl 5, 79 + 1 (`-p`) = 80 bytes

```
$_=substr join('',1..$_**2),$_*($_-1)/2,$_;1while s/(.)(.)/$r+=$2-$1;$2/e;$_=$r

```

Try it online!

# Answer
> 0 votes
# Pyth, ~~29~~ 27 bytes

Saved 2 bytes thanks to @Mr.Xcoder.

```
s.+msdc:sm+hd""U*QQKsUQ+QK1

```

Try it online!

# Answer
> 0 votes
# Jelly, 14 bytes

```
²RDFṫ³ḶS‘¤ðḣIS

```

Try it online!

**Explanation**

```
²RDFṫ³ḶS‘¤ðḣIS    Main Link
²                  Square input
 R                 Range: [1,2,3,..,n^2]
  D                Digits: [1,2,...,[1,0],[1,1],...]
   F               Flatten list
     ³ḶS‘¤         n(n-1)/2+1
    ṫ              Remove the first n(n-1)/2+1 elements from the list of digits
          ðḣ       Take the first n digits of the list. ð is needed to prevent I from acting on n.
            I      Increment. Take the diferences
             S     Sum

```

I originally started by taking the range( n(n+1)/2 ) but since you can have extra digits at the end of the list before slicing it I changed it to range(n^2). You have extra digits after 1-9 anyway.

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


title: Nothing like a good ol' game of ModTen

text:
# Question
Title: Nothing like a good ol' game of ModTen
*Disclaimer: ModTen is a fictional card game which was created for the sole purpose of this challenge.*

## The rules of ModTen

*ModTen* is played with a standard 52-card deck. Because the full rules are yet to be invented, we're going to focus on the hand ranking exclusively.

*A winning hand in ModTen. Graphics from Wikipedia.*

### Card values

The cards have the following values:

* **2** to **9**: worth their face value
* **Ten**: 0 point
* **Jack**: 3 points
* **Queen** or **King**: 8 points
* **Ace**: 9 points

### Hand values

* A *ModTen* hand is made of **two cards**. The base value of a hand is obtained by multiplying the value of both cards together and keeping the last digit only (i.e. applying a modulo 10).

For instance, the value of **7**♥ - **Q**♣ is "\\$6\\$", because \\$(7\times8)\bmod 10=6\\$.
* The only other rule in *ModTen* is that **suited cards** are worth more than unsuited ones. By convention, we are going to append a **"s"** to the value if both cards are of the same suit.

For instance, the value of **9**♠ - **5**♠ will be noted as "\\$5\text{s}\\$", because \\$(9\times5)\bmod 10=5\\$ and the cards are suited.

### Hand ranking and winner

The above rules result in 18 distinct hand ranks which are summarized in the following table, from strongest to lowest (or rarest to most common). The probabilities are given for information only.

Given two hands, the hand with the lowest rank wins. If both hands are of the same rank, then it's a draw (there's no tie breaker).

```
 hand rank | hand value(s) | deal probability
-----------+---------------+------------------
     1     | 9s            | 0.30%
     2     | 3s            | 0.60%
     3     | 1s            | 0.90%
     4     | 7s            | 1.21%
     5     | 5s            | 1.51%
     6     | 3             | 1.81%
     7     | 9             | 2.26%
     8     | 8s            | 2.71%
     9     | 6s            | 3.02%
    10     | 1 or 7        | 3.62% each
    11     | 2s or 4s      | 3.92% each
    12     | 5             | 4.98%
    13     | 0s            | 5.43%
    14     | 8             | 8.14%
    15     | 6             | 9.95%
    16     | 2             | 11.76%
    17     | 4             | 13.57%
    18     | 0             | 16.74%

```

## The challenge

Given two *ModTen* hands, output one of **three consistent values** of your choice to tell whether:

* the first player wins
* the second player wins
* it's a draw

The following rules apply:

* A card must be described by its rank in upper case (`2`, `3`, ..., `9`, `T`, `J`, `Q`, `K` or `A`) followed by its suit in lower case (`c`, `d`, `h` or `s`, for clubs, diamonds, hearts and spades).
* You may use `"10"` instead of `"T"` but any other substitution is prohibited.
* As long as the above rules are followed, you may take the hands in any reasonable and unambiguous format. You are allowed to take the rank and the suit as two distinct characters rather than a single string.

Some valid input formats are:

+ `"7c Qh 8s Ks"`
    + `[["7c","Qh"], ["8s","Ks"]]`
    + `[[['7','c'], ['Q','h']], [['8','s'], ['K','s']]]`
    + etc.
* Instead of using 3 consistent distinct values, your output may also be **negative**, **positive** or **zero**. Please specify the output format used in your answer.
* This is .

## Test cases

Player 1 wins

```
["Js","3s"], ["Ks","Kh"]
["7h","9h"], ["9s","7c"]
["Ah","5s"], ["Ts","8s"]
["Ts","8s"], ["Jh","2s"]
["4h","8s"], ["Qh","Ks"]

```

Player 2 wins

```
["Th","8d"], ["6s","Kd"]
["Jc","5c"], ["3s","9s"]
["Jc","Jd"], ["9h","Ah"]
["2d","4d"], ["3h","3s"]
["5c","4c"], ["3c","2c"]

```

Draw

```
["Js","3s"], ["3d","Jd"]
["Ah","Ac"], ["3d","9s"]
["Qc","Kc"], ["6d","4d"]
["2d","3d"], ["3s","2s"]
["Ts","9c"], ["4h","5d"]

```

# Answer
> 15 votes
# Python 3, ~~114~~ 110 bytes

```
lambda m,n:p(*n)-p(*m)
R=b"T 2J45UNK9RL<3SLM;QAK:O>=/678"
v=R.find
p=lambda i,s,j,t:R[s==t::2][v(j)*v(i)%10+3]

```

Try it online!

@Arnauld proposed the idea of merging the card value and rank table strings. After some attempts I managed to craft a merged string `R="T 2J45UNK9RL<3SLM;QAK:O>=/678"`, which has the same length as the original card value string. The substring `R[6:25]="UNK9RL<3SLM;QAK:O>=/"` serves as the rank table as well as a card value lookup table for `3`, `9`, `A`, `K`, and `Q`. The ASCII-value decoding of the new rank table has the same ranking effect as the previous rank table.

Using byte strings as input saves 4 bytes.

Using `cmp` in Python 2 can reduce the solution to 102 bytes, as shown by @xnor's solution.

---

# Python 3, ~~165~~ ~~142~~ ~~130~~ 129 bytes

```
lambda m,n:p(*n)-p(*m)
v="T 23456789   J    QA        K".find
p=lambda i,s,j,t:ord("HC92FA51GAB4E893D760"[s==t::2][v(j)*v(i)%10])

```

Try it online!

*-23 bytes thanks to @Jonathan Allan*

*-2 bytes thanks to @ovs*

*-1 byte thanks to @mypetlion*

### Ungolfed:

```
f = lambda hand1, hand2: get_rank(*hand2) - get_rank(*hand1)
def get_rank(v1, suit1, v2, suit2):
    get_card_value = "T 23456789   J    QA        K".find
    # rank_table = [[17,9,15,5,16,11,14,9,13,6],[12,2,10,1,10,4,8,3,7,0]]
    # rank_table = ("H9F5GBE9D6","C2A1A48370") # Base-18 encoding of ranks
    rank_table = "HC92FA51GAB4E893D760" # Interleaved base-18 encoding

    # ASCII-value decoding has the same ranking effect as base-18 decoding
    return ord(rank_table[suit1 == suit2::2][get_card_value(v2) * get_card_value(v1) % 10])

```

The function `f` takes two arguments representing the hand of player 1 and player 2. It returns a positive, negative, or zero value in the case of a player 1 win, a player 2 win, or a draw, correspondingly. Each hand is encoded as a single string, e.g. "7cQh".

# Answer
> 12 votes
# x86-16 machine code, ~~87~~ 83 bytes

**Binary:**

```
00000000: e807 0050 e803 005a 3ac2 ad2c 3092 ad2c  ...P...Z:..,0..,
00000010: 30bb 3501 3af4 7503 bb3f 01e8 0a00 92e8  0.5.:.u..?......
00000020: 0600 f6e2 d40a d7c3 b106 bf49 01f2 aee3  ...........I....
00000030: 038a 4504 c312 0a10 0611 0c0f 0a0e 070d  ..E.............
00000040: 030b 020b 0509 0408 0124 1a21 1b11 0003  .........$.!....
00000050: 0808 09                                  ...

```

**Unassembled:**

```
E8 010A         CALL GET_HAND           ; score first hand, ranked score into AL
50              PUSH AX                 ; save score
E8 010A         CALL GET_HAND           ; score second hand
5A              POP  DX                 ; restore first hand into DL
3A C2           CMP  AL, DL             ; compare scores - result in CF, OF and ZF
            GET_HAND:                   ; 4 char string to ranked score ("9s7c" -> 6)
AD              LODSW                   ; load first card string
2C 30           SUB  AL, '0'            ; ASCII convert
92              XCHG DX, AX             ; store in DX
AD              LODSW                   ; load second card string
2C 30           SUB  AL, '0'            ; ASCII convert
BB 0139         MOV  BX, OFFSET R       ; first, point to non-suited table
3A F4           CMP  DH, AH             ; is it suited?
75 03           JNZ  NO_SUIT
BB 0143         MOV  BX, OFFSET RS      ; point to suited table
            NO_SUIT:
E8 012C         CALL GET_VALUE          ; get face card value in AL
92              XCHG DX, AX             ; swap first and second cards
E8 012C         CALL GET_VALUE          ; get face card value in AL
F6 E2           MUL  DL                 ; multiply values of two cards
D4 A0           AAM                     ; AL = AL mod 10
D7              XLAT                    ; lookup value in rank score table
C3              RET                     ; return to caller
            GET_VALUE:                  ; get value of a card (2 -> 2, J -> 3, A -> 9)
B1 06           MOV  CL, 6              ; loop counter for scan
BF 014D         MOV  DI, OFFSET V       ; load lookup table
F2/ AE          REPNZ SCASB             ; scan until match is found
E3 03           JCXZ NOT_FOUND          ; if not found, keep original numeric value
8A 45 04        MOV  AL, BYTE PTR[DI+4] ; if found, get corresponding value
            NOT_FOUND:
C3              RET                     ; return to program

R    DB   18, 10, 16, 6, 17, 12, 15, 10, 14, 7     ; unsuited score table
RS   DB   13, 3, 11, 2, 11, 5, 9, 4, 8, 1          ; suited score table
V    DB   'J'-'0','Q'-'0','K'-'0','A'-'0','T'-'0'  ; face card score table
     DB   3, 8, 8, 9, 0

```

Input is as a string such as `Js3sKsKh`, at pointer in `SI`. Output is `ZF = 0 and SF = OF` (test with `JG`) if player 1 wins, `SF ≠ OF` (test with `JL`) if player 2 wins or `ZF` (test with `JE`) if a draw.

**Output using DOS test program:**

# Answer
> 8 votes
# 05AB1E, ~~41~~ 37 bytes

```
•V›{₆Ÿ&∊WÍj¸•19вyεø`Ës‘ßŒQ‘ŽćS‡Pθ«}èÆ

```

-4 bytes thanks to *@Grimy*.

Input as a list of list of list of characters, like the third example input format in the challenge description. I.e. P1 `7c Qh` & P2 `8s Ks` would be input as `[[["7","c"],["Q","h"]],[["8","s"],["K","s"]]]`. (And uses `"10"` for `10`.)

Outputs a negative integer if player 1 wins; a positive integer if player 2 wins; or 0 if it's a draw.

Try it online or verify all test cases.

**Explanation:**

```
•V›{₆Ÿ&∊WÍj¸•  # Push compressed integer 36742512464916394906012008
 19в           # Convert it to base-19 as list:
               #   [18,10,16,6,17,12,15,10,14,7,13,3,11,2,11,5,9,4,8,1]
Iε             # Push the input, and map each of its hands to:
  ø            #  Zip/transpose the hand; swapping rows/columns
               #   i.e. [["8","s"],["K","s"]] → [[["8","K"],["s","s"]]
   `           #  Push them separated to the stack
    Ë          #  Check if the two suits in the top list are equal (1/0 for truthy/falsey)
    s          #  Swap to get the list with the two values
     ‘ßŒQ‘     #  Push dictionary string "JAKEQ"
     ŽćS       #  Push compressed integer 39808
     ‡         #  Transliterate these characters to these digits
      P        #  Now take the product of the two values in the list
       θ       #  Only leave the last digit (basically modulo-10)
    «          #  And merge it to the 1/0
               #  (now we have the hand values of both players,
               #   where instead of a trailing "s" we have a leading 1)
 }è            # After the map: index each value into the earlier created integer-list
               # (now we have the hand rank of both players)
   Æ           # And then reduce the resulting integers by subtracting
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* *How to compress large integers?* and *How to compress integer lists?*) to understand why `•V›{₆Ÿ&∊WÍj¸•` is `36742512464916394906012008`, `•V›{₆Ÿ&∊WÍj¸•19в` is `[18,10,16,6,17,12,15,10,14,7,13,3,11,2,11,5,9,4,8,1]`, `‘ßŒQ‘` is `"JAKEQ"`, and `ŽćS` is `39808`.

# Answer
> 5 votes
# Nibbles, 31 27 bytes

```
`/.$=+*`*.`'$`r:`#$10$~,`$$`D22-859ff1e2379fa8205a46a3

```

Thats 32 nibbles of code followed by a number that is stored as 22 hex digits. Making 54 half byte instructions in the binary form. (Nibbles isn't on TIO yet).

I found this to be a pretty cool problem. My first instinct was rather than hardcode the hand orders, calculate it! By finding how common each is, but this turned out to be longer surprisingly.

It works by converting each hand to an integer 1-20 and then looking it up it up in a table to find its relative goodness. Finally those goodnesses are subtracted so that equal hands are 0, player 1 wins positive, and player 2 wins negative.

Let's break down the code:

```
`D 22 859ff1e2379fa8205a46a3

```

becomes that data in base 22, which is

```
[5,0,18,8,7,2,19,12,7,1,14,6,9,3,15,8,10,4,20,11]

```

This code just maps on each hand and does a fold on the result

```
`/      special fold
  .$    map on input (for each hand)
    ...
  -     subtract (the type of special fold)

```

Now for the code that converts hand to a unique number for that suitedness and mod10. Multiply the product by 2 to make space for the suitedness value of 1 or 2 without conflict (this is similar to other solutions).

```
+
 * [product mod 10]
  ~     2
, `$ $  length of the unique suites

```

To calculate the hand value mod 10:

```
`*             product
  .            map
   `' $        transpose of input hand [("J",'c'), ("10",'d')] becomes
               (["J","10"],"cd") and since this is a tuple, it returns
               the first value, setting $ to be "cd" (used later)
   `r          read a number from a string in base 10
     :         list concat of
      `# $ 10  hash of the hand value mod 10 (this is to convert JQKA)
      $        the hand value string

```

Finally this is looked up in the table by just looking up the value at an index with `=`

There's a couple of cool tricks here. One is how the hash value becomes the right answer mod 10. It uses the data as salt, but the data is also being used to extract our table. This is why the table was in base 22 when we only needed base 20. It gave us some degrees of freedom to brute for search for different representations that will still give the right answer. On average we need about 10000 degrees of freedom. Since JQKA all have to go to the correct number (1/10 chance each).

This was found with brute force search using this code:

```
.| . | `*.,4`,21 ==\$`<@  # n-b=18
    `@ 22
    ..%"13,18,3,10,11,16,2,6,11,17,5,12,9,15,4,10,8,14,1,7" ',' - 18`r$
    +- 5 ?:@0~ +-@$1 $

 ==."JQKA"
  `#~ : o$ @ 10
:3:8:8 9
hex$

```

Another cool trick is how the card value is parsed. Essentially what we want to do is say if it is an integer than use its value, otherwise the hash value. But it is shorter to just always put the hash in front of the value and parse the result. Like so: "J" -\> "3J", "5" becomes "\[something\]5". In the first case the J is ignored because it isn't a digit. In the second case the \[something\] doesn't matter because the complete value is still 5 mod 10.

Also note that we don't actually ever need to do mod 10 on the product because the size of the table we are looking is size 20 and wraps (and we've multiplied by 2).

To invoke it pass the hands as command line args. List of List of tuple of Str, Char.

For example:

```
nibbles hardcode.nbl "[[(\"7\",'c'),(\"Q\",'h')],[(\"8\",'s'),(\"K\",'s')]]"

```

This problem shows off the power of a deterministic hash function already, but there's a cool idea that could improve it further but it would be computationally intractable unless the hash function can be reversed without using brute force!

The idea is rather than look up the hand in a list of goodnesses, take the hash of it. You just need to find salt that happens to give the right ordering (it doesn't have to use values 0-17).

This would be shorter because the current encoding takes log(18)\*20=83 bits but the new one would be

```
log(18!)+log(n)*2+log2(n^18*(n-18)!/n!)

```

Where n is the base to use in the hash mod. The higher it is the less likely you'll have collisions, but also the less likely you'll manage to get those two hands that are equivalent to map to the same value. This value is maximized by n being 117, giving 68 bits (but really n is another degree of freedom in the search so it could be fewer bits).

This would lead to a 2 byte savings on average! (In data alone, not counting the degrees of freedom for n, you also wouldn't need the * ~ and = instructions).

The ultimate reason less information is needed is because a list stores exact values but all we really need is an order.

This problem has inspired me to try to design a hash function that can be reversed so that a solution like this (and others for other problems) can be realized without brute force. It has gotten pretty mathy, especially when the base we are talking about isn't a prime number, but it is something I intend to revisit and hopefully write a paper and add it into nibbles!

# Answer
> 4 votes
# PHP, ~~212~~ ~~185~~ ~~178~~ 149 bytes

```
while($p=$argv[++$x])$$x=ord(rjpfqlojngmckbkeidha[(($v=[J=>3,Q=>8,K=>8,A=>9])[$p[0]]?:$p[0])*($v[$p[2]]?:$p[2])%10+($p[1]==$p[3])*10]);echo${1}-${2};

```

Try it online!

* -7 bytes thanks to @Night2!
* -29 bytes by ASCII encoding the table instead of array

Input is via command line. Output to `STDOUT` is **negative** if player 1 wins, **positive** if player 2 wins, `0` if tie. Example:

```
$ php modten.php Js3s KsKh
-1

```

# Answer
> 3 votes
# C (gcc), ~~172~~ ~~167~~ ~~165~~ ~~164~~ 162 bytes

```
char*v="T 23456789   J    QA        K";p(char*l){return"A<92?:51@:;4>893=760"[(l[1]==l[3])+(index(v,l[2])-v)*(index(v,*l)-v)%10*2];}f(char*s){return p(s+5)-p(s);}

```

Try it online!

4 bytes shaved off thanks to the amazing @ceilingcat!

Basically a port of @Joel's Python3 solution, but without the base18 encoding. Expects the input as one string with a space separating the hands of the two players, and outputs an integer that is positive, negative or zero to indicate player 1 wins, player 2 wins or if it's a draw.

# Answer
> 3 votes
# Perl 6, ~~101~~ ~~100~~ ~~94~~ 88 bytes

*-1 byte thanks to Jo King*

```
{[-] .map:{'HC92FA51GAB4E893D76'.ords[[*](.[*;0]>>.&{TR/JQKA/3889/})%10*2+[eq] .[*;1]]}}

```

Try it online!

Takes input as `f(((<J ♠>, <3 ♠>), (<10 ♠>, <K ♥>)))` using `10` for Ten. Returns a value \< 0 if player 1 wins, \> 0 if player 2 wins, 0 if it's a draw.

### Explanation

```
{
  [-]  # subtract values
  .map:{  # map both hands
    'HC92FA51GAB4E893D76'.ords[  # lookup rank in code point array
      [*](  # multiply
        .[*;0]  # card ranks
        >>.&{TR/JQKA/3889/}  # translate J,Q,K,A to 3,8,8,9
      )
      %10*2  # mod 10 times 2
      +[eq] .[*;1]  # plus 1 if suited
    ]
  }
}

```

# Answer
> 2 votes
# Jelly, 46 bytes

```
“T0J3Q8K8A9”yⱮZV€P$Eƭ€)%⁵UḌị“©N¿!Æßvṅ?żṀ’b18¤I

```

Try it online!

A full program taking as its argument for example `["7h","Ks"],["4s","Ts"]` and printing zero if both players draw, positive if player 1 wins and negative if player 2 wins.

# Answer
> 1 votes
# Charcoal, 97 bytes

```
≔”)¶＆sＮψU↓”ζＦ¹³Ｆ¹³Ｆ⁻⁴⁼ικ⊞υ⁺÷λ³⊗﹪Π⁺§ζι§ζκχ≔”A↘τ[⁵ＰkxτG”ε≔⁰δＦ⟦θη⟧≦⁻№υ⁺⁼§ι¹§ι³⊗﹪Π⁺§ζ⌕ε§ι⁰§ζ⌕ε§ι²χδＩδ

```

Try it online! Link is to verbose version of code. Takes input as two strings of 4 characters e.g. `QcKc` `6d4d` and outputs a signed integer. Explanation:

```
≔”)¶＆sＮψU↓”ζ

```

Compressed string `2345678903889` represents the card values.

```
Ｆ¹³Ｆ¹³

```

Loop over each possible pair of values.

```
Ｆ⁻⁴⁼ικ

```

Loop over each possible second card suit. Without loss of generality we can assume that the first card has suit 3, so the second card suit can range from 0 to 3 unless the values are the same in which case it can only range from 0 to 2.

```
⊞υ⁺÷λ³⊗﹪Π⁺§ζι§ζκχ

```

Compute the modified score of the hand, which is the value of the hand doubled, plus 1 if the suits are the same (i.e. the second card has suit 3).

```
≔”A↘τ[⁵ＰkxτG”ε

```

Compressed string `23456789TJQKA` represents the card characters. The input cards are looked up in this string and then the position is used to index into the first string to get the card's value.

```
≔⁰δ

```

Initialise the result to 0.

```
Ｆ⟦θη⟧

```

Loop over the two hands.

```
≦⁻№υ⁺⁼§ι¹§ι³⊗﹪Π⁺§ζ⌕ε§ι⁰§ζ⌕ε§ι²χδ

```

Calculate the modified score of the hand, and thus its frequency, and subtract the result from this.

```
Ｉδ

```

Output the frequency difference.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 139 bytes

```
x=>x.Sum(n=>(i++%2*2-1)*(n[1]==n[3]?"":" ")[n.Aggregate(1,(a,b)=>a*(b>85?1:b>83?0:b>74?8:b>73?3:b>64?9:b-48))%10]);int i

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-p`, 107 bytes

```
$a=A;y/ATJQK/90388/;${$a++}=substr"IAG6HCFAE7D3B2B59481",($1eq$3).$&*$2%10,1while/.(.) (.)(.)/g;$_=$A cmp$B

```

Try it online!

### Input:

```
As 4d,Th 8c

```

(Actually, the comma can be any character.)

### Output:

```
-1  Player one wins
 0  Draw
 1  Player two wins

```

---
Tags: code-golf, card-games
---


title: Make an ed clone

text:
# Question
Title: Make an ed clone
ed is the standard text editor on Unix systems. Your goal is to write an ed clone.

## Task

Write a program that reads an input stream and for every received end of line character, print `?` followed by a end of line character.

* The communication has to interactive. Means the program needs to output as soon as possible and has to accept more input after that.
* There are no input lines that are longer than 105 characters + end of line character
* You can choose which character or sequence you use as end of line character, as long as it does not contain any alphanumerical characters nor the `?` character.
* The program should not output anything else.

Shortest code wins.

## Example Python Script

```
#/usr/bin/env python3

import sys

for line in sys.stdin:
  print("?")

```

# Answer
# Nibbles, 2 bytes

```
@"?"

```

That's 4 nibbles at half a byte each in the binary form.

@ is the first line of input but auto maps all lines if there's more input after the first line.

Despite the simplicity of this problem I must thank it for making me make sure Nibbles is properly lazy enough to do interactive IO right. There was an issue in that it adds a newline at termination unless your last character was a newline (to not double print newlines), but that wasn't being done lazy enough and so it wasn't interactive enough to satisfy this question. But I've fixed it in latest commit (you'll need latest unstable version of nibbles).
> 1 votes

# Answer
# Charcoal, 5 bytes

```
?ＷＳＤ⎚

```

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

```
?

```

Write a `?` to the canvas, but don't print anything yet.

```
ＷＳ

```

Repeatedly input lines until there is nothing left to input...

... dump the canvas with a trailing newline.

Clear the canvas so that nothing gets output at the end.
> 0 votes

# Answer
# Perl 5.28.1 (webperl) \+ `-pl`, 6 bytes

```
$_="?"
```

Try it online!
> 0 votes

# Answer
# Ruby \+ `-pl`, 5 bytes

```
$_=??

```

Try it online!
> 0 votes

# Answer
# Python 3, ~~40~~ 27 bytes

```
for i in open(0):print("?")

```

Try it online!

-13 thanks to @ovs
> -1 votes

---
Tags: code-golf, interactive
---


title: Your trees need to be rerooted

text:
# Question
Title: Your trees need to be rerooted
In graph theory a tree is just any graph with no cycles. But in computer science we often use *rooted* trees. Rooted trees are like trees except they have one specific node as the "root", and all computation is done from the root.

The *depth* of a rooted tree is the smallest number, \\$n\\$, such that any node of the tree can be reached from the root in \\$n\\$ steps or less. If the root node is selected poorly and the depth is high this may mean that to get to certain nodes from the roots takes many steps.

Over time as we perform computation our rooted tree may change shapes so, we'd like to then "re-root" the tree. That is without changing the underlying tree change the root of the tree so that the resulting rooted tree has as low a depth as possible.

## Task

In this challenge you will be given as input a rooted tree with positive integers at every vertex. You should output the re-rooted tree. That is a tree which has it's root selected to minimize depth but is otherwise identical.

You may take input in any reasonable format but please state your format so your answers can be tested. You should take input and give output using the same format. The input will always have at least 1 node

This is so answers will be scored in bytes with the goal being to minimize the size of your source-code.

## Test Cases

In the test cases we represent trees as a list of nodes. Each node is a tuple containing its value and a list of children represented as their indexes in the list. The root node is at index `0`.

This way of representing trees is not unique so if you use this format you may get output that is isomorphic to the given result but not identical.

```
[(1,[1]),(9,[2]),(5,[])] -> [(9,[1,2]),(1,[]),(5,[])]
[(1,[1]),(9,[2]),(5,[3]),(7,[])] -> [(9,[1,2]),(1,[]),(5,[3]),(7,[])] or [(5,[1,3]),(9,[2]),(1,[]),(7,[])]
[(1,[1]),(8,[2,3]),(7,[]),(9,[])] -> [(8,[1,2,3]),(1,[]),(7,[]),(9,[])]

```

# Answer
# Wolfram Language (Mathematica), 63 bytes

```
GraphTree[g=UndirectedGraph@TreeGraph@#,Last@GraphCenter@g,#&]&

```

Takes input as a Tree object, e.g., `Tree[1, {Tree[9, {Tree[5, None]}]}]`.

Tree objects are introduced in Mathematica 12.3, so no TIO.

Outputs for the test cases:

```
Tree[1, {Tree[9, {Tree[5, None]}]}] -> Tree[9, {Tree[1, None], Tree[5, None]}]
Tree[1, {Tree[9, {Tree[5, {Tree[7, None]}]}]}] -> Tree[9, {Tree[1, None], Tree[5, {Tree[7, None]}]}
Tree[1, {Tree[8, {Tree[7, None], Tree[9, None]}]}] -> Tree[8, {Tree[1, None], Tree[7, None], Tree[9, None]}]

```

---

# Wolfram Language (Mathematica), 63 bytes

-3 bytes thanks to @att.

```
-(-#//.-a_[b___,c_@d___,e___]/;Depth@b?e<Depth@!d:>-b~a~e~c~d)&

```

Try it online!

Takes input as a Mathematica expression, e.g., `1[9[5[]]]`.

Outputs for the test cases:

```
1[9[5[]]] -> 9[1[], 5[]]
1[9[5[7[]]]] -> 9[1[], 5[7[]]]
1[8[7[], 9[]]] -> 8[1[], 7[], 9[]]

```

Or 59 bytes if we can take input as `-1[9[5[]]]` (I'm not sure if prepending a minus sign is a reasonable format. The output also has this minus sign):

```
#//.-a_[b___,c_@d___,e___]/;Depth@b?e<Depth@!d:>-b~a~e~c~d&

```

Try it online!
> 3 votes

# Answer
# Python3, 527 bytes:

```
from itertools import*
p=lambda x,i=0:[(x[i][0],x[j][0])for j in x[i][1]]+p(x,i+1)if i<len(x)else[]
d=lambda x,i=0:1+(max(d(x,l)for l in x[i][1])if x[i][1]else 0)
def f(n,p,c,u=[]):
 if not p:yield c
 else:
  if(x:=(i:=n.index)(p[0][0]))<(y:=i(p[0][1]))and y not in u:yield from f(n,p[1:],c[:x]+[(c[x][0],c[x][1]+[y])]+c[x+1:],u+[y])
  elif x not in u:yield from f(n,p[1:],c[:y]+[(c[y][0],c[y][1]+[x])]+c[y+1:],u+[x])
e=lambda x:min([j for k in permutations([i[0]for i in x],len(x))for j in f(k,p(x),[(i,[])for i in k])],key=d)

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~60~~ 59 bytes

```
≔ＥθＥθ∨⁼κμ∨№η⟦κμ⟧№η⟦μκ⟧ζ≔ＥζιεＷ¬⊙ε⌊κＵＭεＥκ⊙ζ∧§κπ§ξν⭆¹⟦θη⌕Ｅε⌊λ¹

```

Try it online! Link is to verbose version of code. I/O is a list of node values, an adjacency list and the root node. Explanation:

```
≔ＥθＥθ∨⁼κμ∨№η⟦κμ⟧№η⟦μκ⟧ζ

```

Calculate the adjacency matrix.

```
≔Ｅζιε

```

Make a shallow clone we can safely mutate.

```
Ｗ¬⊙ε⌈κ

```

Until at one node can reach all the other nodes...

```
ＵＭεＥκ⊙ζ∧§κπ§ξν

```

... calculate the adjacency matrix for the next depth.

```
⭆¹⟦θη⌕Ｅε⌊λ¹

```

Output the original tree but with the new root node which the first node that can reach all the other nodes at the current depth.
> 2 votes

# Answer
# JavaScript + DOM, 154 bytes

```
n=>R(D([R(D([n]))]).slice(P.length/2))
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c

```

Input a root `HTMLElement`. Output new root after re-root.

```
f=

n=>R(D([R(D([n]))]).slice(P.length/2))
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c

tree2Dom = ([name, children], parent = document.createElement('div')) => {
  parent.id = name;
  children.forEach(node => parent.append(tree2Dom(node)));
  return parent;
};
dom2Tree = node => [node.id, [...node.children].map(child => dom2Tree(child))];

testcases = [
['1', [['9', [['5', []]]]]],
['1', [['9', [['5', [['7', []]]]]]]],
['1', [['8', [['7', []], ['9', []]]]]],
];

testcases.forEach(t => {
  console.log(JSON.stringify(dom2Tree(f(tree2Dom(t)))));
});
```

With comment

```
// Find out the deepest element in root, output that element and all its parents
D=(h,...t)=>P=h&&D(...t,...[...h[0].children].map(x=>[x,...h]))||h
// Re-root the tree to c, input c and its parents
R=([c,...p])=>p[c.remove(),0]&&c.append(R(p))||c
// Find out the new root and re-root
n=>R(D([R(D([n]))]).slice(P.length/2))

```
> 1 votes

---
Tags: code-golf, graph-theory, tree-traversal
---


title: Who Is Kevin Bacon?

text:
# Question
Title: Who Is Kevin Bacon?
You may know the game *The Six Degrees of Kevin Bacon*, based on the conjecture that every actor in Hollywood can be connected to Kevin Bacon by no more than 6 "co-star" relations, so Kevin Bacon is supposedly the "best-connected" node in that graph. Your task will be to find the Kevin Bacon of a graph.

We will use positive integers to represent actors, and use a list of pairs which defines the relations of the graph (adjacency list). For example, `[(1, 2), (2, 3)]` defines that `1` has costarred with `2`, and `2` has costarred with `3`.

We will measure "connectedness" using *average shortest path length*:

* The shortest path length is the number of steps in the shortest path between two given nodes. In the example graph above, the shortest (and also only) path between `1` and `3` is `1 -> 2 -> 3`, which has path length 2
* The average shortest path length of a node `A` is the mean of the shortest path lengths between `A` and each other node in the network

Your task is to, given an adjacency list, find the best-connected node in the graph. That is, find the node `A` such that this average is minimised, and output its number.

If there are multiple nodes with the same average shortest path length, you may output any of them.

## Worked example

Consider the small graph:

```
    1-----2
   / \    |
  3---4   5

```

which would be represented by the adjacency list:

```
[(1, 2), (2, 5), (1, 3), (1, 4), (3, 4)]

```

Now we compute the shortest path length between each pair of nodes (ignoring the relations between nodes and themselves):

```
  |1 2 3 4 5
--+---------
1 |  1 1 1 2
2 |1   2 2 1
3 |1 2   1 3
4 |1 2 1   3
5 |2 1 3 3

```

For each node we can then compute the average of its path lengths to all the other nodes:

```
1 ~> 1.25  [  (1+1+1+2)/4 = 5/4 = 1.25  ]
2 ~> 1.5
3 ~> 1.75
4 ~> 1.75
5 ~> 2.25

```

So node `1` has the smallest average shortest path length, so the output is `1`.

## Rules

* You may assume the input is non-empty, contains no self-referential pairs (like `(3, 3)`), and no duplicate edges (like `[(3, 1), (1, 3)]`)
* You may assume all nodes of the graph are connected somehow (for example, you don't have to handle `[(1, 2), (3, 4), (5, 3)]`)
* You may assume the set of integers used for node IDs is `1` to `N` (inclusive) for some N. For example, you don't have to handle `[(1, 54), (54, 128)]` nor `[(2, 3), (2, 4)]`
    + You may alternately choose to assume this range is `0` to `N-1`
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

## Test cases

```
Input:  [(1, 2), (2, 5), (1, 3), (1, 4), (3, 4)]
Output: 1

Input:  [(1, 2), (2, 3), (3, 4), (4, 5)]
Output: 3

Input:  [(1, 2), (2, 3), (3, 4), (4, 1), (2, 5)]
Output: 2

Input:  [(1, 2)]
Output: 1 or 2

Input:  [(6, 1), (5, 2), (2, 1), (1, 5), (6, 3), (6, 4), (3, 4), (6, 2), (3, 7)]
Output: 6

```

# Answer
# BQN\*, ~~53~~ 45 bytesSBCS

```
{1+⊑⍒+˝+´(∨∨∨˝∘×⎉1‿∞)⍟n˜∨⟜⍉∨˝≡⌜1+⋈⌜˜n←↕⌈´∾}

```

Run online!

**Theory:**

Let \\$k\\$ be the maximum node id. Then the node IDs are \\$\\{1, 2, ..., k\\}\\$.
For the given adjacency list we can construct an adjancency matrix \\$A=(a\_{ij}) \in \\{0,1\\}^{k \times k}\\$, where \\$a\_{ij} = 1\\$ iff \\$i=j\\$ or node \\$i\\$ and node \\$j\\$ are adjacent.

The distance between two nodes in the graph is given by the smallest \\$m\\$, such \\$A^m\\$ has a non-zero entry at the position.†

**Implementation:**

`∨⟜⍉∨˝≡⌜1+⋈⌜˜n←↕⌈´∾`
Convert the adjacency list to a modified adjacency matrix \\$A-I\_k\\$ with zeros on the diagonals. This part is a bit lengthy, maybe  can be used?

`(∨∨∨˝∘×⎉1‿∞)⍟n˜`
Calculate \\$A-I\_k, \mathop{sign}(A^2), \mathop{sign}(A^3), \cdots, \mathop{sign}(A^{k-1})\\$. In normal matrix multiplication you would use `+` instead of , but here we only care for zero / non-zero.

`+˝+´`
Sum the resulting \\$k\\$ matrices, then each row. This is some kind of *inverse summed shortest path length*. This could be converted to the *average shortest path length*, but that step is not necessary as the order is the same, but reversed.

`1+⊑⍒`
Get the 1-based index of the maximum value. Using 0-indexing for the node IDs would save two bytes.

*According to the documentation, in this situation the name can be pronounced *bacon*
†Slightly longer explanation can be found on Wikipedia
> 12 votes

# Answer
# Wolfram Language (Mathematica), 46 bytes

-12 bytes thanks to @att.

```
g#&@@SortBy[##&@@@g,Tr[g~GraphDistance~#]&]

```

Try it online!

Takes input as a list of `a <-> b`s, e.g. `{1 <-> 2, 2 <-> 5, 1 <-> 3, 1 <-> 4, 3 <-> 4}`.

Sadly the `GraphCenter` built-in uses the *maximal* (instead of *average*) shortest path length.
> 8 votes

# Answer
# , 72 71 73 bytes

```
1+[:(i.<./)1#.[:+/@(*#\)2-~/\0,[:+./ .*^:a:~@(+[:=#\)[:+/](-{.1:)"1@,|."1

```

Try it online!

**Input:** 1-indexed adjacency list.

**Output:** 1-indexed answer.

## how

Consider:

```
1 2
2 5
1 3
1 4
3 4

```
* `[:+/](-{.1:)"1@,|."1` \- Converts the adjacency list to an adjacency matrix. This was the hardest part to golf, and it's still long.

+ `]...,|."1` First we concatenate the list with a copy of itself, with each row reversed:

    ```
    1 2
    2 5
    1 3
    1 4
    3 4
    2 1
    5 2
    3 1
    4 1
    4 3

    ```
    + `(-{.1:)"1` \- Then we create matrices of each of those sizes, with a `1` in the bottom right corner. I'll display them boxed, before the automatic 0 fill, for clarity:

    ```
    ┌───┬─────────┬─────┬───────┬───────┬─┬───┬─┬─┬─────┐
    │0 1│0 0 0 0 0│0 0 1│0 0 0 1│0 0 0 0│0│0 0│0│0│0 0 0│
    │   │0 0 0 0 1│     │       │0 0 0 0│1│0 0│0│0│0 0 0│
    │   │         │     │       │0 0 0 1│ │0 0│1│0│0 0 0│
    │   │         │     │       │       │ │0 0│ │1│0 0 1│
    │   │         │     │       │       │ │0 1│ │ │     │
    └───┴─────────┴─────┴───────┴───────┴─┴───┴─┴─┴─────┘

    ```

    Once the fill is added it looks like:

    ```
    0 1 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 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 0 0 0
    0 0 0 0 0

    0 0 1 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    .
    .
    .

    ```
    + `[:+/` \- Finally we sum the layers, giving us the adjacency matrix:

    ```
    0 1 1 1 0
    1 0 0 0 1
    1 0 0 1 0
    1 0 1 0 0
    0 1 0 0 0

    ```
* `(+[:=#\)` Next we add the diagonal of ones (nodes are already connected to themselves).

```
1 1 1 1 0
1 1 0 0 1
1 0 1 1 0
1 0 1 1 0
0 1 0 0 1

```
* `+./ .*^:a:~` Matrix "or multiply" with self, until we reach a fixed point, saving intermediate values. The additional ones added in iteration `n` represent nodes that can be reached in `n` hops.
* `2-~/\0,` We want to separate each iteration's contribution, so we take successive deltas, starting with a matrix of all zeros:

```
1 1 1 1 0
1 1 0 0 1
1 0 1 1 0
1 0 1 1 0
0 1 0 0 1

0 0 0 0 1
0 0 1 1 0
0 1 0 0 0
0 1 0 0 0
1 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 0 1
0 0 1 1 0

```
* `(*#\)` Multiply each of those values by its iteration number:

```
1 1 1 1 0
1 1 0 0 1
1 0 1 1 0
1 0 1 1 0
0 1 0 0 1

0 0 0 0 2
0 0 2 2 0
0 2 0 0 0
0 2 0 0 0
2 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 3
0 0 0 0 3
0 0 3 3 0

```
* `+/@` And sum the layers:

```
1 1 1 1 2
1 1 2 2 1
1 2 1 1 3
1 2 1 1 3
2 1 3 3 1

```
* `1#.` Then sum the rows:

```
6 7 8 8 10

```
* `1+[:(i.<./)` Finally return the minimum value's index, plus 1:

```
1

```
> 6 votes

# Answer
# Python 3, 234 bytes

```
def f(l):
 m=1+max(map(max,l));g=eval(str([[m]*m]*m))
 for a,b in l:g[a][a]=g[b][b]=0;g[a][b]=g[b][a]=1
 for x in range(m**3):k=x%m;x//=m;j=x%m;i=x//m;g[j][k]=min(g[j][k],g[j][i]+g[i][k])
 return min((sum(g[i]),i)for i in range(m))[1]

```

Try it online!

Implementing simple Floyd-Warshall. This is my first time here. Any tips are welcome!
> 6 votes

# Answer
# , ~~120~~ ~~113~~ ~~111~~ ~~107~~ ~~106~~ 102 bytes

Or **\>=4.1, 95 bytes** by replacing the word `function` with a `\`.

*Edit: -7 bytes and -4 bytes thanks to @Giuseppe. -1 byte thanks to @Dominic van Essen. -4 bytes inpired by @Dominic van Essen's answer to related challenge.*

```
function(v){A=diag(m<-max(v))
A[v]=1
C=B=A=A|t(A)
for(i in 2:m)B[(C=C%*%A)&!B]=i
order(colSums(B))[1]}

```

Try it online!

Straightforward approach:

1. Calculate adjacency matrix `A`.
2. Gradually increase powers of `A` (stored in `C`) to see when will appear the first non-zero entry for each pair of indices. *(Where's built-in matrix power when you need one?)*
3. Store the distances in `B`.
4. Find the column with the smallest sum.
> 5 votes

# Answer
# Jelly, 27 bytes

```
;©U;þ®ẎḢ⁼ṪƊƇƊLÐ¡ŒṬ€ĖP€o/SİM

```

A monadic Link accepting the adjacency list specified that yields a list of all of the Kevin Bacons of that graph.

**Try it online!**

How?

We first produce lists of all pairs of nodes linked by `1, 2, 3, ...` steps (up to `2p+1` where `p` is the number of pairs in the input, just for golfing purposes) - including redundancies and self-linked pairs.

Then we turn each of these into tables showing the number of steps taken, if possible, or zero if not - i.e. the first is `0` or `1` at each point, the second is `0` or `2` at each point, and so on.

We then reduce these by logical OR, giving us the shortest length table shown in the question with a leading diagonal filled with `2`s (since we are guaranteed a fully-connected graph, we will always produce a `2` at this position in the second previous table by following a given pair and its reverse, and the logical OR will keep this value if we could do the same in more steps).

Then we sum the columns, inverse and find maximal indices (aligning with the guaranteed `[1,n]` node numbering).

```
;©U;þ®ẎḢ⁼ṪƊƇƊLÐ¡ŒṬ€ĖP€o/SİM - Link: adjacency list, A
  U                         - reverse each pair in A
;                           - concatenate that to A
 ©                          - copy this to the register for later
              Ð¡            - collect up and repeat:
             L              - ...times: length (of the new list)
            Ɗ               - ...what: the last three links as a monad, f(current):
     ®                      -     use the register as the right argument of:
    þ                       -       (current) table (register) using:
   ;                        -         concatenation (e.g. [2,5];[1,2] -> [2,5,1,2])
      Ẏ                     -     tighten (from a table to a row-major order list)
           Ƈ                -     filter keep those for which:
          Ɗ                 -       last three links as a monad:
       Ḣ                    -         pop and yield head
         Ṫ                  -         pop and yield tail
        ⁼                   -         equal? (leaving the inner two
                                              e.g. [2,5,1,2] -> [5,1]
                                              which is kept since 2=2)
                  €         - for each:
                ŒṬ          -   make a table with 1s at the given coordinates)
                   Ė        - enumerate -> [[1,first],[2,second],...]
                    P€      - product of each
                      o/    - reduce by logical OR
                        S   - sum columns
                         İ  - inverse
                          M - maximal indices (1-indexed)

```
> 5 votes

# Answer
# 05AB1E, ~~44~~ 42 bytes

*I guess crossed out 44 is no longer a thing with the new font. ;)*

```
ZL©ε®yKδ‚εUæ€œ€`ʒнXнåyθXθåyüå€àPP}€gß]OWk>

```

Takes advantage of the rule "*You may assume the set of integers used for node IDs is positive and contiguous.*" to save some bytes, although it still feels pretty long..

Try it online or verify almost all test cases (the largest/last test case times out and is omitted in the test suite).

**Explanation:**

```
Z            # Get the flattened maximum of the (implicit) input-list of pairs
 L           # Pop and push a list in the range [1,max]
  ©          # Store it in variable `®` (without popping)
   ε         # Map over each integer:
    ®        #  Push the [1,max] list from variable `®` again
     yK      #  Remove the current integer from it
       δ     #  Map over each remaining integer:
        ‚    #   Pair it with the current integer
    ε        #  Map over each pair:
     U       #   Pop the current pair and store it in variable `X`
      æ      #   Get the powerset of the (implicit) input-list of pairs
       €œ    #   Get the permutations of each inner list
         €`  #   Flatten it one level down
     ʒ       #   Filter over this list of potential paths:
      н      #    Pop and push the first pair
       Xнå   #    Check if the first value of `X` is in this pair
      yθXθå  #    Do the same for the last pair and last value of `X`
      y      #    Then push the list of pairs again
       ü     #    For each overlapping pair of pairs:
        å    #     Check for both values in the second pair if it's in the first
             #    (this will result in an empty list for single-pair lists)
         €à  #    Check for each overlapping check if either is truthy
           P #    Check if all overlapping checks are truthy
      P      #    Check if all three checks are truthy
     }€g     #   After the filter: get the length of each valid path
        ß    #   Pop and push the minimum path-length
   ]         # Close both the inner and outer maps
    O        # Sum each inner list (shorter than the average)
     W       # Push the minimum sum (without popping the list)
      k      # Get the (first) 0-based index of this minimum
       >     # Increase it by 1 to make it a 1-based index
             # (after which this is output implicitly as result)

```
> 4 votes

# Answer
# Charcoal, ~~82~~ 81 bytes

```
≔⊕⌈Ｅθ⌈ιη≔ＥηＥη∨⁼ιλ∨№θ⟦ιλ⟧№θ⟦λι⟧η≔Ｅηιζ≔ＥηιεＦη«ＵＭζＥκ⊙η∧§κπ§ξνＵＭεＥκ⁺μ§§ζλν»ＵＭεΣιＩ⌕ε⌈ε

```

Try it online! Link is to verbose version of code. Explanation: Port of ovs's "Bacon" answer.

```
≔⊕⌈Ｅθ⌈ιη

```

Get the number of nodes.

```
≔ＥηＥη∨⁼ιλ∨№θ⟦ιλ⟧№θ⟦λι⟧η

```

Calculate the adjacency matrix.

```
≔Ｅηιζ≔Ｅηιε

```

Create two shallow clones as we'll be mutating these.

```
Ｆη«

```

Repeat for each node, to ensure that all nodes are eventually reached.

```
ＵＭζＥκ⊙η∧§κπ§ξν

```

Update the first clone to the adjacency matrix at the next depth.

```
ＵＭεＥκ⁺μ§§ζλν

```

Add it to the second clone.

```
»ＵＭεΣι

```

Sum the rows of the second clone.

```
Ｉ⌕ε⌈ε

```

Find the index of the largest sum.
> 4 votes

# Answer
# Perl 5 List::Util, 174 bytes

```
sub{$S=99;sub D{$_[0]-$a?1+min map D(@$_),grep$_[0]==$$_[1]&&!$b{$$_[0]}++,@g:0}for$a(@a=uniq map@$_,@g=map{$_,[@$_[1,0]]}@_){$S=$s,$A=$a if$S>($s=sum map{%b=();D($_)}@a)}$A}

```

Try it online!
> 3 votes

# Answer
# Python3, 276 bytes:

```
lambda g:min(enumerate(n:=[*{i for k in g for i in k}]),key=lambda x:sum(min(p(g,x[1],j))for j in n[:x[0]]+n[x[0]+1:])/float(len(n)-1))[1]
def p(g,s,e,c=[]):
 if s==e:yield len(c)
 else:
  for i in g:
   if s in i and(j:=[i[0],i[1]][s==i[0]])not in c:yield from p(g,j,e,c+[s])

```

Try it online!
> 3 votes

---
Tags: code-golf, graph-theory, path-finding, optimization
---


# Question
Title: Can I shorten this Python code for simulating a car driving around
I am trying to write a solution to the following problem using as few characters as possible (to meme my friend and introduce him to golfing). Can any improvements be done to my code?

So the problem requires us to write a function called `navigate` in Python 3.6 (language of the judge, sorry, no walruses) that takes two arguments:

* the first is a list of strings called "commands", which can be chosen from the following: `Drive`, `TurnL`, `TurnR`
* the second is a tuple of three element, the first two are integers describing, respectively, the `x` and `y` coordinates of a "car", and the third element of the tuple is a single-character string chosen out of `N`, `E`, `S` and `W`, describing the direction which the car is facing initially

and returns a tuple with the same format as the second argument, which denotes the final coordinates and orientation of the car.

The commands are defined as follows (I tried to make them rigorous):

* `TurnL`: change the orientation of the car with the following map: `f:{N->W->S->E->N}`
* `TurnR`: change the orientation of the car with the inverse of `f`
* `Drive`: increment or decrement the value of `x` or `y` by 1, depending on the current orientation (see below table)

| orientation | change in `x` | change in `y` |
| --- | --- | --- |
| N | 0 | 1 |
| E | 1 | 0 |
| S | 0 | -1 |
| W | -1 | 0 |

---

My current progress is 189 Bytes:

```
N,E,S,W='NESW'
def navigate(c,s):
 x,y,d=s
 for i in c:
  if i[4]=='L':d={N:W,W:S,S:E,E:N}[d]
  elif i[4]=='R':d={N:E,E:S,S:W,W:N}[d]
  else:x+=(d==E)-(d==W);y+=(d==N)-(d==S)
 return x,y,d

```

I do not think typing out the long word "navigation" is avoidable. However, although the question asks for an implementation of a function, I do believe any callable, including anonymous functions, methods, etc., would be accepted.

---

Below is a test case

```
>>> navigate(['Drive', 'TurnR', 'Drive'], (0, 0, 'E'))
(1, -1, 'S')

```

# Answer
> 7 votes
# Flip comparisons

You can remove the space after `if` if you swap the order of the string comparisons, so `if i[4]=='L'` becomes `if'L'==i[4]`.

# String ordering

Because strings in Python can be compared, and are ordered alphabetically (with lowercase coming after uppercase, according to their ASCII codes), and we know the 5th character of each input string will always be `L`, `R`, or `e`, we can change `==` to `>` and compare with the next letter in the alphabet in each case. `if'L'==i[4]` becomes `if'M'>i[4]`.

# Unpacking `i`

*Thanks to @ovs for this suggestion*

Because `i[4]` is always the last character in the string `i`, we can unpack it with Python's `*` syntax in the for loop (`for*_,i in c:`), and remove both instances of `[4]`. The first 4 characters are stored in `_` \- which we just ignore - and the last becomes `i`.

# Complex numbers

Complex numbers are often useful in problems like this, because you can do arithmetic with them like you can with vectors. This avoids the need for two separate variables, and eliminate the costly direction maps you used (`d={N:W,W:S,S:E,E:N}`).

`1j**'ENW'.find(D)` converts a direction character into a complex number which points in that direction. `'ENW'.find(d)` returns the index of `D` in that string, so `0` for `E`, `1` for `N`, `2` for `W`, and, because `S` is not present, it returns `-1`. When we use `1j**`, this gets the complex number with the right direction using the fact that \\$ i \\$ (`1j`), when exponentiated, returns different rotations of the complex numbers. \\$ i^{-1} \\$ is the same as \\$ i^3 \\$, so that handles the `S` case.

`d*=1j` and `d/=1j` turn `d` by 90° anticlockwise and clockwise respectively, again using \\$ i \\$'s rotation-like properties.

# Python, 167 bytes

```
def navigate(c,s):
 x,y,D=s;p=0;d=1j**'ENW'.find(D)
 for*_,i in c:
  if'M'>i:d*=1j
  elif'S'>i:d/=1j
  else:p+=d
 return p.real+x,p.imag+y,'WESN'['-1-1j'.find(str(d))]
```

Attempt This Online!

This is a start. I feel like I'm missing a trick in converting `p` back to a coordinate pair, because `.real` `.imag` is quite verbose.

Thanks to @ovs for the slightly better way of converting the complex numbers back to compass directions, by storing overlapping string representations of the possible values, and searching within it.

---

Also, I don't know if it's possible to switch to Python 2, but if you can, you can save some bytes:

* 2 bytes by extracting the `s` tuple inside the function argument list
* 3 bytes using the `expression` for converting values to strings

# Python 2, 162 bytes

```
def navigate(c,(x,y,D)):
 p=0;d=1j**'ENW'.find(D)
 for*_,i in c:
  if'M'>i:d*=1j
  elif'S'>i:d/=1j
  else:p+=d
 return p.real+x,p.imag+y,'WESN'['-1-1j'.find(`d`)]
```

Attempt This Online!

# Answer
> 6 votes
pxeger's answers covers how this problem would best apporached on our site, where input and output formats are often flexible. However, with your fixed format we can do a bit better by mostly working within the format.

Our starting point is your function with a few improvements taken from the other answer (182):

```
N,E,S,W='NESW'
def navigate(c,s):
 x,y,d=s
 for*_,i in c:
  if'L'==i:d={N:W,W:S,S:E,E:N}[d]
  elif'R'==i:d={N:E,E:S,S:W,W:N}[d]
  else:x+=(d==E)-(d==W);y+=(d==N)-(d==S)
 return x,y,d

```

Try it online!

---

First, lets focus on the rotations. Dictionaries are convenient data structures to implement lookup tables, but are a bit lengthy. Using strings instead can help here:

```
  if'L'==i:d='WSEN'['NWSE'.find(d)]
  elif'R'==i:d='ESWN'['NESW'.find(d)]

```

With a bit of reordering, we can use the same value for the `'...'.find` expression:

```
  j='NWSE'.find(d)
  if'L'==i:d='WSEN'[j]
  elif'R'==i:d='ENWS'[j]

```

And `str.find` returns `-1` if the value is not in the string, which means `E` can be removed.

The two cases are now quite similar and can be combined into one by shifting the index based on `i`:

```
  j='NWS'.find(d)
  if'e'>i:d='WSEN'[j-(2 if i>'L' else 0)] # shorter with j-2*(i>'L')

```

Plugging this into our starting point, we get to 155 bytes:

```
def navigate(c,s):
 x,y,d=s
 for*_,i in c:
  j='NWS'.find(d)
  if'e'>i:d='WSEN'[j-2*(i>'L')]
  else:x+=(d=='E')-(d=='W');y+=(d=='N')-(d=='S')
 return x,y,d

```

Try it online!

---

Now we can look at the moving part. The value of `j` can be used here as well, to get expressions to update the position:

| `d` | `j='NWS'.find(d)` | `j%2*j` | `~j%2*~-j` |
| --- | --- | --- | --- |
| N | 0 | 0 | -1 |
| W | 1 | 1 | 0 |
| S | 2 | 0 | 1 |
| E | -1 | -1 | 0 |

# Python 3, 134 bytes

```
def navigate(c,s):
 x,y,d=s
 for*_,i in c:
  j='NWS'.find(d)
  if'e'>i:d='WSEN'[j-2*(i>'L')]
  else:x-=j%2*j;y-=~j%2*~-j
 return x,y,d

```

Try it online!

Finally, a few more bytes can be saved by using `ord(d)` instead of `'NWS'.find(d)` and using short position and direction update formulas found by a brute force search: 131 bytes

---
Tags: code-golf, grid, tips, python
---


title: Mutually recursive lists

text:
# Question
Title: Mutually recursive lists
Let's define a simple function \\$f\\$ which takes an integer and produces a list:

\\$ f(n) = \[g(1),g(2),\dots,g(n)\] \\ g(n) = \[f(0),f(1),\dots,f(n-1)\] \\$

We can then calculate the first couple of values for \\$f(n)\\$:

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

```

And we notice that each one is bigger than the last and has the last list as a prefix to itself.

So we could say that \\$f(\infty)\\$ is the infinite sequence such that each \\$f(n)\\$ is the first \\$n\\$ entries of it.

Now infinite lists of lists of lists ... are a little complicated so instead we will just treat \\$f(\infty)\\$ as an infinite sequence of opening and closing brackets. The `,`s are redundant so we just omit them. In fact we don't need to even deal with the brackets since there are only two values we can make a binary sequence!

```
1110011011100001101110001110011011100000011011100011100110111000001110011011100001101110001110011011100000001...
[[[]][[][[[]]]][[][[[]]][[[]][[][[[]]]]]][[][[[]]][[[]][[][[[]]]]][[[]][[][[[]]]][[][[[]]][[[]][[][[[]]]]]]][...

```

## Task

Your task is to output the binary sequence given by \\$f(\infty)\\$. You can choose any two distinct values for `1` and `0`. IO otherwise uses defaults. Read the tag wiki for precise info.

This is so answers will be scored in bytes with the goal being to minimize your source code size.

## Test cases

Here's the first 10000 entries

```
[encoded data, 10000 characters]

```

# Answer
# Haskell, 45 bytes

The top line is a function that returns the nth digit (0-based).

```
(!!)=<<f 1
f d n=1:(f(1-d)=<<[d..n-1+d])++[0]

```

Try it online!

The function `f` generates both \\$f(n)\\$ with `d=1` and \\$g(n)\\$ with `d=0`. The top line is a point free version of

```
h n = f 1 n !! n

```

where `!!` is Haskells indexing operator.
> 11 votes

# Answer
# JavaScript (ES6), 71 bytes

Returns the \\$n\\$-th term, 0-indexed.

Very inefficient because it generates way more terms that needed.

```
n=>(F=n=>n?(g=(n,c=F,h=k=>k>n?0:c(k++)+h(k))=>1+h``)(n-1,g):'10')(n)[n]

```

Try it online!
> 3 votes

# Answer
# Charcoal, 32 bytes

```
⊞υ10Ｗ¬›Ｌ⌈υ⊗θ⊞υ⪫10⭆υ⪫10⪫…υ⊕λω§⊟υＮ

```

Try it online! Link is to verbose version of code. Outputs the `n`th digit (0-indexed). Explanation:

```
⊞υ10

```

Start with the base case.

```
Ｗ¬›Ｌ⌈υ⊗θ

```

Repeat until the string is way long enough.

```
⊞υ⪫10⭆υ⪫10⪫…υ⊕λω

```

Generate the next iteration.

```
§⊟υＮ

```

Output the `n`th value.
> 3 votes

# Answer
# Ruby, ~~59~~ 52 bytes

```
p(1).step &f=->n,a=0{p 1
n.times{|x|f[x+a,1-a]}
p 0}

```

Try it online!

* Saved 7 Bytes thanks to @ovs Outputs terms indefinitely on new lines.
Straightforward approach:

> actually saved many bytes by using ovs idea to use just one function behaving differently

p 1           we first print a 1 because we call g(1..) note that we do not need to close an infinite stream.
1.step &$     again: we call g(1..

$f=->n,a=0    a=0->g() , a=1->f()
{p 1          put a 1: open [
(a...n+a).map{|x|$f[x,1-a]}  inner calls
p 0           put a 0: close ]
```
</code></pre>
> 3 votes

# Answer
# Haskell, 49 bytes

Since it's been beat here's my original Haskell solution. It takes a radically different approach.

```
x!y|q<-x++y++[0]=y++0:q!(y++q++[0])
1:[1]![1,1,0]

```

Try it online!

Looking at this, you can start to see the relationship between the lengths of the terms and the Fibonacci sequence as pointed out by Arnauld.
> 2 votes

# Answer
# 05AB1E, ~~19~~ 18 bytes

```
TλèληJ01ý11ì00«}I£

```

Outputs the first \\$n\\$ bits. Could alternatively output the 0-based \\$n^{th}\\$ bit by replacing the trailing `£` with `è`.
Becomes slower the larger \\$n\\$ becomes, because it will calculate all bits representing \\$f(n)\\$ first, before leaving just the first \\$n\\$.

Try it online.

Could have been shorter if 05AB1E had a `to_string` function for lists somehow, since `¯¸λèλη` (7 bytes) already outputs \\$f(n)\\$ including commas and spaces.

Try it online.

**Explanation:**

```
 λ               # Start a recursive environment
  è              # to output the (implicit) input'th value
T                # Starting with a(0) = "10"
                 # Where every following a(n) is calculated as follows:
   λ             #  Push all previous terms as list: [a(0),a(1),...,a(n-1)]
    η            #  Pop and push the prefixes of this list
     J           #  Join each inner prefix-list together to a string
      01ý        #  Join this list of strings with "01"-delimiter
         11ì     #  Prepend a leading "11" to the string
            00«  #  Append a trailing "00" to the string
 }               # After the recursive function:
  I£             # Leave just the first input amount of digits
                 # (after which the result is output implicitly)

```
> 0 votes

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


title: Hide a message in an image - Cops

text:
# Question
Title: Hide a message in an image - Cops
Robbers thread

Your task is to create a method for hiding information in an image. You will post three encoded messages of your choice (keep them classy), each with its associated image. Reveal the messages for the first two images and do not reveal the third. Robbers have the task of determining what your third hidden message is, along with an explanation of how your system works.

## Rules and Scoring

* Any data aside from the image required to make your algorithm work must be revealed openly and be constant across all possible message encodings.
    + For example, you may have a book cipher referencing The Great Gatsby (which is in the public domain as of January 1, 2021) as long as you link to the exact text required to make your system work.
    + RNG and Cryptographic algorithms are allowed under this caveat. Robbers should not be required to guess cryptographic secrets such as keys, hashes, salts, or initial seeds, as that easily makes cracking any given challenge infeasible. That would ruin the fun.
    + Do not share irrelevant information, e.g. "It's one of these 100 books" when you only use 1, or revealing a key which you don't use at all in your system, etc...
* Data may not be hidden entirely in image metadata; you must incorporate at least one bit of one pixel in your system of encoding.
* The encoded messages must be in English.
* The encoded message does not need to be easily machine-readable (though it's perfectly acceptable if it is), but must be reasonably legible as rendered.
    + For example, you could have the message manifest itself as a rendering in Arial. Or perhaps it renders as a figlet font in ascii art.
    + The hidden message being rendered in something like Wingdings would be unacceptable, however. Using a frilly gothic font is probably pushing it.
* You may encode the message as audio as long as it is intelligible to a fluent English speaker.
* The encoded message should always be in the same format. So for example, using a rendered hidden text image for one message, an audio recording for the second, and plain text for the third, would not be allowed.
* Data required to render the message as an image or audio is not considered part of the data required to make your algorithm work (which you would otherwise need to reveal)
* A rendered encoding must be intelligible as-is and not require additional processing, e.g. a ROT13 cipher.
* You may post more than 3 hidden messages if you wish, but keep in mind this is probably a disadvantage.
* You may only encode one message in the image. No (intentional) decoy messages.
* It's not required per-se that the images hiding your messages look like anything (e.g. cats, dinosaurs, scenic vistas, etc...), but you're no fun if they look like random noise and I will be downvoting any post that uses examples that do.

You will score 1 point if your system remains uncracked after 7 days.

# Answer
> 7 votes
# RRRGGGBBB!!! `Cracked by Unrelated String`

##### Difficulty: Easy

---

## First image: `HELLO,WORLD!`

## Second image: `COPS AND ROBBERS`

## Third image

Title inspired by rrrgggbbb.com

# Answer
> 4 votes
# Low difficulty

**Image 1:**

> `ABCDabcd01::::`

**Image 2:**

> `Fun fact: The practice of designing a cryptographic algorithm which itself uses cryptography to allow the designer of the algorithm to read any message is known as "kleptography"` (not relevant to this, just an interesting field that's a friend-of-a-friend of steganography)

**Image 3:**

Crack this one!

## Hints

**Hint 1:**

> Only one color channel is relevant. Look for odd patterns.

**Hint 2:**

> Try looking at the parity of things. (You'll know what these "things" are when you see them)

**Hint 3:**

> Symmetry matters, but not necessarily the visual symmetry.

# Answer
> 3 votes
# Cracked by Redwolf Programs

Message: HI

Message: BYE

So what is this one?

I'll see what happens....

# Answer
> 3 votes
# Feline Steganography

### Image 1: `feline steganography`

### Image 2: `what could it be?`

### Image 3: ???

# Answer
> 2 votes
# Medium difficulty

**Image 1:**

`hello world`

**Image 2:**

`llama with wheels`

**Image 3:**

# Answer
> 2 votes
# Should be easy

##### Image 1:

> `This was a really astoundingly terrible idea, come to think of it`

##### Image 2:

> `posed look`

##### Image 3:

# Answer
> 2 votes
# The sort you'd expect

**Image 1:**

> `These are colorful for a reason!`

**Image 2:**

> `Stock photos FTW`

**Image 3:**

Crack this one!

**Hint 1:**

> The title is a hint

**Hint 2:**

> This was inspired by emanresu A's cop

# Answer
> 2 votes
# Medium

*Note: I had to update the images due to a problem with the encoder, be sure to redownload them if needed*

**Image 1:**

`explore the universe`

**Image 2:**

`no transparency?`

**Image 3:**

**Hint 1:**

> The first pixel of the image is the only one where the green channel is important.

# Answer
> 0 votes
# Should be easy for real this time

##### Image 1

> `This is a simplified version of my previous cop, and very directly so. I hope you can already guess at the basic principle of it, but I would strongly caution against trying to do this by eye alone.`

##### Image 2

> `In combination with salt, this liquid will give the sea a flavour of the kind of lemonade known as aigresel. It will thus be easy to remove the saline and citric particles from the water and render it drinkable, which will make it unnecessary for ships to be provisioned with barrels of water. This breaking down of sea water by the boreal liquid is a necessary preliminary to the development of new sea creatures, which will provide a host of amphibious servants to pull ships and help in fisheries, replacing the ghastly legions of sea-monsters which will be annihilated by the admixture of boreal fluid and the consequent changes in the the sea’s structure. The sudden death of all of them will rid the Ocean of these vile creatures, images of the intensity of our passions which are represented by the bloodthirsty battles of so many monsters.`
>
> `--Charles Fourier, apparently` (there's only supposed to be one newline)

##### Image 3

Hints even though it's already been a week:

> An image composed entirely of red and white of the same intensity (by some measure) could not encode a message. Replace either with yellow, and it could.

> The message is encoded in UTF-8.

---
Tags: cops-and-robbers, steganography
---


title: Encode integers with some others

text:
# Question
Title: Encode integers with some others
Input a non-empty array of positive (greater than 0) integers. Output another non-empty array of positive integers which *encode* the input array. Output array does not use any numbers used in the input array.

## Rules

* Output array should not contain any numbers used in the input array.
    + Both input and output array may contain duplicate numbers.
* Output array may have same length, may be longer, may be shorter than the original one.
* It should be able to decode the original array from the output array.
    + You only need to decode arrays your encoder output. You are not required to implement a one-to-one mapping.
    + Your decoder may only use any info encoded with numbers in the array and its length. You are not allowed to pass extra info by using other properties of the array (whenever your language support it).
    + Input array is not sorted. And after decode, you should keep the order of input numbers. `[3, 2, 1]`, and `[1, 2, 3]` are two different arrays.
    + You may implement your decoder in a different language.
* Encoding to a single integer is allowed. If your encoder always encode to a single integer, it may output an integer instead of an array.
* The word "array" talked in this post does not include SparseArray (in case your language support it). SparseArray is a special kind of array while there may be gaps between array items.
* You may output integers as strings of their decimal representation, if your output integers are too large, or you just prefer so.
    + Leading zeros in the output strings are allowed. But if there are any, after removing leading zeros or padding more leading zeros, your decoder should still output the original array. Or in the other words, your decoder should not relay on the number of leading zeros to work.
* Your program should at least support any array of 100 numbers, while every number in 1~100.
    + The word "support" here means it should be able to decode the original array without any errors introduced by integer overflow or floating point precision. Your program may however timeout on TIO as long as it will output correct result when given enough resources.
* Your encode algorithm should in theory work for any size array with any large numbers.

Task is **code-golf the encoder program**. The decoder does not contribute to your byte count. But you should also include the decoder program for a reference, so we can verify it. (Please include it in the post directly, not only in TIO link.)

## Testcases

The output array may vary from answer to answer. So we only include input array here. You can verify your answer by checking if `decoder(encoder(input))` may result the original `input`, and `encoder(input)` does not contain any numbers in `input`.

```
[1]
[10]
[1,2]
[2,1]
[1,1]
[11]
[1,11]
[11,1]
[1,2,3,4,5,6,7,8,9,10]
[93,29,47,3,29,84,19,70]

```

# Answer
> 14 votes
# Python, 29 bytes

```
lambda l:[x+max(l)for x in l]

```

Try it online!

Just adds the list maximum to each element, producing values greater than any in the original list. The max of the resulting list is double the original max, so we can invert by lowering each element by half the new max.

```
decoder=lambda r:[x-max(r)//2 for x in r]

```

You can encode with `sum` in place of `max` (with a different decoder), in case `sum` is shorter in your language.

# Answer
> 10 votes
# Jelly, 2 bytes

```
ÆẸ

```

Decoder:

```
ÆE

```

Try it online!

A built-in.

> `ÆE`: Compute the array of exponents of z's prime factorization. Includes zero exponents.
>
> `ÆẸ`: Inverse of `ÆE`.

In other words, `ÆẸ` maps \\$\[a,b,c,d,\dots\]\\$ to \\$2^a 3^b 5^c 7^d \cdots\\$.

This trick is also used in the Gödel numbering.

# Answer
> 6 votes
# Vyxal, 2 bytes

```
G+

```

Try it Online!

Add the maximum of the input list to each number - just like xnor's python answer.

## Decoder

```
G½vε

```

Try it Online!

Get the absolute difference of each item and half of the maximum of the list.

# Answer
> 6 votes
# Haskell, 13 bytes

```
map=<<(+).sum

```

Try it online!

Decoder:

```
\r->[x-div(sum r)(1+length r)|x<-r]

```

The code is pointfree for `f l=[x+sum l|x<-l]`, that is `f l=map(+sum l)l`. It increases each element by the sum of the list. This puts each element above the maximum of the original list. The function `sum` was used rather than `maximum` because `sum` is shorter.

To invert this, note that the resulting list then has sum equal to that of the original list times one plus its length. So, subtracting this recovers the original list.

# Answer
> 5 votes
# Jelly, ~~4~~ 2 bytes

-2 bytes from xnor's answer

```
+Ṁ

```

Try it online!

```
+Ṁ     -- Encoder
+Ṁ     -- Add the Ṁaximum to each value

ṀHạ    -- Decoder
ṀH     -- Halve of the Ṁaximum
  ạ    -- ạbsolute difference between this and each value

```

# Answer
> 5 votes
# Pari/GP, 13 bytes

```
a->2*a*lcm(a)

```

Decoder:

```
a->a/sqrtint(2*lcm(a))

```

Try it online!

Inspired by @xnor's Python answer. `lcm` is shorter than `vecsum` and `vecmax`.

# Answer
> 5 votes
# Retina 0.8.2, ~~10~~ 7 bytes

```

9
,
00

```

Try it online! Link includes test cases. Explanation: Inserts `9`s everywhere, then changes commas into double zeros.

The decoder is ~~12~~ 13 bytes:

```
00
,
9(.?)
$1

```

Try it online! Link includes encoded test cases.

# Answer
> 4 votes
# , 19 bytes

Or **\>=4.1, 12 bytes** by replacing the word `function` with a `\`.

```
function(v)v+max(v)

```

Try it online!

Port of @xnor's answer.

# Answer
> 4 votes
# Ruby, 20 bytes

```
->a{a.map{_1+a.max}}

```

**Try it online**

# Answer
> 2 votes
# Add++, 11 bytes

```
L,bUMVB]G€+

```

Try it online!

Decoder:

```
L,bUM2/VB]dbLGiXz£_€|

```

Try it online!

Basically, a really convoluted way of porting Python - to encode, add the maximum to each item, and to decode, get the absolute value of subtracting half the maximum from each item

# Answer
> 2 votes
# Husk, 4 bytes

```
m+Σ¹

```

Try it online!

Decoder

### Explanation

adds sum to each element

```
m+Σ¹   translates to m+Σ⁰⁰
  Σ⁰   sum of input
m   ⁰  for each element in input
 +     add the sum

Decoder
ṠṀ-§÷o→LΣ

```

alternate 4-byte

```
SM+Σ
S     hook: call   with input and     of input
 M Σ             M                sum
 M+Σ  map + over input with sum as right argument

```

alternate 6-byte with short decoder

```
J0MR¹Σ  [1,2] -> [3, 0, 3, 3]
                 \1/    \ 2 /

Decoder
mLx0

```

# Answer
> 2 votes
# JavaScript (Node.js), 23 bytes

```
a=>a.map(x=>a.join``+x)

```

Try it online!

```
a=>a.map(v=>+v.slice(a.join('').length/(a.length+1)))

```

# Answer
> 1 votes
# C (clang), <sup>~~65~~ ~~57~~</sup> 56 bytes

```
i;s;f(*a,n){for(s=i=0;i<n;)s+=a[i++];for(;n--;)a[n]+=s;}

```

Try it online!

Inputs a pointer to an array of positive integers and its length (becasue pointers in C carry no length info).
Encodes the array in place by adding the sum of all the array elements to each element.

### Decoder

```
i;s;d(*a,n){for(s=i=0;i<n;)s+=a[i++];for(s/=-~n;n--;)a[n]-=s;}

```

Try it online!

Inputs a pointer to an array of positive integers and its length (becasue pointers in C carry no length info).
Decodes the array in place by subtracting from each element the sum of all the elements divided by the length plus one.

# Answer
> 1 votes
# Charcoal, 5 bytes

```
Ｉ⁺⌈θθ

```

Try it online! Another port of @xnor's answer. Explanation:

```
    θ   Input array
   θ    Input array
  ⌈     Maximum
 ⁺      Vectorised sum
Ｉ       Cast to string
        Implicitly print

```

Decoder, 7 bytes:

```
Ｉ⁻θ÷⌈θ²

```

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

```
  θ     Input array
 ⁻      Vectorised subtract
     θ  Input array
    ⌈   Maximum
   ÷    Integer divided by
      ² Literal integer `2`
Ｉ       Cast to string
        Implicitly print

```

# Answer
> 1 votes
# brainfuck, 25 bytes

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

```

Try it online!

If you are working on strings. You can simply encode each character by its ASCII value.

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

```

Try it online!

---
Tags: code-golf, array, integer, open-ended-function
---


# Question
Title: Generalised multi-dimensional chess knight's moves
Multi-dimensional chess is an extension of normal chess that is played on an 8x8x8x8... "board".

In normal 2D chess, a knight's move is a movement by a vector of \\$ \begin{bmatrix} \pm 2 \\ \pm 1 \end{bmatrix} \\$ or \\$ \begin{bmatrix} \pm 1 \\ \pm 2 \end{bmatrix} \\$, as long as it doesn't cause the knight to go outside the \\$ 8 \\$ by \\$ 8 \\$ bounds.

In \\$ N \\$-dimensional chess, a knight's move is a vector of

$$ \begin{bmatrix} \vdots \\ \pm 2 \\ \vdots \\ \pm 1 \\ \vdots \end{bmatrix} \text{or} \begin{bmatrix} \vdots \\ \pm 1 \\ \vdots \\ \pm 2 \\ \vdots \end{bmatrix} $$

where \\$ \begin{bmatrix} \vdots \end{bmatrix} \\$ is any number of \\$ 0 \\$s (such that the vectors are \\$ N \\$ in rank), again as long as it doesn't go outside the \\$ 8^N \\$ bounds.

## Task

Given a coordinate vector of length \\$ N \\$, output all possible coordinate vectors that are a knight's move away on an unobstructed \\$ 8^N \\$ chess board.

You should assume the input vector will always be at least 2-dimensional (i.e., \\$ N \ge 2 \\$), and always within the bounds of the board.

## Test-cases

Using 1-indexed coordinates (0-indexed available here)

```
Input            Output
[1, 8]           [2, 6], [3, 7]
[4, 5]           [5, 7], [3, 7], [3, 3], [5, 3], [6, 6], [2, 6], [2, 4], [6, 4]
[6, 5, 2]        [7, 7, 2], [5, 7, 2], [5, 3, 2], [7, 3, 2], [8, 6, 2], [4, 6, 2], [4, 4, 2], [8, 4, 2], [7, 5, 4], [5, 5, 4], [8, 5, 3], [4, 5, 3], [4, 5, 1], [8, 5, 1], [6, 6, 4], [6, 4, 4], [6, 7, 3], [6, 3, 3], [6, 3, 1], [6, 7, 1]
[5, 1, 3]        [6, 3, 3], [4, 3, 3], [7, 2, 3], [3, 2, 3], [6, 1, 5], [4, 1, 5], [4, 1, 1], [6, 1, 1], [7, 1, 4], [3, 1, 4], [3, 1, 2], [7, 1, 2], [5, 2, 5], [5, 2, 1], [5, 3, 4], [5, 3, 2]
[8, 8, 8]        [7, 6, 8], [6, 7, 8], [7, 8, 6], [6, 8, 7], [8, 7, 6], [8, 6, 7]
[1, 1, 1, 1]     [2, 3, 1, 1], [3, 2, 1, 1], [2, 1, 3, 1], [3, 1, 2, 1], [2, 1, 1, 3], [3, 1, 1, 2], [1, 2, 3, 1], [1, 3, 2, 1], [1, 2, 1, 3], [1, 3, 1, 2], [1, 1, 2, 3], [1, 1, 3, 2]
[7, 3, 8, 2]     [8, 5, 8, 2], [6, 5, 8, 2], [6, 1, 8, 2], [8, 1, 8, 2], [5, 4, 8, 2], [5, 2, 8, 2], [6, 3, 6, 2], [8, 3, 6, 2], [5, 3, 7, 2], [8, 3, 8, 4], [6, 3, 8, 4], [5, 3, 8, 3], [5, 3, 8, 1], [7, 2, 6, 2], [7, 4, 6, 2], [7, 1, 7, 2], [7, 5, 7, 2], [7, 4, 8, 4], [7, 2, 8, 4], [7, 5, 8, 3], [7, 1, 8, 3], [7, 1, 8, 1], [7, 5, 8, 1], [7, 3, 7, 4], [7, 3, 6, 3], [7, 3, 6, 1]
[8, 4, 7, 8, 4]  [7, 6, 7, 8, 4], [7, 2, 7, 8, 4], [6, 5, 7, 8, 4], [6, 3, 7, 8, 4], [7, 4, 5, 8, 4], [6, 4, 8, 8, 4], [6, 4, 6, 8, 4], [7, 4, 7, 6, 4], [6, 4, 7, 7, 4], [7, 4, 7, 8, 6], [7, 4, 7, 8, 2], [6, 4, 7, 8, 5], [6, 4, 7, 8, 3], [8, 3, 5, 8, 4], [8, 5, 5, 8, 4], [8, 6, 8, 8, 4], [8, 2, 8, 8, 4], [8, 2, 6, 8, 4], [8, 6, 6, 8, 4], [8, 3, 7, 6, 4], [8, 5, 7, 6, 4], [8, 2, 7, 7, 4], [8, 6, 7, 7, 4], [8, 5, 7, 8, 6], [8, 3, 7, 8, 6], [8, 3, 7, 8, 2], [8, 5, 7, 8, 2], [8, 6, 7, 8, 5], [8, 2, 7, 8, 5], [8, 2, 7, 8, 3], [8, 6, 7, 8, 3], [8, 4, 6, 6, 4], [8, 4, 8, 6, 4], [8, 4, 5, 7, 4], [8, 4, 8, 8, 6], [8, 4, 6, 8, 6], [8, 4, 6, 8, 2], [8, 4, 8, 8, 2], [8, 4, 5, 8, 5], [8, 4, 5, 8, 3], [8, 4, 7, 7, 6], [8, 4, 7, 7, 2], [8, 4, 7, 6, 5], [8, 4, 7, 6, 3]
[3, 4, 2, 5, 7, 3, 2, 2, 4, 3, 6, 4, 5, 7, 5, 8, 8, 8, 7, 8, 3, 7, 5, 8, 7]  https://gist.github.com/pxeger/8a44daec42d34d9507d7ca6431e2a9fc

```

## Rules

* Your code does not need to practically handle very high \\$ N \\$, but it must work in theory for all \\$ N \\$
* You may use 0-indexed (\\$ \[0, 7\] \\$) or 1-indexed (\\$ \[1, 8\] \\$) input and output, but this must be consistent
* You may optionally take a second input, an integer \\$ N \\$, which is the length of the vector and the number of dimensions
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
> 6 votes
# Ruby, ~~93~~ 81 bytes

```
->a,n{w=*1..8;w.product(*[w]*~-n).select{|r|r.zip(a).sum{|x,y|(x-y).abs*8/3}==7}}

```

Try it online!

### Quickly explained - old version

Generate all possible positions as vectors of N numbers between 1 and 8, then check the differences between each vector and the starting position, the sorted array of absolute values of the components must be `[<bunch of 0s ...>, 1, 2]`

### And then:

(Thanks @dingledooper): If we multiply the differences by 8 and divide them by 3, the vector becomes `[<bunch of 0s>, 2, 5]` and its sum is unequivocally 7, no other combination of numbers can produce the same sum, so we can simplify the check a lot and shave off 12 bytes.

# Answer
> 5 votes
# Jelly, 13 bytes

```
8RṗLạṢ¹ƇØ½ƑʋƇ

```

Try it online!

## Explanation

```
8RṗLạṢ¹ƇØ½ƑʋƇ   Main monadic link
8R              Range from 1 to 8
  ṗ             To the Cartesian power of
   L              the length of the input
            Ƈ   Filter by
           ʋ    (
    ạ             Absolute difference with the input
     Ṣ            Sort
       Ƈ          Filter by
      ¹             identity
        Ø½Ƒ       Equals [1,2]?
           ʋ    )

```

It's a shame that  doesn't automatically convert the left argument to a range, like other list functions…

# Answer
> 5 votes
# JavaScript (V8), 114 bytes

0-indexed. Prints all valid vectors.

```
v=>v.map((x,i)=>v.map((y,j)=>j>i&&(g=n=>n--&&g(n,(V=[...v],x-(V[i]=n&7))**2+(y-(V[j]=n>>3))**2-5||print(V)))(64)))

```

Try it online!

### How?

Let \\$v\\$ be the input vector of length \\$N\\$.

For each pair \\$(i,j),\\:0\le i\<j\<N\\$ and each value \\$n\in\[0\dots 63\]\\$, we compute:

$$X=n \bmod 8\\ Y=\lfloor n/8 \rfloor\\ V=\[v\_0,\\:\dots,v\_{i-1},\\:X,\\:v\_{i+1},\\:\dots,v\_{j-1},\\:Y,\\:v\_{j+1},\\:\dots,\\:v\_{N-1}\]$$

We print the output vector \\$V\\$ if:

$$(v\_i-X)^2+(v\_j-Y)^2=5$$

# Answer
> 4 votes
# 05AB1E, 12 bytes

Takes `N` as first input and the current position as second input.

```
8LIãʒα0K{2LQ

```

Try it online!

```
8L            # push the range [1 .. 8]
  Iã          # all N-tuples of integers in [1 .. 8]
    ʒ         # only keep those for which ...
     α        # ... the element-wise absolute difference to the current position
      0K      # ... without zeros
        {     # ... sorted ascending
         2L   # ... and [1, 2]
           Q  # ... are equal

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 47 bytes

```
Array[#~Norm~1#.#&@*List,0#+8,1-#]~Position~15&

```

Try it online!

Returns a list of coordinates. The product of the taxicab distance and the squared Euclidean distance can only be 15 on knight's moves.

```
Array[           &@*List,0#+8    ]                  for the whole chessboard
                             ,1-#                   offset so the input location is 0:
      #~Norm~1                                          taxicab distance times
              #.#                                       squared Euclidean distance
                                  ~Position~15&     find 15s

```

---

### Wolfram Language (Mathematica), ~~64~~ 55 bytes

```
x/.Solve[0<x<9&&!#-2<x<#+2,x∈#~Sphere~√5,Integers]&

```

Try it online!

Returns a list of coordinates. `x/.` could be omitted (-3 bytes) for a slightly uglier output format (a list of `{x->*coord*}`s).

```
x/.Solve[                 ,             ,Integers]& integer coordinates which are
                           x∈#~Sphere~√5            √5 away from the input,
         0<x<9                                      inside the chess board,
              &&!#-2<x<#+2                          and 2 away on some dimension.

```

# Answer
> 3 votes
# Haskell, ~~132~~ ~~119~~ 118 Bytes

```
e!(o:x)=[z|o==0,z<-[e:x,-e:x]]++map(o:)(e!x)
_!_=[]
k p=filter(all(`elem`[0..7]))$zipWith(+)p<$>([0<$p]>>=(1!)>>=(2!))

```

Try it Online!

-13 bytes thanks to Wheat Wizard

-1 byte thanks to pxeger

# Answer
> 3 votes
# Python, 115 bytes

```
lambda p,N:[i for i in[[*map(int,f"{j:0{N}o}")]for j in range(8**N)]if~-sum((k-l)**(2*N)for k,l in zip(i,p))==4**N]
```

Attempt This Online!

#### Old Python, 116 bytes

```
lambda p,N:[i for i in[[*map(int,f"{j:0{N}o}")]for j in range(8**N)]if 4**N+1==sum((k-l)**(2*N)for k,l in zip(i,p))]
```

Attempt This Online!

Takes the 0-based list and its length as inputs. Uses octal representation as a poor-man's `itertools.product` to generate all squares and then filters out the bad ones using a high-p Minkowski distance.

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~134~~  119 bytes

```
lambda v,d:[i for i in product(*[range(8)]*d)if[1,2]==sorted(abs(x-y)for x,y in zip(i,v)if x-y)]
from itertools import*

```

Try it online!

* Generate all possible coordinates.
* Then, compute he list of the absolute difference between our vector and the coordinate.
* Remove all `0` in this list an verify that the remaining contains exactly `1` and `2`

Thanks to @ovs for -15 bytes

# Answer
> 2 votes
# Pari/GP, 66 bytes

```
a->forvec(b=[[1,8]|i<-a],norml2(a-b)==5&&normlp(a-b)==2&&print(b))

```

Try it online!

For input \\$a\\$, find all coordinate vectors \\$b\\$ on the chessboard such that the \\$l\_2\\$ distance (Euclidean distance) between \\$a\\$ and \\$b\\$ is \\$\sqrt{5}\\$, and the \\$l\_\infty\\$ distance (Chebyshev distance) between \\$a\\$ and \\$b\\$ is \\$2\\$.

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

```
a=>{for(i=a>>2;++i<a*4;)/[09]/.test(i)|[...a].map((n,j)=>s+=((i+'')[j]-n)**2,s=0)^s^5||print(i)}

```

Try it online!

Input is a string, for example, `[6, 5, 2]` is inputed as `"652"`. Output each answer per line to stdout.

---

# Python 2, 104 bytes

```
lambda a:[i for i in range(a/4,a*4)if sum((q in'90')*6+(int(p)-int(q))**2for p,q in zip(`a`,`i*10`))==5]

```

Try it online!

Input `[6, 5, 2]` as an integer `652`. Output list of integers.

# Answer
> 1 votes
# Charcoal, 46 bytes

```
ＦＬθＦＬθＦ⊗¬⁼ικＦ²⊞υＥθ⁺ν⁺×⁼ξι⊗∨λ±¹×⁼ξκ∨μ±¹ＩΦυ⁼ι﹪ι⁸

```

Try it online! Link is to verbose version of code. 0-indexed. Outputs using Charcoal's default array output of each element on its own line with separate results double-spaced from each other. Explanation:

```
ＦＬθ

```

Loop over the possible `N` dimensions for the 2-step part of the knight's move.

```
ＦＬθ

```

Loop over the possible `N` dimensions for the 1-step part of the knight's move.

```
Ｆ⊗¬⁼ικ

```

Loop over 2-step moves toward or away from the origin, but only if different dimensions were chosen.

```
Ｆ²

```

Loop over 1-step moves toward or away from the origin.

```
⊞υＥθ⁺ν⁺×⁼ξι⊗∨λ±¹×⁼ξκ∨μ±¹

```

Calculate the coordinates of the move.

```
ＩΦυ⁼ι﹪ι⁸

```

Output only those coordinates which stay within the bounds of the board.

# Answer
> 1 votes
# Python 3, 230 210 bytes

```
v=lambda n:sum([[m.insert(i,0)or m for m in v(n-1)]for i in range(n)],[])if n>2else[[i,j//i]for i in[-2,-1,1,2]for j in[2,-2]]
k=lambda*l:[p for p in[[*map(sum,zip(l,m))]for m in v(len(l))]if min(p)>0<9>max(p)]

```

Thanks to Jakque for the -20

Try it online!

Python 3 solution that does not use any external modules and calculates the possible moves by recursivly generating all possible moves before filtering out impossible ones.

The original (non-golfed) code that I wrote:

```
def moves(n): # n is the number of dimensions
    out = []
    if n > 2: # If higher then base dimension
        for i in range(n): # For each possible location that the 0 can be
            temp = [move for move in moves(n-1)] # Generate the previous dimension's move list
            for j in range(len(temp)): # Insert 0 in the same location for all moves
                temp[j].insert(i, 0)
            out.extend(temp) # Add to master move list
    else: # Base case, if n = 2
        out = [[1, 2], [1, -2], [-1, 2], [-1, -2],
               [2, 1], [2, -1], [-2, 1], [-2, -1]]

    return out

def knights_moves(*loc):
    n = len(loc) # count dimensions

    # Debug
    print(f"n: {n} n-out: {len(moves(n))}")

    pos_list = []
    for move in moves(n): # Iterate through every move
        pos_list.append([a+b for a, b in zip(loc, move)]) # Add move elementwise with original location

    filtered = [pos for pos in pos_list if min(pos) > 0 and max(pos) < 9] # Check if the move ins

    return filtered

```

Any suggestions/tips or questions are very welcome!

# Answer
> 1 votes
# Haskell, 66 bytes

```
f a=[x|x<-mapM(\_->[1..8])a,sum[n^2*9`div`4|n<-zipWith(-)a x]==11]

```

Try it online!

Essentially a port of G B and dingledooper's Ruby answer.

---
Tags: code-golf, array, combinatorics, chess
---


# Question
Title: Remove consistently dependent smaller integers
Consider this nested array

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

In each subarray in which 1 appears, a 2 appears. You might say that 1's presence is dependent on 2's presence. The converse is not true, as 2 appears in a subarray without 1. Additionally, 3 is dependent on 2, and 4 is dependent on 1 and 2.

## Task

Given a list of lists of positive integers (in whatever I/O form is most convenient for you) remove only the integers which are dependent on integers larger than themselves. In other words, for every integer A that is dependent on an integer B, and B\>A, remove A.

## You may assume:

Positive integers only

Input will not be nested further than one level, as in the example above

No integer will appear more than once in a given subarray

Subarrays will be sorted (increasing or decreasing, whichever is more convenient as long as you state in your answer)

No empty arrays anywhere in input

## Examples:

```
in: [[1,2,4],[1,2,3],[2,3]]
out: [[2,4],[2,3],[2,3]]
in: [[3,4],[5,6]]
out: [[4],[6]]
in: [[1,2,3],[1,2,3,4],[2,3,4]]
out: [[3],[3,4],[3,4]]
in: [[1]]
out: [[1]]
in: [[2,12],[2,13],[2,14]]
out: [[2,12],[2,13],[2,14]]

```

Shortest code wins :)

# Answer
> 3 votes
# Python, <sup>~~104~~</sup> 93 bytes

```
lambda i:[[x for x in a if~-any(x<c>0<all(c in d for d in i if x in d)for c in a)]for a in i]
```

Attempt This Online!

Stupid naïve iterative solution which I'm really not happy with. A recursive solution will be shorter.

-11 bytes thanks to a hint from xnor.

```
for a in z for b in a for c in b for d in c for e in d for f in e for g in f for h in g for i in h for j in i for k in j for l in j for m in l for n in m for o in n for p in o for q in p for r in q for s in r for t in s for u in t for v in u for w in v for x in w for y in x for z in y please kill me why is python's syntax so whitespace and keyword heavy

```

# Answer
> 3 votes
# Charcoal, 21 bytes

```
ＩＥθΦι⬤ι∨¬›νλ⊙θ‹№πν№πλ

```

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

```
  θ                     Input array
 Ｅ                      Map over subarrays
    ι                   Current subarray
   Φ                    Filtered where
      ι                 Current subarray
     ⬤                  All elements satisfy
          ν             Innermost element
        ¬›              Not greater than
           λ            Inner element
       ∨                Logical Or
             θ          Input array
            ⊙           Any subarray satisfies
               №        Count of
                 ν      Innermost element
                π       In innermost subarray
              ‹         Is less than
                  №     Count of
                    λ   Inner element
                   π    In innermost subarray
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 3 votes
# Jelly, 15 bytes

```
ċƇf/>Ƈ⁹ȧ
çⱮFḟ@Ɱ

```

A monadic Link accepting a list of lists of strictly positive integers that yields a list of lists of strictly positive integers.

**Try it online!** (The footer calls the Link for each and formats the output)

### How?

```
ċƇf/>Ƈ⁹ȧ - Helper Link: list of lists, A; integer, I
 Ƈ       - filter keep those lists in A for which:
ċ        -   count occurrences of I - truthy if the list contains I
   /     - reduce this list of lists that contain I by:
  f      -   filter keep
             - gets us a list of those values appearing in all of them
      ⁹  - use I as the right argument of:
     Ƈ   -   filter keep those for which:
    >    -     greater than I?
       ȧ - logical AND I (non-vectorising)
             - i.e. I if it is a consistently dependent smaller integer, else 0

çⱮFḟ@Ɱ - Link: list of lists, A
  F    - flatten A
 Ɱ     - map across each integer I in that with:
ç      -   call the Helper Link as a dyad - f(A, I)
     Ɱ - map across each list in A with:
    @  -   with swapped arguments:
   ḟ   -     filter discard

```

# Answer
> 3 votes
# , ~~167~~ ~~163~~ ~~159~~ ~~157~~ 147 bytes

Or **\>= 4.1, 126 bytes** by replacing three `function` occurrences with `\`s.

*Edit: -2 bytes thanks to @Giuseppe and -10 bytes thanks to @Dominic van Essen.*

```
function(x,b=combn(c(0,sort(unique(unlist(x)))),2))lapply(x,setdiff,b[1,apply(b,2,function(y,`+`=function(k)sapply(x,match,x=y[k],0))all(!+1|+2))])

```

Try it online!

That turned out long...

Straightforward approach:

1. Create all pairs of values from input list (leading zeros to fix issues with 1-length inputs). `unique` and `sort` take care of the "first element is smaller" requirement.
2. Define a helper function `+` to look for a value in nested list.
3. Which pairs are dependent? (Uses \\$\lnot p \lor q\\$ for implication.) Extract first elements from them.
4. `setdiff` those from all sublists.

# Answer
> 2 votes
# Haskell, ~~80~~ 70 bytes

```
f l=filter(\n->all(\m->m<=n||any((&&).elem n<*>all(/=m))l)$l>>=id)<$>l

```

Try it Online!

-10 bytes thanks to Wheat Wizard

# Answer
> 2 votes
# 05AB1E, ~~14~~ 12 bytes

```
εʒδåÏ.«Ãy›O_

```

Try it online or verify all test cases.

**Explanation:**

```
ε            # Map over each inner list of the (implicit) input list of lists:
 ʒ           #  Filter this inner list by:
  δ          #   Map over each list of the (implicit) input list of lists:
   å         #    Check if it contains the current integer
    Ï        #   Only keep those lists from the (implicit) input list of lists
     .«      #   Reduce the remaining list of lists by:
       Ã     #    Keep the values which are present in both lists
        y›   #   Then check which remaining values are larger than the current integer
          O  #   Sum to get the amount of values for which this is truthy
           _ #   Check if this sum is 0
             # (after which the modified list of lists is output implicitly as result)

```

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

```
#/.Table[#⋂##&@@#~Select~MemberQ@ii||i->Set@$,{i,Max@#}]&

```

Try it online!

The private-use character is `\[VectorLessEqual]`.

```
   Table[                                     ,{i,Max@#}]   for positive i up to the max
#/.                                   i->Set@$              remove i if
         #⋂##&@@                                              intersection of
                #~Select~MemberQ@i                              lists containing i
                                  i||                        not all <=i

```

# Answer
> 1 votes
# JavaScript (ES6), 79 bytes

Expects an array of sets.

```
a=>a.map(([...b])=>b.filter(p=>!b.some(q=>q>p&a.every(b=>b.has(q)|!b.has(p)))))

```

Try it online!

# Answer
> 1 votes
# Ruby, 85 bytes

```
->l{l.map{|a|a-l.flatten.select{|x|l.select{|c|c&[x]!=[]}.reduce(&:&).any?{|y|y>x}}}}

```

Try it online!

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