title: Reversed Multiple Pair

text:
# Question
Title: Reversed Multiple Pair
# Intro

Two numbers are a *reversed multiple pair* if they satisfy the following property:

$$ a\cdot b = \operatorname{reversed}( (a-1)\cdot b ) $$

Here, \\$\operatorname{reversed}()\\$ means to reverse the digits of a number (e. g `123` becomes `321`.)

# Example

$$ a=6,\quad b=9,\quad 6\cdot 9=54,\quad 5\cdot 9=45 $$

As you can see, \\$45\\$ is the reversed version of \\$54\\$.

# Task

Given two integers, \\$a\\$ and \\$b\\$, output if these two numbers is a reversed multiple pair.

# Test Cases

```
6 9 => True
4 5 => False
3 2178 => True
34 2079 => True
7 8 => False
600 100 => False
46 1089 => True
817 503 => False
6 9009 => True
321 81 => False
10 1089 => False

```

Shortest code wins!

# Answer
# tinylisp, 76 bytes

```
(load library
(d f(q((a b)(e(to-base 10(*(- a 1)b))(reverse(to-base 10(* a b

```

Try it online!
> 9 votes

# Answer
# Brachylog, 8 bytes

```
-₁ʰ×↔~×?

```

Try it online!

### Explanation

```
           Input = [A, B]
-₁ʰ        Compute [A-1, B]
   ×       Compute (A-1) × B
    ↔      Reverse digits
     ~×?   It can be unmultiplied into [A,B]

```
> 8 votes

# Answer
# Python 3, 37 bytes

```
lambda a,b:str(a*b)==str(~-a*b)[::-1]

```

Try it online!
> 6 votes

# Answer
# Jelly, 6 bytes

```
’×ṚḌ⁼×

```

A dyadic Link accepting \\$a\\$ and \\$b\\$ that yields `1` if \\$a\times b = \text{reversed}( (a - 1)\times b )\\$, `0` if not.

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

### How?

```
’×ṚḌ⁼× - Link: a, b
’      - a-1
 ×     - (a-1) times b
  Ṛ    - reverse the digits of (a-1)×b
   Ḍ   - convert back to an integer
     × - a×b
    ⁼  - equal?

```
> 6 votes

# Answer
# APL (Dyalog Unicode), 9 bytes

Anonymous tacit infix function, taking \\$a\\$ as left argument and \\$b\\$ as right argument.

```
×≡∘⌽⍥⍕×-⊢

```

Try it online! (Uses Extended because TIO hasn't updated to 18.0)

`×` \[Does\] the product

`≡∘` match the…

`⌽⍥` reversed, when both are…

stringified

`×` product

`-` minus

the right argument\[?\]
> 6 votes

# Answer
# Jelly, 9 bytes

```
,’$×DU⁼¥/

```

Try It Online!

```
,’$×DU⁼¥/    Main Link; dyad accepting a, b
,’$          pair: [a, a - 1]
   ×         multiply: [ab, (a - 1)b]
    D        to digit list
        /    reduce between the two:
     U       is the reverse of the former
      ⁼      equal to the latter?

```
> 5 votes

# Answer
# Factor, ~~47~~ 39 bytes

```
[ over * dup present reverse dec> - = ]

```

Try it online!

Saved 8 bytes thanks to @ovs' observations.

## Explanation

Takes input as `b a`.

```
         ! 9 6
over     ! 9 6 9
*        ! 9 54
dup      ! 9 54 54
present  ! 9 54 "54"
reverse  ! 9 54 "45"
dec>     ! 9 54 45
-        ! 9 9
=        ! t

```
> 4 votes

# Answer
# Python 2, 31 bytes

```
lambda a,b:`a*b`==`a*b-b`[::-1]

```

Using the logic that $$ ab = \operatorname{rev}( (a-1)b ) \iff ab = \operatorname{rev}(ab-b) $$ -2 thx to @dingledooper

Try it online!

## Other solutions:

### Python 2, 31 bytes

```
lambda a,b:`a*b`[::-1]==`a*b-b`

```

Using the logic that $$ \operatorname{rev}(ab) = (a-1)b \iff \operatorname{rev}(ab) = ab-b $$ -2 thx to @dingledooper

Try it online!

### Python 2, 34 bytes

```
lambda a,b:a*b-int(`a*b`[::-1])==b

```

Using the logic that $$ ab - \operatorname{rev}(ab) =b $$

Try it online!

^Credits to @ovs for the equations!
> 4 votes

# Answer
# Vyxal, 7 bytes

```
:‹"*÷Ṙ=

```

Try it Online!

```
  "     # Pair the first input with
:‹      # Itself decremented
   *    # Multiply both by the second input
    ÷   # Push both to the stack
     Ṙ= # Is one reversed equal to the other?

```
> 3 votes

# Answer
# Charcoal, 13 bytes

```
ＮθＮη⁼×θη⮌×⊖θη

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a reversed pair, nothing if not. Explanation:

```
Ｎθ              First input as a number
  Ｎη            Second input as a number
      θ         First input
     ×          Multiplied by
       η        Second input
    ⁼           Equals
           θ    First input
          ⊖     Decremented
         ×      Multiplied by
            η   Second input
        ⮌       Reversed
                Implicitly print

```
> 3 votes

# Answer
# Pari/GP, 40 bytes

```
f(a,b)=d=digits;d(a*b)==Vecrev(d(a--*b))

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 41 bytes

Expects `(a)(b)`. Returns a Boolean value.

```
a=>b=>[...a*b+''].reverse().join``==a*b-b

```

Try it online!
> 3 votes

# Answer
# C (gcc), 55 bytes

```
c;r;f(a,b){for(r=0,c=~-a*b;c;c/=10)r+=9*r+c%10;r-=a*b;}

```

Try it online!

Inputs two integers \\$a\\$ and \\$b\\$.
Returns a falsy value if these two numbers are a reversed multiple pair or a truthy value otherwise.
> 3 votes

# Answer
# Burlesque, 14 bytes

```
Jpdjp^-..*<-==

```

Try it online!

Takes input as array of pairs {a b}

```
J   # Duplicate
pd  # Product of array
j   # Swap
p^  # Push elements to stack (b, a)
-.  # Decrement
.*  # Product
<-  # Reverse digits
==  # Equal

```
> 3 votes

# Answer
# Ruby, 33 bytes

```
->a,b{"#{a*=b}"==(a-b).digits*''}

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~43~~ 33 bytes

```
a?b=a*b==read(reverse$show$a*b-b)

```

Try it online!

* I haven't thought `reverse` was available in prelude, no reason to use foldl(flip(:))""String
> 3 votes

# Answer
# Retina 0.8.2, 55 bytes

```
\d+
$*
1,
,
1(?=.*,(1+))
$1
,
,$`
1+
$.&
+`(.),\1
,
^,$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
1,
,

```

Decrement `a`.

```
1(?=.*,(1+))
$1

```

Multiply `a-1` by `b`.

```
,
,$`

```

Add that to `b` giving `(a-1)b,ab`.

```
1+
$.&

```

Convert to decimal.

```
+`(.),\1
,
^,$

```

Test whether the results are mirror images of each other.
> 2 votes

# Answer
# Red, ~~47~~ 45 bytes

```
func[a b][(to""a * b)= reverse to""a - 1 * b]

```

Try it online!
> 2 votes

# Answer
# APL+WIN, ~~22~~ 20 bytes

Prompts for a then b. Minus 2 bytes using rearrangement logic

```
(⍎⌽⍕n-b)=n←(b←⎕)×a←⎕

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# BQN, ~~33~~ 22 Bytes

~~This seems too long.~~

A little better.

```
{(×)=•BQN⌽•Fmt×-1}

```

Try it!

*¯11 bytes thanks to @Razetime*
> 2 votes

# Answer
# Retina, 41 bytes

```
L$`.+,
*$'*_,$($^$.(*$'*))*_$'*
^(_+),\1$

```

Try it online! Link includes test cases. Explanation: Based on @ovs' 05AB1E answer.

```
L$`.+,

```

Match `a` as `$&` (Retina ignores the trailing comma when performing arithmetic) and `b` as `$'` and replace the whole input with the result.

```
*$'*_,$($^$.(*$'*))*_$'*

```

Calculate `a*b` and also `rev(a*b)+b` in unary.

```
^(_+),\1$

```

See whether they are the same.
> 2 votes

# Answer
# GeoGebra, ~~86~~ ~~77~~ 70 bytes

```
a=6
b=9
s=Text(ab-b)
o=Sum(Zip(Take(s,c,c),c,Length(s)…1))==Text(ab)

```

Try It On GeoGebra!

Input is `a` and `b`, output is `o` as `true` if `a` and `b` are a reversed multiple pair, `false` otherwise.

The example input shown in the code is `a=6` and `b=9`, but you can change these values to whatever you want.
> 2 votes

# Answer
# , ~~20~~ 14 bytes

```
*=|.&.":@(*<:)

```

-6 bytes, thanks @Jonah

Try it online!
> 2 votes

# Answer
# PHP, 79 bytes

```
$a=trim(fgets(STDIN));$b=trim(fgets(STDIN));echo $a*$b==(int)strrev($b*($a-1));

```

Try it online!

With the help of Github Copilot
> 1 votes

# Answer
# MathGolf, 7 bytes

```
`(*x¬*=

```

Try it online.

**Explanation:**

```
`        # Duplicate the top two items, using the implicit inputs
         #  STACK: b,a,b,a
 (       # Decrease the top item
         #  STACK: b,a,b,a-1
  *      # Multiply the top two together
         #  STACK: b,a,b*(a-1)
   x     # Reverse the top integer
         #  STACK: b,a,reverse(b*(a-1))
    ¬    # Reverse rotate the stack:
         #  STACK: reverse(b*a(-1)),b,a
     *   # Multiply the top two again
         #  STACK: reverse(b*a(-1)),b*a
      =  # Check if the two are equal
         #  STACK: reverse(b*a(-1))==b*a
         # (after which the entire stack joined together is output implicitly)

```
> 1 votes

# Answer
# T-SQL, 31 bytes

Using bitwise operators

```
PRINT-1/~(@*@b^reverse(@b*~-@))

```

**Try it online**
> 1 votes

# Answer
# Julia 1.0, 56 bytes

```
(a,b,d=digits,s=string)->s(d(a*b))==s(reverse(d(a*b-b)))

```

Try it online!

Pretty straightforward answer, with nothing particularly clever to it (unfortunately).
> 1 votes

# Answer
# Ly, 15 bytes

```
nn&s*SrJlf,*=u;

```

Try it online!

```
nn               - read two numbers from STDIN
  &s             - save the entries to the backup cell
    *            - multiple the two numbers passed in
     S           - convert integer to individual digits on stack
      r          - reverse stack
       J         - re-compose digits on stack into a integer
        l        - restore saved numbers
         f       - flip top two entries
          ,      - decrement the top of stack
           *     - multiple top two entries
            =    - compare the two entries on the stack
             u   - print "1|0" from comparison
              ;  - exit the program

```
> 1 votes

---
Tags: code-golf, math, number, decision-problem
---


title: AoCG2021 Leftover: HexaGoL

text:
# Question
Title: AoCG2021 Leftover: HexaGoL
This challenge is one of the two challenges which were planned for Advent of Code Golf 2021, but didn't fit into the 25-day schedule.

Related to AoC2020 Day 24, Part 2.

---

Given a binary configuration on a hexagonal grid, output the next generation of Hexagonal Game of Life using AoC rules:

* A living cell survives if it has one or two living neighbors. Otherwise, it turns into a dead cell.
* A dead cell becomes alive if it has exactly two living neighbors. Otherwise, it does not change.

A hexagonal grid can be input and output in any sensible 2D or 3D representation. The input grid has a shape of a regular hexagon. You can choose how to handle the borders: either expand it by one layer, or keep the input size. You can choose the values of alive and dead cells, but they must be consistent across input and output.

You may choose the two distinct values for the alive and dead cells in the input and output, and you may use the value for "dead" or the third value for the necessary padding.

Standard rules apply. The shortest code in bytes wins.

## Example I/O

An input representing the following grid

```
  . . .
 * . . *
* . * * *
 * * * .
  * . .

```

could be skewed to the right, giving

```
    . . .
  * . . *
* . * * *
* * * .
* . .

```

or, as a Python 2D array using 0 and 1 (with zero padding),

```
[[0, 0, 0, 0, 0],
 [0, 1, 0, 0, 1],
 [1, 0, 1, 1, 1],
 [1, 1, 1, 0, 0],
 [1, 0, 0, 0, 0]]

```

The expected output for this input, if expanding by one layer, is

```
   . . . .
  . . . . .
 * * * . * *
. * . . . * .
 * . . . . .
  * * . . .
   . . . .

```

or, in the same representation,

```
[[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 1, 1],
 [0, 1, 0, 0, 0, 1, 0],
 [1, 0, 0, 0, 0, 0, 0],
 [1, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]

```

As written above, you're free to choose to not expand the borders, in which case the result would be

```
  . . .
 * * . *
* . . . *
 . . . .
  * . .
[[0, 0, 0, 0, 0],
 [0, 1, 1, 0, 1],
 [1, 0, 0, 0, 1],
 [0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0]]

```

Example code is here.

# Answer
# Wolfram Language (Mathematica), 73 bytes

```
CellularAutomaton[{56,{2,{{0,2,2},{2,1,2},{2,2,0}}},{1,1}},#~ArrayPad~1]&

```

Try it online!

Takes a 2D array (skewed to the right) as input.

---

# Wolfram Language (Mathematica) \+ my LifeFind package, 71 bytes

```
<<Life`
CellularAutomaton[{RuleNumber@"B2/S12H",2,{1,1}},#~ArrayPad~1]&

```

Sorry, no TIO for this one.

Takes a 2D array (skewed to the left) as input.

There is a convenient `CA` function in this package, but it automatically removes the surrounding zeroes.

The main purpose of this package is to find interesting patterns in cellular automata. Here are something I found:

```
A period 2 oscillator:

 . *       * .
* . .  => . . *
 . *       * .

A period 3 oscillator:

 . * .      * . *      . * .
* . . * => . . . . => * * * *
 . * .      * . *      . * .

Another period 3 oscillator:

  * . *        . * .        * . *
 . . . .      * . . *      . * * .
* . . . * => . . . . . => * * . * *
 . . . .      * . . *      . * * .
  * . *        . * .        * . *

A period 4 oscillator:

    * . *            . * .            * . *            * . *
   . . . .          * . . *          . * * .          . * * .
  * . . . *        . . . . .        * . . . *        . * * * .
 . . . . . .      * . . . . *      . . . . . .      . * . . * .
* . . . . . * => . . . . . . . => * * . . . * * => * * * . * * *
 . . . . . .      * . . . . *      . * . . * .      . * * * * .
  * . * . *        . * . * .        * . . . *        * . . . *

A period 4 spaceship:

 . * . * . . . . .      . . . * . . . . .      . . * . * . . . .      . . * . * . . . .
. . . * * * . . .      . . * . . * . . .      . . . * * * * . .      . . . . . . * . .
 . . . * * . . . .      . . . . . * . . .      . . * . * * . . .      . . . . . . * . .
. . * . . . . . .      . * * . . . . . .      . * * * . . . . .      * . . * . . . . .
 . * . * . . . . .      . * . * . . . . .      * * . . * . . . .      . . . . * . . . .
. . * * * * . . .      . . . . . * . . .      . * . . * * * . .      . . . . . . * . .
 . * * * * . . . .      * . . . . * . . .      * * . . * * . . .      . . . * . . * . .
. * * . . . . * .      . * . . . . * * .      . * . . . . . . *      . . . . * . . * *
 . . . * . . * . .      * . . . * * * * .      * . * . * . . * .      * . . . * * * * *
. * * . . * . . .      . * * * * . * . .      . . . . * . * . .      . . . * * . . * .
 . * . . . . . . .      * * * . . . . . .      . . . . . . . . .      . . . . . . . . .
. . . . . . . . .  =>  . * * . . . . . .  =>  . . . . . . . . .  =>  . . . . . . . . .
 . * . . . . . . .      * * * . . . . . .      . . . . . . . . .      . . . . . . . . .
. * * . . * . . .      . * * * * . * . .      . . . . * . * . .      . . . * * . . * .
 . . . * . . * . .      * . . . * * * * .      * . * . * . . * .      * . . . * * * * *
. * * . . . . * .      . * . . . . * * .      . * . . . . . . *      . . . . * . . * *
 . * * * * . . . .      * . . . . * . . .      * * . . * * . . .      . . . * . . * . .
. . * * * * . . .      . . . . . * . . .      . * . . * * * . .      . . . . . . * . .
 . * . * . . . . .      . * . * . . . . .      * * . . * . . . .      . . . . * . . . .
. . * . . . . . .      . * * . . . . . .      . * * * . . . . .      * . . * . . . . .
 . . . * * . . . .      . . . . . * . . .      . . * . * * . . .      . . . . . . * . .
. . . * * * . . .      . . * . . * . . .      . . . * * * * . .      . . . . . . * . .
 . * . * . . . . .      . . . * . . . . .      . . * . * . . . .      . . * . * . . . .

```
> 5 votes

# Answer
# JavaScript, 86 bytes

```
a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i&&~~a[(i/3|0)+y-1]?.[i%3+x-1]+g(i-1))(7)&~c)==2))

```

Try it online! (TIO link use `||{}` instead of `?.` which is not supported on older NodeJS.)

Input boolean matrix with holes as padding. Output in same format.
> 4 votes

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

```
({+/1↓¯1↓,⍵}⌺3 3∊¨2+0,¨⊢)(⌽0,⍉)⍣4

```

Try it on APLgolf!

A partially tacit function that takes a 2D grid of booleans (0s and 1s) skewed to the right, and returns the next step with one cell expanded.

GoL body is mostly from the APLcart entry, modified to make sure the region to be considered is hexagonal, the rules (2/12 instead of 3/23) are encoded correctly, and the entire grid is padded before running the GoL calculation. Padding is easier than not padding here, because otherwise we need to make sure the cells outside the valid hexagonal region are zero.

The hexagonal region trick is what I came up with when AoC2020 day 24 was ongoing. The orientation of the entire grid is part of the trick; this works by looking at a 3x3 square sub-grid and removing the top left and bottom right cells from consideration. This is easier than the other orientation because it suffices to flatten the array and drop the first and the last element in this case, instead of manual reshape or indexing.

```
. o o
o O o  =>  . o o o O o o o .
o o .

```
> 4 votes

# Answer
# Charcoal, 50 bytes

```
⊞υωＷＳ⊞υιＥΦυκ⭆ι⎇⁼λ λ§.*›²↔⁻⁴⁻⊗№⭆³✂⁺  §υ⁺κνμ⁺⁵μ¹*⁼λ*

```

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

```
⊞υω

```

Push a dummy entry to the predefined empty list to prevent wrapping between the top and bottom.

```
ＷＳ⊞υι

```

Input the grid.

```
ＥΦυκ⭆ι

```

Map over the grid, excluding the dummy entry.

```
⎇⁼λ λ

```

Leave spaces as-is.

```
§.*›²↔⁻⁴

```

Output `.` or `*` depending on the number of live neighbours. There are three cases which result in a `*`; live with one live neighbour, dead with two live neighbours, and live with two live neighbours. When you add the liveness of the cell to double the number of neighbours, these three cases are the only cases to map to `3`, `4` and `5`, therefore the absolute difference from `4` must be less than `2` to output a `*`.

```
⁻⊗№⭆³✂⁺  §υ⁺κνμ⁺⁵μ¹*⁼λ*

```

Count the neighbours by extracting a `3×5` rectangle from the grid centred on the current cell. (Two spaces are prefixed to the grid to avoid negative slice offsets.) Since this already includes the liveness of the current cell, it needs to be subtracted from the double count to produce the value in the range `3-5` from above.
> 1 votes

---
Tags: code-golf, hexagonal-grid, cellular-automata, game-of-life
---


title: Ragged index of

text:
# Question
Title: Ragged index of
Your input is a ragged list of positive integers and a positive integer. Your task is to find that positive integer and return it's index, or if the positive integer doesn't exist, indicate it's nonexistence.

How are indices in ragged lists defined? They are simply lists of indices that when used consecutively to index the ragged list, return the desired element. For example, if the ragged list is `[1,[2,3],[[4,5]],[]]` then the index of `2` is `[1,0]` and the index of `5` is `[2,0,1]`.

If there are multiple integers, return the index of the first one. That is, the one whose index is the smallest when compared lexicographically.

# Rules

You can choose between 0 and 1 based indexing and also the order of the returned index.

You must indicate the non-existance of a solution in some easily identified manner. Here are some examples:

## Ok

* Return a value that is not a list. For example, -1 or None
* Return an empty list
* Error in some way
* Exit the program

## Not ok

* Infinite loop/recursion (if you want to use a resource exhaustion error, be sure to read this)
* Undefined behavior
* A list of integers, even if those integers are out of bounds or negative.

An exception to the last point. You may use a single consistent value that can never be the output to indicate nonexistence. For example, a program that returns `[-1]` whenever there is no solution is allowed, but a program that returns `[-1]` or `[-2]` when there isn't a solution is not allowed.

Finally, you can also return a list of all solutions in sorted order. If you use this IO format, you must return an empty list if there are no solutions.

# Test cases

```
[], 1 -> None
[[[40]]], 40 -> [0,0,0]
[[1,[]],[[3]],3,[3]], 3 -> [1,0,0]
[5], 5 -> [0]
[[],[[],[]]], 5 -> None

```

# Answer
# Wolfram Language (Mathematica), 8 bytes

```
Position

```

Try it online!

Built-in that returns all indices, 1-indexed. A very interesting answer, I'm sure.

---

To return the first such index:

### Wolfram Language (Mathematica), 13 bytes

```
FirstPosition

```

Try it online!

Another built-in. Returns `Missing["NotFound"]` if `n` is not present. Almost as interesting as the above.
> 6 votes

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

Returns an empty list if the value is not present. 1-based indexing.

```
∊(∊↑⍸⍤=)∘(↑⍣≡)

```

Try it on APLgolf!

`↑⍣≡` Mix right argument until homogeneous (array). This converts the nested list to a rectangular array by inserting 0's.
`⍸⍤=` All indices where the left argument is equal to the resulting array.
`∊↑` Take 1 index if the left argument is present, 0 otherwise.
Flatten resulting list. This might not be necessary, but returning results with different levels of nesting seems wrong.

If returning an out-of-bounds index for the error case would be allowed, something like `⊃⍸⍤=∘(↑⍣≡)` could work.
> 4 votes

# Answer
# Whython, ~~63~~ ~~62~~ 59 bytes

*-3 bytes thanks to att*

```
f=lambda l,n,i=0:[i]+f(l[i],n)?[l[i]]*0+f(l,n,i+1)?l-n or[]

```

Returns the 0-based ragged index if found; raises an exception if not found. Attempt This Online! Or, verify all test cases.

### Explanation

We define a recursive function `f` that takes three arguments:

* `l` is the object we're searching--usually a list, but could also be an integer at the bottom of the recursion
* `n` is the number we're searching for
* `i` is the current index in `l` that we're testing

We want to error if the number is not found; using Whython's `?` operator, we can catch any errors from deeper recursive calls and try the next case. As soon as we find the right number, we return a result instead of erroring. Or, once we run out of options, the error propagates back to the caller.

The function body has three cases, connected by `?`:

```
[i]+f(l[i],n)

```

If `l` is a list and `i` is a valid index into that list, try recursing over `l[i]`. If that succeeds, it returns a list representing a ragged index, to which we prepend `i` and return. If the recursive call fails, or if `l` is not a list, or if `len(l) <= i` and therefore `i` is not a valid index into `l`, error and try the next branch:

```
[l[i]]*0+f(l,n,i+1)

```

If `l` is a list and `i` is a valid index into that list, try recursing over the same `l` with `i+1`. If that succeeds, it returns a list representing a ragged index, to which we add an empty list and return. If the recursive call fails, or if `l` is not a list, or if `i` is not a valid index into `l`, error and try the next branch:

```
l-n or[]

```

If `l` is an integer and is equal to `n`, we've found the number we're looking for; the difference is 0, so we return `[]`. If `l` is not an integer, `l-n` errors; if `l` is an integer not equal to `n`, returning some nonzero integer causes an error when we return from the recursive call and try to add the result to a list.
> 2 votes

# Answer
# Jelly, 2 bytes

```
œi

```

Try it online!

Just the builtin. 1-indexed and outputs an empty list if not found.

Marginally less built in:

# Jelly, 4 bytes

```
=ŒṪṂ

```

Try it online!

1-indexed and outputs 0 if not found.
> 2 votes

# Answer
# Brachylog, 16 bytes

```
dbĖ|ċʰiʰgᵗz↰ʰkᵗc

```

Try it online!

Input as a list `[list, item]`. Output 0-indexed, innermost index first, declarative failure if not found. There's definitely a byte or two left to shave off with all this list juggling, but it's already 5 down from how it started, so I'm giving it a rest for now.

# Brachylog, 16 bytes

```
h~t?bk|bB&hċi,B↰

```

Try it online!

This feels somehow worse.
> 2 votes

# Answer
# Pari/GP, 72 bytes

```
f(l,a)=if(l==a,[],#l'&&s=[concat(i,r)|i<-[1..#l],e!=r=f(l[i],a)],s[1],e)

```

Try it online!

1-indexed. Returns `e` if not found.

---

# Pari/GP, 64 bytes

```
f(l,a)=if(l==a,,#l'&&s=[r*x+i|i<-[1..#l],e!=r=f(l[i],a)],s[1],e)

```

Try it online!

Returns a polynomial whose coefficient list is the index, e.g., `[[1, []], [[3]], 3, [3]], 3 -> x^2 + x + 2`. I'm not sure if this is allowed.

1-indexed. Returns `e` if not found.
> 2 votes

# Answer
# Javascript, 54 bytes

```
t=>g=a=>r=a.some?.((n,i)=>s=g(n)&&[i,...r])?s:a==t&&[]

```

Input the target and the array. Output an array or `false` if not found.

```
f=

t=>g=a=>r=a.some?.((n,i)=>s=g(n)&&[i,...r])?s:a==t&&[]

console.log(f(1)([]))
console.log(f(40)([[[40]]]))
console.log(f(3)([[1,[]],[[3]],3,[3]]))
console.log(f(5)([5]))
console.log(f(5)([[],[[],[]]]))
```

# JavaScript 62 bytes

```
a=>t=>JSON.parse(a,(x,y)=>y.some?.(x=>z=x)?x?x+[,z]:z:y==t&&x)

```

```
f=

a=>t=>JSON.parse(a,(x,y)=>y.some?.(x=>z=x)?x?x+[,z]:z:y==t&&x)

console.log(f("[]")(1))
console.log(f("[[[40]]]")(40))
console.log(f("[[1,[]],[[3]],3,[3]]")(3))
console.log(f("[5]")(5))
console.log(f("[[],[[],[]]]")(5))
```

Input the array as JSON, and target value currying. Output a comma separated string or `false` if not found. It could be 58 bytes if a leading comma is acceptable.
> 2 votes

# Answer
# Python 2, 75 bytes

```
f=lambda n,l,h=[],t=0:f(n,l[0],h+[t])or f(n,l[1:],h,t+1)if[]<l else(l==n)*h

```

Try it online!
> 2 votes

# Answer
# Python, 72 bytes (@att)

```
f=lambda L,n,*p:sum((f(l,n,*p,i:=i+1)for l in-1*L+L or[]),[p]*(i:=L==n))
```

Attempt This Online!

### Old Python, 75 bytes

```
f=lambda L,n,*p:[p]*(i:=L==n)+sum([f(l,n,*p,i:=i+1)for l in-1*L+L or[]],[])
```

Attempt This Online!

1-based, outputs all matches.
> 2 votes

# Answer
# Ruby, ~~63~~ 59 bytes

```
f=->l,x{l*0==0?x==l:(x=l.index{|e|l=f[e,x]})&&[x,*l]-[1>0]}

```

Try it online!

f=-\>l,x{...}
Lambda taking *l* list, *x* element and return index or *nil*.

l\*0==0?x==l:
if *l* is a value, return if it's the value, else:

(x=l.index{|e|l=f\[e,x\]})&&
*x* becomes index of{..} which may be nil, in that case return nil(falsely).
Block calls recursively *f* on each element returning *true* or an array of indexes( which are both truthy ), or false otherwise.

~~\[x,\*l==1\>0?\[\]:l\]~~ \[x,\*l\]-\[1\>0\] else return that index and append *l*(next indexes) removing `true`.
> 2 votes

# Answer
# Python3, 99 bytes:

```
f=lambda l,t,c=[]:next((m for i,a in enumerate([l,[]][l*0==0])if(m:=f(a,t,c+[i]))),0)if l!=t else c

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6),  ~~62~~  60 bytes

*Saved 2 bytes thanks to @l4m2*

Expects `(value)(array)`. Returns *false* if not found.

```
n=>g=(a,...o)=>a.map?a.some((v,i)=>g(v,...o,i))&&r:a-n?0:r=o

```

Try it online!
> 1 votes

# Answer
# Julia 1.0, ~~95~~ ~~78~~ ~~77~~ ~~75~~ ~~73~~ 72 bytes

```
l::Int\n=l==n&&[]
l\n=for(i,v)=pairs(l);0∈(p=[i;v\n])||return p;end==0

```

Try it online!

Returns `false` for not found, 1-based indices for found.

`l::Int\n = l==n && []` \- base case, when first argument is an Integer: if it's equal to the second argument, return empty Array `[]`; if it's not, return `false` (== 0).

`0 ∈ (p=[i;v\n]) || return p` \- 1-based index `i` can never be 0, so if `[i; v\n]` contains a 0, that means the recursive call failed, move on. If `v\n` isn't 0, we found the number, so prepend the current index and return that back to the caller.

`==0` at the end - This check happens at the end of the loop and always returns `false` (thanks to @MarcMush for -1 byte by using this). If `for` loop completed without returning, we didn't find the number anywhere. So return `false` to indicate failure.
> 1 votes

# Answer
# 05AB1E (legacy), 15 bytes

```
ΔQƶʒZĀ}нZˆĀ*}¯¨

```

1-based. Results in `[[]]` if the ragged list doesn't contain the integer.

Try it online. (Or here a scuffed attempt to create a test suite..)

Uses the legacy version of 05AB1E, because there apparently is a bug with `Ā` (Python-style truthify) incorrectly resulting in `1` for (some) empty strings..

**Explanation:**

```
Δ           # Loop until the result no longer changes:
 Q          #  Check for each value in the ragged list if it's equal the to
            #  second (implicit) input-integer
            #  (will use the implicit first input-list in the first iteration)
  ƶ         #  Multiply each inner value by its 1-based index
   ʒ  }н    #  Find the first inner list which is truthy for:
    Z       #   Push the flattened maximum ("" if it lacks integers)
     Ā      #   Check if this is truthy (thus not 0 nor "")
        Z   #  Push the flattened maximum of the found list (without popping)
         ˆ  #  Pop and add it the global array
        Ā   #  Truthify the integers in the ragged list
         *  #  Multiply it by the second (implicit) input-integer
}¯          # After the loop: push the global array
  ¨         # Remove the last value, since the `Δ`-loop will have looped an
            # additional time before it stops; otherwise we could have printed
            # the flattened maximum directly instead of using the global array
            # (after which this list is output implicitly)

```
> 1 votes

# Answer
# Perl 5, 83 bytes

```
sub{($_,$n,@_)=@_;/\[/?push@_,0:/]/?pop:/,/?$_[-1]++:/^$n$/?return\@_:0for/\d+|./g}

```

Try it online!
> 1 votes

# Answer
# Charcoal, 38 bytes

```
⊞υ⟦⟦⟧θ⟧ＦυＦＥ⁺⟦⟧§ι¹⟦⁺§ι⁰⟦λ⟧κ⟧⊞υκＩ⌊Φυ⁼⊟ιη

```

Try it online! Link is to verbose version of code. Outputs `None` if the desired element is not present in the ragged array. Explanation:

```
⊞υ⟦⟦⟧θ⟧Ｆυ

```

Start a breadth-first enumeration of all the elements and their ragged indices with the input list and an empty index.

```
ＦＥ⁺⟦⟧§ι¹⟦⁺§ι⁰⟦λ⟧κ⟧⊞υκ

```

If this element is a non-empty list then push all of its elements and their ragged indices to the search list.

```
Ｉ⌊Φυ⁼⊟ιη

```

Output the lexicographically earliest (if any) index of the desired element.
> 0 votes

---
Tags: code-golf, ragged-list
---


title: Pretty print my arrays

text:
# Question
Title: Pretty print my arrays
I like to pretty print multidimensional arrays, like this:

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

```

But it's a pain to do by hand and it'd be nice to have a program that does this for me. Your challenge is to create a program that does this for me, taking a multidimensional array containing only positive integers and prettyprinting it.

Specifically, an array of depth 1 is printed joined by `,`  with `[` prepended and `]` appended:

```
[1, 2, 3]

```

An array of depth \\$n+1\\$, which contains at least one array of depth \\$n\\$, has its subarrays prettyprinted, joined by newlines and indented by two spaces. All but the last subarray have a comma appended, the last has  `]` appended, and the first has its first line indented with `[`  instead of two spaces:

Here's a reference implementation:

```
function recursivePrettyPrint(array){
  if(array.every(x => typeof x == "number")){
    return `[${array.join(', ')}]`;
  } else {
    return array.map((item, index) => {
      let result = recursivePrettyPrint(item) + ',';
      result = result.split`\n`;
      if(index == 0){
        result[0] = '[ ' + result[0];
      } else {
        result[0] = '  ' + result[0];
      }
      for(let i = 1; i < result.length; i++){
        result[i] = '  ' + result[i]
      }
      return result.join('\n');
    }).join('\n').slice(0,-1) + ' ]';
  }
}

function change(){
  let array = JSON.parse(document.getElementById('input').value);
  let output = document.getElementById('output');
  output.innerText = recursivePrettyPrint(array);
}
```

```
<textarea id=input></textarea>

<button id=run onclick=change()>Pretty Print</button>

<pre id=output></pre>
```

Numbers may be multiple digits. The input will always be orthogonal/rectangular, and you may take its dimensions as well. Trailing spaces on lines are allowed.

## Testcases

```
[[892, 759], [962, 251]] ->
[ [892, 759],
  [962, 251] ]

[118, 922, 619] ->
[118, 922, 619]

[[966, 639, 616, 255], [622, 483, 87, 241], [453, 870, 728, 725], [163, 936, 48, 967], [261, 833, 87, 200]] ->
[ [966, 639, 616, 255],
  [622, 483, 87, 241],
  [453, 870, 728, 725],
  [163, 936, 48, 967],
  [261, 833, 87, 200] ]

[[[[[912, 547], [366, 754]], [[723, 536], [779, 238]]], [[[559, 392], [602, 709]], [[692, 915], [412, 302]]]], [[[[3, 504], [936, 83]], [[352, 442], [425, 375]]], [[[380, 440], [793, 762]], [[850, 321], [780, 457]]]]] ->
[ [ [ [ [912, 547],
        [366, 754] ],
      [ [723, 536],
        [779, 238] ] ],
    [ [ [559, 392],
        [602, 709] ],
      [ [692, 915],
        [412, 302] ] ] ],
  [ [ [ [3, 504],
        [936, 83] ],
      [ [352, 442],
        [425, 375] ] ],
    [ [ [380, 440],
        [793, 762] ],
      [ [850, 321],
        [780, 457] ] ] ] ]

[[[128, 910, 664, 658], [172, 238, 564, 492], [325, 384, 566, 90]], [[876, 819, 764, 105], [583, 528, 731, 839], [480, 126, 692, 875]], [[215, 84, 268, 504], [400, 674, 997, 526], [799, 692, 193, 296]], [[943, 185, 567, 188], [118, 200, 879, 409], [116, 493, 62, 343]]] ->
[ [ [128, 910, 664, 658],
    [172, 238, 564, 492],
    [325, 384, 566, 90] ],
  [ [876, 819, 764, 105],
    [583, 528, 731, 839],
    [480, 126, 692, 875] ],
  [ [215, 84, 268, 504],
    [400, 674, 997, 526],
    [799, 692, 193, 296] ],
  [ [943, 185, 567, 188],
    [118, 200, 879, 409],
    [116, 493, 62, 343] ] ]

```

# Answer
> 10 votes
# Python 2, ~~74~~ ~~73~~ 72 bytes

-1 thanks to loopy walt

-1 thanks to dingledooper

```
f=lambda l,s=',\n  ':l<[f]and`l`or'[ %s ]'%s.join(f(r,s+'  ')for r in l)

```

Try it online!

# Answer
> 5 votes
# JavaScript (SpiderMonkey), 69 bytes

```
(g=j=>a=>+(u=uneval(a))[1]?u:`[ ${a.map(g(j+'  ')).join(j)} ]`)`,
  `

```

Try it online!

This answer assume the array only contains positive integers.

# Answer
> 4 votes
# 05AB1E, ~~38~~ 37 bytes

```
dΔ€`}\„, ý'[ì']«N©F„
,®N-·úRý„[ ì„ ]«

```

Try it online or verify all test cases.

**Explanation:**

```
dΔ€`}\...N         # Determine the depth of the input:
d                  #  Transform each inner-most integer to a 1 (with >=0 check)
 Δ                 #  Loop until the result no longer changes:
  €`               #   Flatten it one level down
    }\             #  After the loop: discard the resulting list of 1s
„, ý               # Join each inner-most list of the (implicit) input with
                   # ", "-delimiter
    '[ì           '# Prepend a "[" in front of each string
    ']«           '# Append a "]" after each string
         N         # Push the reached index of the earlier loop, which is the
                   # depth of the input-list - 1
 ©                 # Store this depth-1 in variable `®` (without popping)
  F                # Loop `N` in the range [0,®):
   „\n,            #  Push string "\n,"
       ®N-         #  Subtract `N` from `®`
          ·        #  Double it
           ú       #  Pad the string with that meany leading spaces
            R      #  Reverse it
             ý     #  Join each inner-most list of strings with this as delimiter
              „[ ì #  Prepend a "[ " in front of each string
              „ ]« #  Append a "]" after each string
                   # (after which the result is output implicitly)

```

`dΔ€`}\...N` to determine the depth is taken from this answer of mine.

# Answer
> 3 votes
# Pari/GP, 96 bytes

```
f(a,i=",\n  ")=print1(if(#a[1]',l=!print1("[ ");[(l--&&print1(i))+f(b,Str(i"  "))|b<-a];" ]",a))

```

Try it online!

A port of @att's Python answer.

# Answer
> 3 votes
# Retina 0.8.2, 76 bytes

```
,|\[\B
$&
\B]
 ]
+%1`((.*?\[)((\[)|(?<-4>])|[^][])+(?(4)^),) \[
$1¶$.2$*  [

```

Try it online! Link includes test cases. Assumes input contains no spaces (seems awkward to ask for spaces given that this is a formatting challenge). Explanation:

```
,|\[\B
$&
\B]
 ]

```

Insert the necessary spaces.

```
+%1`

```

Repeatedly replace the first occurrence on each line until no more replacements can be made:

```
((.*?\[)((\[)|(?<-4>])|[^][])+(?(4)^),) \[

```

Match as little indentation (up to and including the parent `[`) as possible, as many subarrays as possible, then the start of a subarray.

```
$1¶$.2$*  [

```

Wrap that last subarray to a new line, giving it the indentation it needs converted to spaces (it would have contained `[`s).

60 bytes by using @DLosc's observation that the amount of indent can be calculated from the remaining square brackets:

```
,|\[\B
$&
\B]
 ]
], (?=((\[)|(?<-2>])|(){2}]|.)+)
],¶$#3$*

```

Try it online! Link includes test cases. Explanation: The first two stages add the necessary spaces as above.

```
], (?=((\[)|(?<-2>])|(){2}]|.)+)

```

Match a closing square bracket with a comma, count the number of `[`s in `$#2`, ignore that many `]`s, then count two (spaces of indent) for each extra `]`.

```
],¶$#3$*

```

Break the line after the comma and replace the space with the desired amount of indent.

# Answer
> 3 votes
# Charcoal, ~~75~~ 60 bytes

```
≔⭆¹ＳθＦ[]≔⪫Ｅ⪪θι∨κ ιθ≔⪪✂θ¹±¹¦¹], θ⪫Ｅθ⁺×  ⁻№⪫…θκω[⁺κ№⪫…θκω]ι],¶

```

Try it online! Link is to verbose version of code. Explanation: Uses @Dlosc's observation that the indent can be calculated from the difference in numbers of `[`s and `]`s.

```
≔⭆¹Ｓθ

```

Input the array and perform Python stringification on it, which joins the elements with `,`  but wraps them in `[` and `]` without spaces.

```
Ｆ[]≔⪫Ｅ⪪θι∨κ ιθ

```

Insert spaces between pairs of `[` or `]`. Unfortunately this also adds a leading and a trailing space.

```
≔⪪✂θ¹±¹¦¹], θ

```

Trim away that leading and trailing space, then split on `],` .

```
Ｅθ⁺×  ⁻№⪫…θκω[⁺κ№⪫…θκω]ι],¶

```

Map over the pieces of strings, calculating the indent from the number of `[`s in all the previous strings minus the number of `]`s in all the previous strings (adjusted because they've been split on `],`), then output the strings each on their own line with the `],` restored (but not on the last line).

# Answer
> 3 votes
# Pip `-x`, ~~37~~ 35 bytes

```
"[]"J:0*@a?(fMaJ:",
")WRsRn"
  "aJk

```

Recursive full program; takes the array as a nested list in Pip format from the command-line. Attempt This Online!

### Explanation

Using  in place of newlines for better readability:

```
"[]"J:0*@a?(fMaJ:",¶")WRsRn"¶  "aJk
         a                           ; Current list
        @                            ; First element
      0*                             ; Times 0
          ?                          ; Is truthy?
                                     ; If so, first element is a list:
            f                        ;  Apply the main function recursively
             M                       ;  to each element of
              a                      ;  the current list
               J:                    ;  Join the results on
                 ",¶"                ;  comma + newline
           (         )WR             ;  Wrap that string in
                        s            ;  space
                         R           ;  Replace
                          n          ;  each newline with
                           "¶  "     ;  newline plus two spaces
                                     ; Else, first element is a number:
                                a    ;  Current list
                                 J   ;  joined on
                                  k  ;  comma + space
"[]"                                 ; Open bracket + close bracket
    J:                               ; joined on the above result

```

# Answer
> 3 votes
# Retina 0.8.2, 66 bytes

```
,|\[\B
$&
\B]
 ]
], (?=(.+))
],¶$1_
T`d ,``.+_
+`\[]

+`]_
_
_

```

Try it online!

### Explanation

The first four lines, which add spaces where necessary, are taken from Neil's Retina answer.

Now, observe that:

* We need to add a newline and an indent after every occurrence of `],`
* The indentation level is equal to the nesting level at that point in the list, which can be calculated by looking at the number of brackets in the remaining part of the list: nesting level = (# of remaining close brackets) - (# of remaining open brackets)

So:

```
], (?=(.+))

```

Match `],`  and capture the rest of the line in group 1; then:

```
],¶$1_

```

Replace that with `],` followed by a newline, the contents of group 1, and an underscore for a separator.

```
T`d ,``.+_

```

Transliteration stage: Replace digits, space, and comma with nothing (i.e. delete them) when they appear in any match of `.+_` (i.e. before `_` on a line).

```
+`\[]

```

Repeatedly delete empty matched brackets (which can only occur in the before-`_` context) until none are left.

```
+`]_
_

```

Repeatedly replace close-bracket followed by underscore with underscore followed by two spaces. This has the effect of translating each level of nesting (represented by the unmatched close-brackets) into two spaces of indentation.

```
_

```

Delete the underscores.

# Answer
> 2 votes
# Python3, 230 bytes:

```
E=enumerate
def f(x,d=[]):
 m=len(d)-(min(i+1 for i,a in E(d)if not any(d[i+1:]))if any(d)else 0)
 return ' '*((len(d)-m)*2)+'[ '*m+str(x)if all(int==type(i)for i in x)else'\n'.join(f(a,d+[i])+','*(i<len(x)-1)for i,a in E(x))+' ]'

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, 60 bytes

```
>(l,s=",\n  ")=try.~l;"$l"catch;"[ $(join(l.>s*"  ",s)) ]"end

```

Try it online! (with a literal `\n`)

port of att's great answer

`.~l` tries to apply `~` to each element of `l`, which only works if `l` is not nested (shorter than `l[1] isa Int`)

---
Tags: code-golf, string, ascii-art, array
---


title: Interpret the Shue Language

text:
# Question
Title: Interpret the Shue Language
## Overview

Shue (Simplified Thue) is a language that was designed by AnttiP for this challenge. A Shue program consists of the possible outputs and a list of string replacements. For example, the following program prints "yes" if an unary string is even:

```
yes
no
11=2
12=1
22=2
1=no
2=yes

```

Try it online!

The possible outputs here are listed as "yes" and "no". Then comes the list of replacements. Here, "11" is replaced with "2", "22" with "2", "12" with "1", "1" with "no", and "2" with "yes". All replacements are done non-deterministically. Once the program reaches a state where one of the replacements is the output, it terminates and prints the output.

## Exact definition of Shue

###### Copied from the original post

The source code is interpreted as a list of bytes. The only characters with special meaning are the newline, the equals sign and the backslash. `\n` corresponds to a literal newline, `\=` to a literal equals sign and `\\` to a literal backslash. Any other use of `\` is an error. Every line must contain 0 or 1 unescaped equals signs.

Or in other words, to be syntactically valid, the program has to match the following regex: `/([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?(\n([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?)*/`

Here is the mathematical definition of a Shue program:

A Shue program is a set of terminator strings \\$T\_e\\$, and a set of transformation rules \\$T\_r\\$, which are pairs of strings.

The execution of a Shue program on a input string \\$i\\$ is defined as follows. Let \\$U\\$ be the minimal set, so that \\$i\in U\\$ and \\$\forall a,x,y,b: axb \in U \land (x,y) \in T\_r \rightarrow ayb \in U\\$. Let \\$S=U\cap T\_e\\$.

If \\$S=\\{x\\}\\$, then the program will terminate, and \\$x\\$ will be printed to stdout.

If \\$S=\emptyset\\$ and \\$|U|=\aleph\_0\\$, then the program will enter an infinite loop.

In all other cases, the behavior is undefined (yes, Shue isn't memory safe).

However, since most esolangs cannot process byte arrays, you may take a string or a list of lines as input. See the linked original challenge for a better definition and more examples.

## Reference Implementation

Here is the Python reference implementation:

```
import re, sys
re1 = re.compile(rb"(([^=]|\\=)*)(=([^=]|\\=)*)?")

def unescape(i):
    ret = b""
    esc = 0
    for c in i:
        if esc and c == b"\\":
            ret+= b"\\"
            esc = 0
        elif esc and c == b"=":
            ret+= b"="
            esc = 0
        elif esc and c == b"n":
            ret+= b"\n"
            esc = 0
        elif esc:
            raise ValueError(f"Parser error: got character {c} after \\")
        elif c == b"\\":
            esc = 1
        else:
            ret+= bytes([c])
    if esc:
        raise ValueError(f"Parser error: got EOL/EOF after \\")
    return ret

def parse(i):
    terminators = set()
    rules = set()
    lines = i.split(b"\n")
    for l in lines:
        m = re1.match(l)
        if m.group(3):
            rules|= {(unescape(m.group(1)), unescape(m.group(3)[1:]))}
        else:
            terminators|= {unescape(m.group(1))}
    return terminators, rules

def execute(c, i):
    terms, rules = parse(c)
    universe = {i}
    mod = True
    while mod:
        mod = False
        new_universe = set()
        for s in universe:
            if s in terms:return s
        for s in universe:
            for a,b in rules:
                for o in range(len(s)+1):
                    if s[o:o+len(a)] == a:
                        new_universe|= {s[:o]+b+s[o+len(a):]}
                        mod = True
        universe = new_universe
    raise ValueError(f"Program error: no replacements are possible (undefined behaviour)")

code = input().encode()
inp = sys.stdin.read().encode()

res = execute(code, inp)
print(res.decode())

```

## Rules

* Standard loopholes are forbidden
* You may take input either as a byte list, a single string, or a list of lines.
* As this is , shortest program in bytes wins.

# Answer
# Python3, 264 bytes:

```
lambda x,y:next(M(x,p(y)))
def M(s,g):
 if s in g[0]:yield s
 for a,b in g[1]:
  for i in range(len(s)):
   if a==s[i:i+len(a)]:yield from M(s[:i]+b+s[i+len(a):],g)
def p(s):
 d={}
 for i in s.split('\n'):d[c]=d.get((c:='='in i),[])+[[i,i.split('=')][c]]
 return d

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js), 198 bytes

```
c=>g=(a,...b)=>c.every(s=>([_,p,q,r]=s.match(/^((?:\\?.)*?)(=(.*))?$/).map(t=>t&&eval(`"${t.split`"`.join`\\"`}"`)),q?[...a].map((_,i)=>b.push(a.slice(0,i)+a.slice(i).replace(p,r))):a!=p))?g(...b):a

```

Try it online!

Fixed and optimized tsh's (deleted) answer
> 1 votes

---
Tags: code-golf
---


title: Is it a sub-permutation?

text:
# Question
Title: Is it a sub-permutation?
A finite-permutation is a function which takes an \\$n\\$-tuple and produces an \\$n\\$-tuple such that every element of the input is present in the output, and the ordering does not rely on the values of the inputs.

We can unambiguously represent these permutations with an \\$n\\$-tuple where each element is the index of where it will end up. For example:

$$ (3 \\,\\, 2 \\,\\, 1 \\,\\, 0) $$

This permutation reverses a \\$4\\$ element tuple. The first element goes to the 3rd (last) position, the second goes to the 2nd (penultimate) position etc.

With this representation a valid permutation is just any list of size \\$n\\$ which contains the numbers \\$0\\$ through \\$n-1\\$.

Now if we want let's apply a permutation, \\$(5 \\,\\, 2 \\,\\, 1 \\,\\, 4 \\,\\, 3 \\,\\, 0)\\$, but first lets color 3 elements red.

$$ (A,\color{red}{B},C,\color{red}{D},\color{red}{E},F) \\ \underset{\\,(5 \\,\\, 2 \\,\\, 1 \\,\\, 4 \\,\\, 3 \\,\\, 0)\\,}{\xrightarrow{}}\\ (F,C,\color{red}{B},\color{red}{E},\color{red}{D},A) $$

Now if we just look at how the permutation effects the order of highlighted elements we get:

$$ (\color{red}{B},\color{red}{D},\color{red}{E}) \\ \longrightarrow{}\\ (\color{red}{B},\color{red}{E},\color{red}{D}) $$

Which is the permutation \\$(0\\,\\,2\\,\\,1)\\$.

One permutation is a *sub*-permutation of another if it is the permutation acting on some subset of the elements of the tuple. So

$$ (0\\,\\,2\\,\\,1)\subseteq(5 \\,\\, 2 \\,\\, 1 \\,\\, 4 \\,\\, 3 \\,\\, 0) $$

by the example shown above. Every permutation is a sub-permutaton of itself.

## Task

Given two permutations \\$A\\$ and \\$B\\$ determine if \\$A\\$ is a sub-permutation of \\$B\\$. You should output one of two distinct values. One if \\$A\\$ is a sub-permutation of \\$B\\$ and the other if a does not.

This is so the goal is to minimize your source code as scored in bytes.

You may take permutations in any reasonable format, this includes formats that use 1 indexing instead of 0 indexing.

## Test cases

```
[] [0,1,2] -> True
[0] [0,1,2] -> True
[0,1] [0,1,2] -> True
[0,1,2] [0,1,2] -> True
[1,0] [0,1,2] -> False
[0,1,2,3] [0,1,2] -> False
[] [2,1,0] -> True
[0] [2,1,0] -> True
[0,1] [2,1,0] -> False
[1,0] [2,1,0] -> True
[0,2,1] [2,1,0] -> False
[0,2,1] [3,2,1,0] -> False
[0,2,1] [5,2,1,4,3,0] -> True
[0,1,2] [5,2,1,4,3,0] -> False
[2,1,0] [5,2,1,4,3,0] -> True
[1,2,0] [5,2,1,4,3,0] -> True

```

# Answer
> 4 votes
# APL(Dyalog Unicode), 25 bytes SBCS

```
{⍺≡∊(⊂⍺)∩⍋⍤,¨⊃,/(⊢,,¨)\⍵}

```

Try it on APLgolf!

`⊃,/(⊢,,¨)\⍵` generates all non-empty subsequences and is taken from this tip.
`⍋⍤,¨` converts each subsequence to a sub-permutation by getting the indices that would sort the sequence.
`(⊂⍺)∩` intersects that list of sub-permutations with the left input.
`⍺≡∊` checks if the flattened result of that matches the left argument.

Without dealing with the empty list the last two steps could be `(⊂⍺)∊`, adding the empty list to the sub-permutations would be longer: `(⊂⍬),`.

# Answer
> 4 votes
# Vyxal, 5 bytes

```
ṗv⇧$c

```

Try it Online!

Port of Jonathan Allan's Jelly answer.

```
ṗ     # Powerset
 v⇧   # Grade up each
   $c # Is the input contained in that?

```

# Answer
> 3 votes
# JavaScript (ES6),  ~~74~~  70 bytes

Expects `(A)(B)` in 1-indexing format. Returns \\$0\\$ or \\$1\\$.

```
A=>F=([v,...B],C=[0])=>v?F(B,C)|F(B,[...C,v]):A.every(i=>~~v<(v=C[i]))

```

Try it online!

### Commented

```
A =>                 // A[] = candidate sub-permutation
F = (                // F is a recursive function taking:
  [v,                //   v = next value from the main permutation
      ...B],         //   B[] = remaining values in the main permutation
  C = [0]            //   C[] = subset of B[], with a leading 0 to take
                     //         1-indexing into account
) =>                 //
v ?                  // if v is defined:
  F(B, C) |          //   try a recursive call where C[] is left unchanged
  F(B, [...C, v])    //   try a recursive call where v is added to C[]
:                    // else:
  A.every(i =>       //   for each entry i in A[]:
    ~~v < (v = C[i]) //     make sure that v is less than C[i]
                     //     (v is initially undefined and coerced to 0)
                     //     and update v to C[i]
  )                  //   end of every()

```

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
æεD{kQ}à

```

Inputs are in the order \\$B,A\\$.

Try it online or verify all test cases.

**Explanation:**

```
æ       # Get the powerset of the first (implicit) input-list B
 ε      # Map over each list:
  D     #  Duplicate the current list
   {    #  Sort the copy
    k   #  Get the index of each value in the list
     Q  #  Check if this is equal to the second (implicit) input-list B
 }à     # After the map: pop and push the maximum to check if any was truthy
        # (which is output implicitly as result)

```

Try it online with step-by-step debug lines.

# Answer
> 3 votes
# Factor, 47 bytes

```
[ all-subseqs { } suffix [ arg-sort ] map in? ]

```

Try it online!

Is the first input in the inverse permutations of the subsequences of the second input?

# Answer
> 2 votes
# Jelly, 6 bytes

Or only 5 bytes for a count of the ways - `ŒPỤ€ċ`

```
ŒPỤ€e@

```

A dyadic Link accepting the permutation on the left and the potential sub-permutation on the right (both 1-indexed).

**Try it online!**

### How?

```
ŒPỤ€e@ - Link: permutation, P; potential sub-permutation, S
ŒP     - powerset (i.e. all sub-sequences) of P
   €   - for each:
  Ụ    -   grade up (1-based indices sorted by their respective values)
     @ - with swapped arguments - f(S, that):
    e  -   S exists in that?

```

# Answer
> 1 votes
# Python3, 117 bytes:

```
f=lambda x,y,p=0,q=0:not x or(y and(k:=(x[0]-p>=0)==(y[0]-q>=0))and any([f(x[k:],y[k:],x[0],y[0])*k,f(x,y[1:],p,q)]))

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 38 bytes

```
MemberQ[(o=Ordering)/@Subsets@#2,o@#]&

```

Try it online!

Expects f\[A,B\].

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


title: Resize the image

text:
# Question
Title: Resize the image
Given an \\$n\times m\\$ matrix \\$A\\$ and two integers \\$w,h\\$, output a matrix of \\$w\times h\\$ called \\$B\\$, such that $$B\_{i,j} = \int\_{i-1}^i\mathbb dx\int\_{j-1}^j A\_{\left\lceil \frac xw\cdot n\right\rceil,\left\lceil \frac yh\cdot m\right\rceil}\mathbb dy\text{ (1-index),}$$ $$B\_{i,j} = \int\_i^{i+1}\mathbb dx\int\_j^{j+1} A\_{\left\lfloor \frac xw\cdot n\right\rfloor,\left\lfloor \frac yh\cdot m\right\rfloor}\mathbb dy\text{ (0-index),}$$ or "split a square into \\$n\times m\\$ smaller rectangles, fill each with the value given in \\$A\\$, then resplit into \\$w\times h\\$ one and get average of each small rectangle" (which is a simple image rescaling algorithm and that's why this title is used)

Shortest code in each language wins. You can assume reasonable input range, which may give good to few languages though.

Test cases:

$$ \begin{matrix}1&1&1\\ 1&0&1\\ 1&1&1\end{matrix}, (2,2) \rightarrow \begin{matrix}\frac 89&\frac 89\\ \frac 89&\frac 89\end{matrix}$$ $$ \begin{matrix}1&1&1\\ 1&0&1\\ 1&1&0\end{matrix}, (2,2) \rightarrow \begin{matrix}\frac 89&\frac 89\\ \frac 89&\frac 49\end{matrix}$$ $$ \begin{matrix}1&0\\0&1\end{matrix}, (3,3) \rightarrow \begin{matrix}1&\frac 12&0\\ \frac 12&\frac 12&\frac 12\\ 0&\frac 12&1\end{matrix}$$ $$ \begin{matrix}1&0\\0&1\end{matrix}, (3,2) \rightarrow \begin{matrix}1&\frac 12&0\\ 0&\frac 12&1\end{matrix}$$

Sample solution just by definition

# Answer
> 1 votes
# Jelly,  ~~20~~  14 bytes

<sup>~~I can't help but think that more of the manipulation could be put inside the reduction `ƒ`~~ \- done</sup>

```
xs€⁴Z¹ƭL¤ZÆmðƒ

```

A full-program accepting `[w, h]` and `A` that prints a representation of `B`.

**Try it online!**
Or see the test-suite (this uses the register `®` in place of the 2nd program argument,  to make a reusable Link, and formats each result as a grid).

### How?

We repeat row elements `w` times, split these into chunks of length `n` transpose the result, and take the means, then we do the same to the result, but with `h` and `m` instead of `w` and `n`.

```
xs€⁴Z¹ƭL¤ZÆmðƒ - Main Link: [w,h]; A
            ðƒ - reduce [A,w,h] by:
x              -   repeat (row elements) ([[1,2]]x3->[[1,1,1,2,2,2]])
        ¤      -   nilad followed by links as a nilad:
   ⁴           -     2nd program argument, A
      ƭ        -     call in turn:
    Z          -     ...1st time: transpose
     ¹         -     ...2nd time: do nothing
       L       -     length -> 1st=n; 2nd=m
 s€            -   split each (row) into chunks of length (n or m)
         Z     -   transpose
          Æm   -   arithmetic mean (vectorises)
               - implicit print

```

# Answer
> 0 votes
# Charcoal, 28 bytes

```
ＦＥ²Ｎ≔ＥιＥζ∕ΣＥμ§μ÷⁺×κＬμπιＬμζＩζ

```

Try it online! Link is to verbose version of code. Takes input in the order `w`, `h`, `A`. Explanation:

```
ＦＥ²Ｎ

```

Repeat twice, once for the width, once for the height.

```
≔ＥεＥζ∕ΣＥμ§μ÷⁺×κＬμπεＬμζ

```

Rescale and transpose the array.

```
»Ｉζ

```

Output the final array.

---
Tags: code-golf, matrix, image-processing
---


title: Draw a Signal strength indicator

text:
# Question
Title: Draw a Signal strength indicator
Given the signal level `L` in the range `0-4`. Your program should draw the following ASCII art.

When `L=0`:

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

```

When `L=1`:

```
               ....
               ....
          .... ....
          .... ....
     .... .... ....
     .... .... ....
oooo .... .... ....
oooo .... .... ....
oooo .... .... ....

```

When `L=2`:

```
               ....
               ....
          .... ....
          .... ....
     oooo .... ....
     oooo .... ....
oooo oooo .... ....
oooo oooo .... ....
oooo oooo .... ....

```

And etc. You can change the characters `o` and `.` to others, it's up to you. Trailing spaces are allowed.

This is a code-golf challenge so the shortest solution wins.

# Answer
# , 47 46 bytes

```
' .o'{~[:|.@|:[:,/(4,&0@#"+3+2*i.4)#"+1+4{.$&1

```

Try it online!
> 4 votes

# Answer
# Vyxal, 17 bytes

```
4ɾ≥vS4ɾd›*¶+4*⁋↵§

```

Try it Online!

-3 thanks to Seggan.

```
4ɾ≥               # Create a map of ones and zeroes corresponding to the bar characters.
   vS             # Stringify those
     4ɾd›         # Create the range [3, 5, 7, 9]
         *        # And repeat each char of those
          ¶+      # Append a newline to each
            4*    # Repeat each four times
              ⁋↵  # Turn into a list of lines
                § # Rotate 90°

```
> 2 votes

# Answer
# Python 3, 76 bytes

```
f=lambda L,i=0:i<36and". o"[i%4+i/8<3or-(i%4<L)]*4+" \n"[i%4>2]+f(L,i+1)or""

```

Try it online!

-2 bytes by dingledooper

---

# Python 3, 91 bytes

```
f=lambda L:L<45and" ".join(4*" o."[j+j+L//5>5and~(j<L%5)]for j in[0,1,2,3])+"\n"+f(L+5)or""

```

Try it online!
> 2 votes

# Answer
# APL+WIN, 48 bytes

Prompts for n

```
⊖⍉⊃((n↑m)⍴¨⊂⊂4⍴'0'),((-4-n←⎕)↑m←1+2×⍳4)⍴¨⊂⊂4⍴','

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Python, 75 bytes

```
def f(n,j=4):print(*(" .o"[(i>=j)*~(n<i)]*4for i in b""));1/j;f(n,j-.5)
```

Attempt This Online!

Finishes with an exception. The `b""` string contains the literal bytes `0x01` `0x02` `0x03` `0x04`, but they're invisible here.

Could probably be improved with some more tweaking.

## 76 bytes

```
def f(n,j=4):print(*(" .o"[(i>=j)*~(n<i)]*4for i in b""));j>0!=f(n,j-.5)
```

Attempt This Online!

No error.
> 2 votes

# Answer
# Charcoal, 17 bytes

```
↑Ｅ⁴Ｅ⁴×§.o›Ｉθι⁺³⊗ι

```

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

```
  ⁴                 Literal integer `4`
 Ｅ                  Map over implicit range
    ⁴               Literal integer `4`
   Ｅ                Map over implicit range
       .o           Literal string `.o`
      §             Indexed by
           θ        Input `L`
          Ｉ         Cast to integer
         ›          Is greater than
            ι       Outer value
     ×              Repeated by
              ³     Literal integer `3`
             ⁺      Plus
                ι   Outer value
               ⊗    Doubled
↑                   Print rotated 90° anticlockwise

```

Charcoal prints each array element in its own row (or column, if rotated as it is here) and automatically double-spaces nested arrays when printing them.

14 bytes by using the custom characters `1` and `0` instead of `o` and `.`:

```
↑Ｅ⁴Ｅ⁴⭆⁺³⊗ι›Ｉθι

```

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

```
  ⁴             Literal integer `4`
 Ｅ              Map over implicit range
    ⁴           Literal integer `4`
   Ｅ            Map over implicit range
        ³       Literal integer `3`
       ⁺        Plus
          ι     Outer value
         ⊗      Doubled
     ⭆          Map over implicit range and join
            θ   Input `L`
           Ｉ    Cast to integer
          ›     Is greater than
             ι  Outer value
↑               Print rotated 90° anticlockwise

```
> 2 votes

# Answer
# JavaScript (Node.js), 73 bytes

```
L=>(g=i=>i--?` .
 o`[i%20?i%5&&i/20+2*(x=i/5&3)<9|x+L&4:3]+g(i):'')(180)

```

Try it online!

-1 byte by Arnauld

---

# JavaScript (Node.js), 90 bytes

```
L=>(g=i=>i>8?'':[1,2,3,4].map(j=>' o.'[j+j+i<8?0:j>L?2:1].repeat(4)).join` `+`
`+g(++i))``

```

Try it online!
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~104~~ ~~100~~ 93 bytes

```
lambda n:[f'{"oooo "*(b:=n-4+(k:=min(i,7)//2+1))+".... "*(k-max(0,b)):>20}'for i in range(9)]

```

Try it online!

Returns a list of strings, allowed here.

Thanks everyone for all the tips on my previous python answer. I used some of those tips here!
> 1 votes

# Answer
## Javascript, 99 bytes

```
x=>"0004003402341234"[r="replace"](/\d{4}/g,"$&\n$&\n")[r](/\d/g,y=>+y?x<y?".... ":"oooo ":"     ")

```

(Didn't it use to be `$0` for this and not `$&`?)
> 1 votes

# Answer
# 05AB1E (legacy), 18 bytes

```
4L‹ā·>×ε4иø}ζR€.B»

```

Uses `01` instead of `o.` respectively.

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E because it can zip/transpose on a list of strings, where the new version would require a character-matrix.

```
4L      # Push list [1,2,3,4]
  ‹     # Check for each whether it's larger than the (implicit) input
   ā    # Push a list in the range [1,length] (without popping): [1,2,3,4]
    ·   # Double each: [2,4,6,8]
     >  # Increase each by 1: [3,5,7,9]
      × # Repeat the earlier checks that many times as strings
        #  (e.g. input=2 → [0,0,1,1] → ["000","00000","1111111","111111111"])
ε       # Map over each string:
 4и     #  Repeat it 4 times as list
   ø    #  Zip/transpose; swapping rows/columns
}ζ      # After the map: zip/transpose again, with implicit " " as filler
  R     # Reverse this list of lists
   €    # Map over each inner list:
    .B  #  Box: expand the single filler space to length 4 by adding trailing
        #  spaces based on the string with the longest length in the list
      » # Join each inner list by spaces; and then each string by newlines
        # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Ruby, 65 bytes

```
->n{(0..8).map{|x|(0..3).map{|y|(y<3-x/2?" ":y<n ??o:?.)*3}*' '}}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 26 bytes

Uses `1/0` instead of `o/.`.

```
3 5 7 9,.{¯9 5↑⍺4⍴⍕⍵}4↑⍴∘1

```

Try it online!

`⍴∘1`: Reshape of 1. Creates a vector of `L` 1's.
`4↑`: Take 4. Extend to length 4 by appending 0's.

`,.{...}`: Inner product. Pair elements from the computed boolean vector and `3 5 7 9` and call the inner dfn on it. Reduce the resulting list by concatenating character matrices horizontally.
`⍕⍵`: Format. Convert the 1 or 0 to a string.
`⍺4⍴`: Reshape into a `⍺×4` character matrix by replicating the digit.
`¯9 5↑`: Extend to a `9×5` matrix by padding with spaces to the top and right.
> 1 votes

# Answer
# C (gcc), 78 bytes

```
j,i;f(x){for(i=180;--i;putchar(j?i%5&&i/35+j/5<5?j/5+x>3?79:46:32:10))j=i%20;}

```

Try it online!

Pretty straightforward approach:
often times in C is convenient to iterate backwards the entire volume so we start with *i=lines x width*.
Each time we print the proper character based on div modulus values.

Luckily I found that I could save some Bytes by using i%35 instead of i%40 which would require some extra operations to fit the right shape of each bar.
> 1 votes

# Answer
# Jelly, 15 bytes

```
4RðḤ‘ṁ"@>z⁶Ṛx4Y

```

Prints with `o` as `0` and `.` as `1`.

**Try it online!**

### How?

```
4RðḤ‘x"@>z⁶Ṛx4Y - Main Link: integer, L
4               - four
 R              - range -> [1,2,3,4]
  ð             - new dyadic chain - f(X=[1,2,3,4], L)
   Ḥ            - double X          -> [2,4,6,8]
    ‘           - increment         -> [3,5,7,9]
        >       - X greater than L? -> [1>L,2>L,3>L,4>L]
       @        - with swapped arguments - f([1>L,2>L,3>L,4>L], [3,5,7,9]):
      "         -   zip with:
     x          -     times -> [[1>L,1>L,1>L],[2>L,2>L,2>L,2>L,2>L],[3>L,...],[4>L...]]
         z⁶     - transpose with filler of space characters
           Ṛ    - reverse
            x4  - times four (vectorises)
              Y - join with newline characters
                - implicit, smashing print

```
> 1 votes

# Answer
# Python 3, 76 bytes

```
lambda n:"".join(". o"[i<~i%4*8or-(i%4<n)]*4+"   \n"[i%4]for i in range(36))

```

Try it online!
> 1 votes

# Answer
# Java 11, ~~105~~ 102 bytes

```
n->{for(int i=36;i-->0;)System.out.print((i/4>8-i%4*2?" ":n<i%4?".":"o").repeat(4)+(i%4<1?"\n":" "));}

```

Could probably be golfed slightly more by removing the `.repeat(4)` and looping `144` times instead, but I don't have the time to figure it out for now.

Try it online.

**Explanation:**

```
n->{                   // Method with integer parameter and no return-type
  for(int i=36;i-->0;) //  Loop `i` in the range (36,0]:
    System.out.print(  //   Print:
       (i/4            //    If `i` integer-divided by 4
        >              //    is larger than
        8-i%4*2?       //    8 minus `i` modulo-4 times 2
         " "           //     Use a space
        :n<i%4?        //    Else-if the input is smaller than `i` modulo-4:
         "."           //     Use a dot
        :              //    Else:
         "o"           //     Use an O
       ).repeat(4)     //    Repeat this character 4 times
       +(i%4<1?        //    Once every four iterations:
         "\n"          //     Append a newline
        :              //    Every other iteration:
         " "));        //     Append a space instead

```
> 0 votes

# Answer
# brainfuck, 544 bytes

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

```

Try it online!

Builds each line in segments. Ungolfed:

```
memory layout
0    1    2    3    4    5    6    7    8    9    10   11   12   13
' '  dot  'o'  \n   cnt  inp  0    Nge1 0    Nge2 0    Nge3 0    Nge4

constants
space = 32
+[-->---[-<]>]>
[<<+>>>+<-]<
o = 111
-[>--<-------]>+
[<+>-]
dot = 46
>[<+>-]
+++++++[<++>-]
\n = 10
>+++++[<++>-]>
get input
-[>+<-----]>---<,>[<->-]<#

check 0
[
  >>+<<
  check 1
  -[
    >>>>+<<<<
    check 2
    -[
     >>>>>>+<<<<<<
     check 3
      -[
        >>>>>>>>+<<<<<<<<
        check 4
        -
      ]
    ]
  ]
]#
first 2 lines
++[
  15 spaces
  <+++++[<<<<...>>>>-]>-
  4 bar segment
  >>>>>>>>[<]<<<<<<<<<<<....
  [>]<.>>
]
next 2 lines
++[
  10 spaces
  <+++++[<<<<..>>>>-]>-
  3 bar segment
  >>>>>>[<]<<<<<<<<<....
  space
  [<]>.[>]>
  4 bar segment
  >>>>>>>>[<]<<<<<<<<<<<....
  [>]<.>>
]
next 2 lines
++[
  5 spaces
  <<<<<.....>>>>>-
  2 bar segment
  >>>>[<]<<<<<<<....
  space
  [<]>.[>]>
  3 bar segment
  >>>>>>[<]<<<<<<<<<....
  space
  [<]>.[>]>
  4 bar segment
  >>>>>>>>[<]<<<<<<<<<<<....
  [>]<.>>
]
last 3 lines
+++[
  -
  1 bar segment
  >>[<]<<<<<....
  space
  [<]>.[>]>
  2 bar segment
  >>>>[<]<<<<<<<....
  space
  [<]>.[>]>
  3 bar segment
  >>>>>>[<]<<<<<<<<<....
  space
  [<]>.[>]>
  4 bar segment
  >>>>>>>>[<]<<<<<<<<<<<....
  [>]<.>>
]

```

It could probably be shorter with a complex loop to handle generating each line but I couldn't get something like that to work.
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Wordle solver challenge

text:
# Question
Title: Wordle solver challenge
Wordle is a daily online word game that has received considerable attention recently.

# The Game

The object is to guess a secret word in the fewest attempts. Consider the following instance of the game:

The secret word is `rebus`, and the player's first guess was `arise`. The letters `r`, `s`, and `e` are displayed in yellow to indicate that these letters appear in the secret word, but not at these locations. Meanwhile, the letters in gray do not appear in the secret word at all. The player uses this information to formulate a second guess: `route`. Here, the `r` appears in green, indicating that `r` appears in the secret word at this location. Notice that each guess is an English word.

A comment on duplicated letters: If the first guess above were `river`, then the first `r` would appear in green, but the second `r` would appear in gray. In general, the duplicated letters are only highlighted if they are similarly duplicated in the solution, and letters appear in green whenever possible. As another example, suppose the secret is `inane` and we guess `nanny`. Then our first `n` will be marked in yellow, the second in gray, and the third in green. In this case, only two of our three `n`s are highlighted since the secret only has two `n`s.

# The Challenge

In this challenge, you will write code that plays Wordle as well as possible. The following link contains a curated list of 2315 common 5-letter words:

words.txt

Notably, every Wordle solution to date appears on this list, and I suspect future solutions will, too.

Your code will play Wordle by iteratively selecting words from the above `.txt` file and receiving Wordle-style feedback on which letters appear in the secret word. To evaluate your code, play this game 2315 times (each time using a different secret word from the above `.txt` file), and record the number of guesses it took to win. (While the official game terminates after six guesses, in this challenge, you may take arbitrarily many guesses.)

In the end, your score will be the histogram of the number of guesses required, arranged in a tuple. For example, `(1,1000,900,414)` is a 4-tuple that indicates that the code solved every word in only 4 guesses, with 414 words requiring all 4 guesses, 900 taking only 3, 1000 taking only 2, and one word being identified after a single guess. Your code must be deterministic (i.e., your first guess will be fixed), and so the first entry of your score tuple will necessarily be `1`.

A comment on implementation: There are a few ways to organize things (and to encourage participation, I don't want to impose any one way), but one approach is to write three programs: the game, the player, and the evaluator. The game receives a secret and a guess (both from words.txt) and outputs Wordle-style feedback. The player interacts with the game for some fixed secret word. The evaluator makes the player play the game for each secret word from words.txt. (One might use submissions from Build a Mastermind engine to write the game program, but for this challenge, the interesting program is the player.)

# The Winner

Scores will be compared in lexicographic order. That is, shorter tuples are better, and tuples of the same size are first compared in the last entry, then second-to-last entry, etc. For example:

`(1,1000,900,414)` \< `(1,1000,899,415)` \< `(1,999,900,415)` \< `(1,998,900,415,1)`

Lowest score wins.

# Answer
> 8 votes
# Python 3, (1, 149, 945, 1118, 102)

```
from collections import Counter

# history: a list of tuple of (guess, feedback)
# feedback: a list of length 5, each element can be MISS, CLOSE, or MATCH
def play(history):
  # Hard coded first guess
  turn = len(history) + 1
  if turn == 1:
    return 'trace'

  # When there are few words left
  remaining_words = [word for word in WORDS if all(get_feedback(guess, word) == feedback for guess, feedback in history)]
  if len(remaining_words) <= 2:
    return remaining_words[0]

  # Hardcoded hard case
  if turn == 3 and history == [('trace', [MISS, CLOSE, MISS, MISS, CLOSE]), ('risen', [CLOSE, MISS, MISS, MATCH, MISS])]:
    return 'howdy'

  guess_list = WORDS if turn > 2 and len(remaining_words) < 100 else remaining_words
  return find_best_guest(guess_list, remaining_words)

def find_best_guest(guess_list, secret_list):
  R = []
  secret_set = set(secret_list)
  for guess in guess_list:
    c = Counter([tuple(get_feedback(guess, secret)) for secret in secret_list])
    R.append([guess, len(c), guess in secret_set, -max(c.values())])
  best_guess = max(R, key=lambda t:t[1:])
  return best_guess[0]

```

Try it online!

Scorer

# Big idea

Each time, I pick the guess from the list of remaining words (words matching all previous guesses), such that the guess maximize the number of possible outcomes. For example, at the start, we guess "trace". This splits the possible secrets into 150 groups, only one of which is possible based on the feedback. For the second guess, if we guess a word from that group, then there is 1 universe where we guess correctly. Thus in total, we have 150 universes where we guess correctly within the first 2 turns. By maximizing the number of groups each turn, we can make sure that there are more universes where we guess correctly early on.

Following the naive strategy above, the result is `(1, 149, 1044, 904, 178, 31, 7, 1)`. If we score by lexicographical order from left to right, without caring about the length of the tuple, then this is the largest tuple possible. Heuristically, this is good since if the left entries of the tuple are as large as possible, then the right most entries will be small. However, because the most important criteria is the length of the tuple, I have to tweak this algorithm a bit to get rid of all cases that have \>5 turns.

# Optimization

* If we have too few remaining words, then we might have to guess a word outside of those, to get the best split. Specifically, I allow selecting from outside if we're at the 3rd guess (or after) and there are less than 100 remaining words.
* I brute forced search a some hard subtrees (e.g. 'trace' -\> 'risen') to get the worst case at most 5 guesses.

# Answer
> 6 votes
# Python 3, \[1, 49, 871, 1354, 40\]

**Idea**

1. Use Knuth's minimax algorithm for Mastermind as default strategy. That is, minimize the number of remaining words for worst case group.
2. Find good starting words. 'alter', 'cater', 'close', 'crate', 'crone', 'lance', 'react', 'slant', 'stole', 'trace' are some of the good words (best 10 in my opinion). 'trace' and 'crate' score \[1, x, x, x, 9x, 1\] and 'alter', 'cater', 'trace' words score \[1, x, x, x, 100\]. Other words have 110 5th guess or less. (All using default strategy)
3. Do this recursively.

* For each nth word, for each worst case group which results in at least one 5th guess, try every single word and find 10 best word that minimizes number of 5th guess.

For example, first guess 'lance' and feedback CLOSE, CLOSE, MISS, MISS, MATCH leaves 2 5th guesses using second move from default strategy 'blast'. One can find that using either 'sight', 'smart', 'sharp', or 'fight' reduces number of 5th guess to 1 and one can recursively continue from there.

```
from collections import Counter

hard_codes = {(): 'lance', (0, 1, 0, 0, 0): 'sport', (1, 1, 0, 0, 2): 'sight', (0, 2, 0, 0, 0): 'storm', (0, 2, 0, 0, 1): 'straw', (0, 0, 0, 0, 1): 'posit', (0, 0, 0, 0, 1, 0, 0, 0, 0, 0): 'defer', (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1): 'berry', (0, 0, 0, 0, 1, 0, 0, 0, 0, 1): 'deter', (0, 0, 0, 0, 1, 0, 2, 0, 0, 0): 'rowdy', (0, 0, 0, 0, 1, 0, 0, 0, 1, 0): 'drier', (0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 2): 'fiber', (0, 0, 0, 0, 1, 0, 0, 1, 0, 0): 'sever', (0, 0, 1, 0, 1): 'sewer', (1, 0, 0, 0, 1, 0, 0, 0, 2, 2): 'disco', (0, 0, 0, 0, 0): 'frost', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0): 'pudgy', (0, 0, 0, 0, 0, 0, 0, 1, 0, 0): 'buddy', (0, 0, 0, 0, 0, 0, 0, 2, 0, 0): 'woody', (0, 0, 0, 0, 0, 0, 2, 2, 0, 0): 'buddy', (0, 0, 0, 0, 0, 0, 0, 0, 1, 0): 'mushy', (1, 0, 0, 0, 0): 'still', (1, 0, 0, 0, 0, 0, 0, 0, 1, 0): 'plumb', (1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0): 'flood', (1, 0, 0, 0, 0, 0, 0, 0, 2, 1): 'fudge', (0, 0, 0, 0, 2): 'first', (0, 0, 1, 0, 0): 'wrist', (0, 0, 1, 0, 0, 0, 0, 0, 0, 0): 'nymph'}

# history: a list of feedbacks, flattened
# feedback: a list of length 5, each element can be MISS, CLOSE, or MATCH
def play(history, remaining_words):
    history = tuple(history)
    if history in hard_codes:
        return hard_codes[history]

    if len(remaining_words) <= 2:
        return remaining_words[0]

    key = lambda g: max(Counter(tuple(get_feedback(g, c)) for c in remaining_words).values())
    return min(WORDS, key=key)

```

Try it online!

Grader

Some interesting results outside of code golf (they have larger word set for guessing and the strategy cannot be applied to this challenge):

# Answer
> 5 votes
# BQN

```
┌─
╵ 1  2   3   4   5   6  7  8 9
  1 56 407 861 722 210 44 13 1
                               ┘

```

The strategy is very basic, this just chooses the first word in the word lists that is still possible according to the previous results. I will improve on that later, but for now I just wanted to get the "infrastructure" up.

```
#!/usr/bin/env bqn

# Judge takes the correct and word and a guess, and returns a pair of vectors
# The first has 1's at green letters, the second one 1's at yellow letters
Judge ← { word  guess:
    wrong ← ¬correct ← word=guess
    misplaced ← (+`⊸×wrong)⊏0∾word(⊒∘⊢<·+˝=⌜)○(wrong⊸/)guess
    correct⋈misplaced
}

# Game takes a path to the word list,
# plays every single word, and returns an histogram
Game ← {  file:
    words ← •FLines file
    1↓˘⊒˜⊸≍≠¨⊔˜ {⊸Judge _Player words}¨ words
}

# The Player takes a monadic judge as its left operand and a word list as the right argument
# It has to guess until it finds the right word and return its score ( Don't cheat ;) )
_Player ← { Ju _P words:
    score ← Ju attempt←⊑words
    ¬∧´⊑score ? 1+Ju _P words/˜(score≡Judge⟜attempt)¨ words ; 1
}

•Show Game "words.txt"

```

This should be run in the same directory as the *words.txt* file. You can try a modified version with only 100 words online here, the full program is a bit too much for the JS interpreter.

# Answer
> 3 votes
# Clojure, (1 59 1051 1166 38)

```
(def lookup {
;; turn 1
"" "stole",
;; turn 2
"*-*--" "prawn", "*----" "prank", "*--++" "spiel", "-+-+-" "final", "--+-*" "gourd", "*-*+-" "whoop", "*-*-*" "ranch", "-+*--" "truth", "++--+" "buyer", "+---*" "ranch", "--*+-" "dwarf", "--**-" "diner", "--*--" "droop", "-+++-" "total", "-+--*" "birch", "+--+-" "pubic", "*---*" "chirp", "---*+" "wordy", "-+-*-" "baggy", "---++" "rival", "-*--+" "utter", "-+-*+" "wound", "--+--" "hardy", "+-+-+" "verso", "*+--+" "sweep", "-++++" "motel", "*--+*" "smack", "+---+" "purer", "-+*+-" "graft", "+-+-*" "morph", "-+-+*" "earth", "*--*-" "ralph", "--*+*" "vegan", "---+*" "gland", "--*-+" "epoxy", "-++-+" "motor", "*+--*" "unzip", "**--*" "vigor", "-+---" "truth", "*+-+-" "split", "---+-" "brain", "*+*--" "churn", "**---" "prank", "+++--" "trash", "+--+*" "pulse", "---**" "aping", "*+---" "faith", "*--+-" "clink", "--+-+" "rocky", "-+*-*" "trove", "-++-*" "route", "++--*" "wrath", "+-*--" "rigid", "--++-" "local", "--+++" "mover", "+--++" "welsh", "**-*-" "still", "+-+--" "bacon", "*--**" "shale", "-+-++" "craft", "*--*+" "wimpy", "-+--+" "taint", "**--+" "drank", "----*" "guard", "+----" "champ", "--+*-" "dwarf", "***-*" "trunk", "***--" "murky", "----+" "cedar", "-----" "cramp", "---*-" "diary", "--*-*" "drank", "+-++-" "lousy", "-+-**" "blink", "++*--" "roost", "*-+--" "sonar", "+-*-*" "woman", "*-++-" "salvo", "++---" "dairy", "*---+" "preen", "-++--" "burnt",
;; turn 3
"----+-+--*" "unify"
})

(defn pick-guess [words]
  (let [nwords (count words)
        candidates (if (> 3 nwords) words dict)
        comparator #(let [f (frequencies (for [word words] (game word %)))]
          (- (* 100 (apply max (vals f))) (count f) (if (some #{%} words) 1 0)
             (reduce (fn [a [k v]] (+ a (* (/ v nwords) (/ (Math/log (/ nwords v)) (Math/log 2))))) 0 f)))
        counts (into {} (map (juxt identity comparator) candidates))]
    (apply min-key counts candidates)))

(defn player [blackbox]
  (loop [depth 1 history "" words dict]
    (let [guess (or (lookup history) (pick-guess words))
          feedback (blackbox guess)]
       (println guess)
       (println feedback)
       (if (= feedback "*****") depth
         (recur (inc depth) (str history feedback) (filter #(= feedback (game % guess)) words))))))

```

Player

Evaluator

## Strategy

Good heuristic rules behind picking the best next guess have already been discussed in the answers by Surculose Sputum and didgogns. However, any heuristics can still arrive quite far from the optimal solution, that's why it is always helpful to include some kind of more extensive evaluation of possible guesses, even if we don't undertake the daunting exercise of exhaustive search through all possible subtrees.

In this solution instead of fixing problematic cases in the deeper branches of the guessing tree, I decided to add an extensive enumeration step early in the process. In essence, this algorithm uses 2 predefined guesses instead of 1:

* For the 1st guess, the word `stole` was chosen as it produced the most promising results.
* For the 2nd guess, a (semi-)exhaustive enumeration was run. For any possible feedback from the game after the 1st guess that still leaves more than 2 valid secret candidates, further simulation was run with each of the top 200 words by heuristic score, and those that produced the best results were encoded in the lookup table used to pick the guess.
* 3rd & later guesses are normally picked using the heuristic. This procedure alone results in the overall score of `(1 59 1051 1164 40)`, which at the time of writing, ties the best answer for the number of 5-guesses, but gets an edge in 4-guesses. Then, I went further into some worse-case branches and found a better guess in the 3rd turn that saves another 2 points. Other such improvements are likely possible.

## Heuristic score

Since the challenge asks to optimize for the worst case, the primary factor for picking the best guess should be the minimax - the least among the maximum numbers of remaining secrets in each group. For the tie breaker score, I tried throwing in a mix including:

* The count of different possible feedbacks from a guess
* An indicator, if the word is still valid as a guess itself
* The information gain from the guess (as explained in 3Blue1Brown video)

However, the exact definition of the score that will yield better overall results at this stage becomes pretty much hit or miss, so that performing more exhaustive search seems like a more promising direction for potential further improvement.

# Answer
> 2 votes
# JavaScript (Node.js)

## \[ 1, 101, 650, 1000, 465, 87, 11 \]

A simple algorithm computing the list of remaining possible words and picking either the first one if there are less than 3 of them, or the one located at a precomputed index otherwise. (This is therefore playing in 'hard mode'.)

The precomputed values are based on a hash of the list of remaining words and were simply found with a naive random search running for a while. They are probably very far from optimal ones.

```
const GRAY    = 0;
const YELLOW  = 1;
const GREEN   = 2;

const LOOKUP = {'14143202':1,'26364370':2,'30190943':3,'38882992':23,'43995839':2,'46997544':2,'47100915':2,'58773399':2,'70621541':3,'76111564':0,'78629445':0,'83279074':4,'53c11c74':2100,'921bd960':36,'2528c69d':1,'7964d0cf':11,'2e48ad14':2,'8b3ca4cb':0,'79c8a291':121,'8cf4eed6':3,'67c21ff2':1,'bc7835a4':33,'26270c62':16,'5095e262':0,'6fc77853':90,'aa78d00f':2,'efd5ee03':13,'f7e85504':0,'9ed6869a':13,'2f28d552':2,'ebadec4c':9,'dd657502':1,'75e99b72':9,'9e4d1e39':1,'6b1ee6bc':0,'94847f8e':2,'d69854c6':1,'79f08c51':29,'975ea22e':5,'74a4f766':4,'93913d7d':1,'f5a80453':3,'834b3950':10,'d311f685':3,'cf69c214':0,'3c1bb448':1,'eea7d694':7,'67980f55':2,'5bc6e50f':1,'b6a74c7f':1,'41086a3f':5,'c42acaa3':5,'f1ed7962':19,'f013f6de':1,'e2c19ca8':6,'bd62ab41':2,'31850f4c':14,'a65e6c62':1,'d8d65610':0,'0b60b7a3':7,'377f178d':1,'bed253cc':2,'55417f48':21,'2a195973':2,'89b99ca0':0,'5734ec44':1,'d994dab6':6,'747ac68c':1,'5cbfb6df':4,'6d145f3f':9,'cd7cd6dd':4,'ef04be81':2,'4332f7de':4,'9d0bdd07':1,'dc12394d':9,'90ae0678':2,'c76b85f1':4,'ec06d2ca':2,'c1c8a84f':10,'e8c899d1':0,'cc022066':14,'48f50318':3,'cac2bc3a':3,'e25292bb':1,'48a08d77':5,'14db746d':1,'f086993f':0,'5ce89220':9,'f9ad9ada':1,'229f8965':0,'0c4905a7':0,'0302235f':0,'96f622f5':0,'54252eab':2,'0c8e25a6':3,'9286bc52':3,'d2d53386':2,'c8f8fb4e':166,'702bb5a4':16,'38cbb5d6':0,'4474aa82':18,'d96b3f5d':28,'30ec466d':4,'8796640a':2,'5ccf8034':4,'f397de6b':18,'40ba7a83':38,'85ee6b8a':2,'1ee95569':0,'e6881291':1,'165b616c':0,'bb9a5866':0,'79fbfdcf':27,'b43dee5f':2,'50f28e4b':197,'f2ba2523':23,'fdef66e9':1,'e53b6fb5':1,'d6d16e7d':15,'708ab8ab':13,'c1214176':1,'453b0ab9':1,'bf525f76':6,'9baaa801':12,'99a34529':3,'e8cdc21c':1,'a1d69531':3,'43cb5c4e':4,'f2cc4081':3,'4497f9dd':3,'2c4dd2f4':3,'7f76ec38':1,'216cf28f':6,'427af08e':1,'5565ea4a':3,'ab97f7e6':5,'d621e228':2,'ac239f20':6,'ab593aad':1,'e1a6be75':0,'07a70237':1,'e5849d40':1,'0771e66f':0,'f0b2ccad':3,'5263f0b5':4,'dc007dc6':1,'8061bddc':2,'1b738423':7,'9c3c3eb4':3,'2c207b38':3,'1e560e0c':1,'9d483c9c':1,'a54ad297':3,'adf1e213':1,'8ece546f':0,'2868ded4':1,'0be47967':2,'76c48ab0':1,'ec5a2986':5,'08f02724':4,'2f1e8fe0':13,'61b01746':2,'a945af43':2,'b3298621':0,'c902c85d':0,'59b4b3a6':0,'65adc148':7,'da2d4f4f':1,'bdabc7b7':1,'363a673f':78,'57df5665':21,'4dff9da8':2,'0e86ae9c':7,'6c77953e':1,'714ca992':2,'32f55d3c':0,'8f730c78':4,'bef4237c':9,'0cd58e64':1,'9782b612':1,'46e616b4':5,'d8aea010':1,'9928cb50':12,'49a9a502':0,'899b630b':2,'e62dc0ee':0,'5e422bc1':1,'028f178c':1,'0d18106f':1,'73318b3f':1,'f99ae1c9':34,'e1cd8425':4,'4dfed81f':3,'add3dd22':10,'3b3db49a':0,'f1034ad7':2,'4a5046f3':1,'7ac5ce28':2,'28536ff5':0,'75ea6e53':1,'63fea0b1':2,'ab09cc25':2,'d6ceba64':2,'bfc4bed7':3,'960d9151':0,'cd868422':3,'11a4d91c':1,'83a7119c':0,'6c552bd4':0,'77095d30':10,'c8bcfcac':2,'ba21e593':0,'3d336693':5,'fba36a94':2,'10f9f1ed':2,'6204e786':0,'6e07f888':2,'2bb3482a':10,'d686a716':2,'e31d35d2':2,'dce35a86':0,'78d964ba':1,'851c0f3b':1,'37f4f3b4':2,'fe75e788':1,'93d09506':5,'604107e8':0,'44c077ae':13,'0f7f452d':1,'7c9bce8b':4,'7e6687c7':2,'7e58e0a8':5,'7dbabf3c':0,'65aec92b':74,'5b0b56f2':4,'ce548f7e':1,'f37040ba':0,'61a3de73':0,'6e752063':1,'f70d8eb1':0,'3855ec7a':4,'ec9b1d60':1,'a9de0559':2,'5db0cc60':3,'09ac011b':1,'06f2bd54':19,'c0abb288':1,'7740b151':8,'a2e3e28b':0,'f4c7948d':2,'dd7e56a0':2,'257e38eb':2,'8ec556e6':2,'fad4a8aa':2,'007da174':3,'48a5ee80':8,'daf0805d':1,'2c0bbd90':22,'a68704dd':2,'2edc16a2':0,'bdd7d751':1,'12fa8a9c':2,'bd6c82c1':5,'daa03ebb':2,'14a007cc':3,'b057a058':3,'fe2e6048':3,'930b8a67':2,'e6021a93':0,'715f9f50':2,'3bb3f9c8':2,'314ae620':2,'bf9d0ff9':3,'d6f78470':3,'6ffd5525':0,'bfa4d989':7,'2fcb4ed3':1,'8dff3605':2,'cc0e1441':2,'510e2239':2,'932cad71':4,'8a2babae':7,'b5069042':2,'870facb1':2,'81dc1545':2,'a366065a':2,'7f92a451':1,'17e04242':1,'00f397da':1,'5c792244':0,'d0bb4351':0,'98ffa283':3,'78bac9e6':2,'14f2bafd':0,'d086c2ee':2,'08a38507':0,'5fd0ea1d':3,'2ba1913e':0,'117654e7':1,'f5eea614':7,'b811e17b':1,'69dda9de':3,'46b94977':2,'7b766732':3,'af195935':2,'b1eb20d4':3,'8b66476e':2,'aa533625':0,'be9f3907':0,'743ce282':3,'02a97dc8':4,'42bec4ec':0,'5f8be41b':2,'4e053217':17,'efaf99ff':2,'558976a8':3,'f61dff94':2,'13784ef6':0,'05354011':0,'382e4364':1,'6f20b790':1,'e1b754bf':2,'c979fdaf':1,'ddd9b414':1,'2a2dddfc':3,'7f585610':2,'dc70293f':12,'7f328e23':2,'bbc51714':4,'d970cf9e':1,'f1db083f':3,'c698465c':1,'d67bb6a4':2,'6bf5c971':0,'a5dad7ee':3,'c20230d7':2,'6c69bcc4':2,'ddaa91fc':0,'aceffaa8':3,'5ac4f937':0,'fb589434':0,'e3f3c1d7':2,'062698f6':0,'67cff0e7':0,'2c367774':1,'5f163080':0,'c526fc35':0,'b77cce91':0,'f69aa500':2,'9f5bb9b2':1,'88c58554':2,'4524f59e':1,'d8d3541e':1,'c007c12f':0,'71a48e89':4,'897fcd24':0,'8f6a94fe':0,'4ab727d1':3,'95d7089e':0,'44b3c427':4,'689a27db':2,'42f43571':3,'b02a73cd':0,'c4310e8c':1,'e605072f':5,'cea8ea81':1,'072fdcc0':1,'bb4c095c':1,'bb6830d5':2,'ae22f8fb':1,'ffa4e084':1,'79aec494':2,'db71d0dc':2,'8f481b7a':4,'5e30001f':1,'0e114e8c':1,'6ecfeac0':0,'da3c8846':1,'bb77b1b0':1,'3d8d6830':3,'063be66d':0,'b07584b9':1,'e6aa8602':2,'00ee7c82':4,'8a0b3a9b':1,'fff50a02':2,'9522070e':2,'9fb93302':2,'f5c487bb':1,'f3becf6c':2,'7acd7d34':1,'e39973c9':0,'48a2f6d7':10,'c556b389':0,'aae28d8b':2,'26394f7b':2,'6987fcb5':1,'3c8b70b5':1,'0ec76191':3,'bede1e43':3,'e9e75a90':2,'93ecaaaf':7,'9c85d484':0,'6cfc5c54':4,'0e956f0c':0,'e0ee2ae6':2,'ae37d2b7':6,'e7356cc4':1,'191bee62':4,'34ac52df':2,'edf40c22':1,'a3c46eae':1,'07c59ea8':0,'cebc4b79':2,'b83825b1':4,'967d3108':2,'52674dd2':1,'ad289b28':0,'671ce983':5,'3f340614':1,'99027f41':4,'96da67b7':0,'4a8871e3':0};

let wordList = require('fs').readFileSync(0).toString().split(' ');

let stat = [];

wordList.forEach(secret => {
  let hist = solve(word => guess(word, secret)),
      n = hist.length;

  console.log('[' + secret + '] ' + hist.join(' '));
  stat[n] = -~stat[n];
});

console.log(stat.slice(1));

function solve(blackBox) {
  let list = [...wordList],
      hist = [],
      w, j;

  for(j = 1;; j++) {
    let key = list.join(''),
        md5 = require('crypto').createHash('md5').update(key).digest('hex').slice(0, 8);

    w = list[list.length < 3 ? 0 : LOOKUP[md5]];
    hist.push(w);

    let res = blackBox(w);

    if(res.every(c => c == GREEN)) {
      break;
    }
    list = filter(list, w, res);
  }
  return hist;
}

function filter(list, w, res) {
  let cnt = {};
  let exact = {};
  res.map((c, i) => c == GRAY ? (cnt[w[i]] = ~~cnt[w[i]], exact[w[i]] = true) : cnt[w[i]] = -~cnt[w[i]]);
  let pattern = RegExp(res.map((c, i) => c == GREEN ? w[i] : '[^' + w[i] + ']').join(''));
  let newList = list.filter(word => pattern.test(word));

  res.forEach((_, i) => {
    if(cnt[w[i]] !== undefined) {
      newList = newList.filter(word => {
        let n = [...word].reduce((p, c) => p += c == w[i], 0);
        return exact[w[i]] ? n == cnt[w[i]] : n >= cnt[w[i]];
      });
    }
  });
  return newList;
}

function guess(word, secret) {
  let misplaced = {};

  [...secret].forEach((c, i) => c != word[i] ? misplaced[c] = -~misplaced[c] : 0);

  return [...word].map((c, i) => c == secret[i] ? GREEN : misplaced[c] ? (misplaced[c]--, YELLOW) : GRAY);
}

```

Try it online!

# Answer
> 1 votes
# Python

**\[1, 108, 696, 952, 436, 101, 17, 4\]**

Of course, the fact that there are 8 elements sucks, but I'll update the answer as I improve my algorithm.

Complete code, including scoring:

```
# Wordle challenge.

with open('words.txt', 'r') as wordsFile:
    words = wordsFile.read().split('\n')

resultsDict = {} # dictionary format is easier, but then it will be converted to a tuple.

def best(pool): # it's a function that determines the word with the "most common" letters.
    best_word = ''

    for _ in range(5):
        best_word += max('abcdefghijklmnopqrstuvwxyz', key=lambda letter: len([w for w in pool if w.startswith(best_word + letter)]))

    return best_word

def get_feedback(guess, wo): # it's a function to give feedback.
    return [
        'LET' * (guessed in wo) + 'POS' * (guessed in wo and guessed == actual)
        for guessed, actual in zip(guess, wo)
    ]

for word in words:
    guesses = 0
    cur_words = words

    while True:
        cur_guess = best(cur_words) # guess the best word.
        feedback = get_feedback(cur_guess, word) # "word" is only accessed here. Nowhere else.
        guesses += 1
        if all([x == 'LETPOS' for x in feedback]): # mission accomplished
            break

        # set "cur_words" to a new set based on the feedback.

        cur_words = [
            w
            for
            w
            in cur_words
            if
            all([w[i] == cur_guess[i] for i in range(5) if feedback[i] == 'LETPOS'])
            and
            all([cur_guess[i] in w and w[i] != cur_guess[i] for i in range(5) if feedback[i] == 'LET'])
            and
            all([cur_guess[i] not in w for i in range(5) if feedback[i] == ''])
        ]

    if resultsDict.get(guesses):
        resultsDict[guesses] += 1
    else:
        resultsDict[guesses] = 1

    print(resultsDict, words.index(word))

resultsTuple = [resultsDict.get(i) or 0 for i in range(1, max(resultsDict.keys()) + 1)]
print(resultsTuple)

```

All I do here is pick the word with the most common letters each time. For instance, if there are 5 words:

```
abcde
abcfg
aedri
bbbbb
cdegh

```

It goes through the first letters: a, a, a, b, and c. It sees that a is the most common, so it starts with a. Its guess so far is: a

Same for the second letters: as it has isolated a as the first letter, it only considers b, b, and e. (of the first three words). It sees that b is more common, so it adds b. Its guess so far is: ab

Same for third letters: abc

Fourth letter: both d and f are equally common, so in picking the maximum it just chooses the first one: d

Now the only option is e, so its guess is **abcde**.

---
Tags: code-challenge, word-puzzle
---