title: Maximal hexagonal dot pattern

text:
# Question
Title: Maximal hexagonal dot pattern
## Challenge

Imagine a hexagonal grid as shown below. Let's call such a grid has size \\$n\\$ if it has \\$n\\$ dots on one side. The following is one of size 3:

```
  - - -
 - - - -
- - - - -
 - - - -
  - - -

```

Then, pick as many dots as possible on the grid so that no two dots are adjacent. For size 3, the maximum is 7 dots:

```
  - * -          * - *
 * - - *        - - - -
- - * - -  or  * - * - *
 * - - *        - - - -
  - * -          * - *

```

Your task is to output such a grid. For a size-\\$n\\$ hexagon, the output must contain exactly A002061(n) = \\$n^2-n+1\\$ non-adjacent dots. The corresponding maximal pattern can be found in this image linked on the OEIS sequence (imagine this: dissect all the hexagons there into triangles, remove one outermost layer of triangles, and pick the centers of original hexagons). The corresponding ASCII-art output must look like the following, modulo rotation/reflection:

```
n = 1
*

n = 2
 * -
- - *
 * -

n = 3 (following or alternative shown above)
  * - *
 - - - -
* - * - *
 - - - -
  * - *

n = 4
   * - - *
  - - * - -
 - * - - * -
* - - * - - *
 - * - - * -
  - - * - -
   * - - *

n = 5
    - * - - *
   * - - * - -
  - - * - - * -
 - * - - * - - *
* - - * - - * - -
 - * - - * - - *
  - - * - - * -
   * - - * - -
    - * - - *

n = 6
     - * - - * -
    * - - * - - *
   - - * - - * - -
  - * - - * - - * -
 * - - * - - * - - *
- - * - - * - - * - -
 * - - * - - * - - *
  - * - - * - - * -
   - - * - - * - -
    * - - * - - *
     - * - - * -

n = 7
      * - - * - - *
     - - * - - * - -
    - * - - * - - * -
   * - - * - - * - - *
  - - * - - * - - * - -
 - * - - * - - * - - * -
* - - * - - * - - * - - *
 - * - - * - - * - - * -
  - - * - - * - - * - -
   * - - * - - * - - *
    - * - - * - - * -
     - - * - - * - -
      * - - * - - *

n = 8
       - * - - * - - *
      * - - * - - * - -
     - - * - - * - - * -
    - * - - * - - * - - *
   * - - * - - * - - * - -
  - - * - - * - - * - - * -
 - * - - * - - * - - * - - *
* - - * - - * - - * - - * - -
 - * - - * - - * - - * - - *
  - - * - - * - - * - - * -
   * - - * - - * - - * - -
    - * - - * - - * - - *
     - - * - - * - - * -
      * - - * - - * - -
       - * - - * - - *

n = 9
        - * - - * - - * -
       * - - * - - * - - *
      - - * - - * - - * - -
     - * - - * - - * - - * -
    * - - * - - * - - * - - *
   - - * - - * - - * - - * - -
  - * - - * - - * - - * - - * -
 * - - * - - * - - * - - * - - *
- - * - - * - - * - - * - - * - -
 * - - * - - * - - * - - * - - *
  - * - - * - - * - - * - - * -
   - - * - - * - - * - - * - -
    * - - * - - * - - * - - *
     - * - - * - - * - - * -
      - - * - - * - - * - -
       * - - * - - * - - *
        - * - - * - - * -

n = 10
         * - - * - - * - - *
        - - * - - * - - * - -
       - * - - * - - * - - * -
      * - - * - - * - - * - - *
     - - * - - * - - * - - * - -
    - * - - * - - * - - * - - * -
   * - - * - - * - - * - - * - - *
  - - * - - * - - * - - * - - * - -
 - * - - * - - * - - * - - * - - * -
* - - * - - * - - * - - * - - * - - *
 - * - - * - - * - - * - - * - - * -
  - - * - - * - - * - - * - - * - -
   * - - * - - * - - * - - * - - *
    - * - - * - - * - - * - - * -
     - - * - - * - - * - - * - -
      * - - * - - * - - * - - *
       - * - - * - - * - - * -
        - - * - - * - - * - -
         * - - * - - * - - *

```

## I/O and rules

You can use any two distinct non-whitespace chars for marked and unmarked dots respectively. Trailing spaces on each line and leading/trailing whitespaces are allowed. Outputting a list of lines, and outputting integer charcodes instead of the corresponding chars are also allowed.

Standard rules apply. The shortest code in bytes wins.

# Answer
> 5 votes
# Charcoal, 33 bytes

```
ＮθＧ↙↘→→↗↖θ⎇﹪θ³“⟲∧ＬＶoIＧ；”“⟲∧⦄≧Σ¶ζ；

```

Try it online! Link is to verbose version of code. Explanation: After reading in `n`, the code simply draws a hexagon using one of two fill patterns depending on whether `n` is a multiple of 3; if it is, the fill pattern has the `*` one `-` in from the corner, otherwise it has the `*` in the top left corner.

# Answer
> 4 votes
# Python 3.8 (pre-release), 92 bytes

```
f=lambda n,i=0:[l:=' '*(n-i)+('- * - '*n)[n%3%2+i<<1:][:n+i<<1]]+(n>i+1and[*f(n,i+1),l]or[])

```

Try it online!

# Answer
> 3 votes
# Haskell, 84 bytes

```
f n=[[" * - -"!!mod(i+gcd 3n)6|i<-[1,3..2*y]++[4*y..2*y+4*n-4]]|y<-abs<$>[1-n..n-1]]

```

Try it online!

# Answer
> 2 votes
# Jelly,  ~~27~~  26 bytes

```
3ḍ6_BṙN€ṁ"Ḥ’rƊK€ṭ"Ḷ⁶ẋƊṚŒḄY

```

A full program that accepts a positive integer and prints using `0` as `*` and `1` as `-`.

**Try it online!** Or see a few with `*` and `-` in place of `0` and `1`.

### How?

```
3ḍ6_BṙN€ṁ"Ḥ’rƊK€ṭ"Ḷ⁶ẋƊṚŒḄY - Main Link: positive integer, n
3ḍ                         - three divides (n)? -> 1 if n is a multiple of three else 0
  6                        - six
   _                       - subtract -> 5 if n is a multiple of three else 6
    B                      - to binary -> 101 (i.e. "-*-") ...else 110 (i.e. "--*")
      N€                   - negate each (of implicit [1..n]) -> [-1,-2,...,-n]
     ṙ                     - rotate (110 or 101) left by (each of those) -> Patterns (one for each row of bottom half of a hexagon)
             Ɗ             - last three links as a monad, f(n):
          Ḥ                -   double -> 2n
           ’               -   decrement -> 2n-1
            r              -   (2n-1) inclusive range (n) -> [2n-1..n]
         "                 - zip (Patterns) and (range) applying, f(Pattern, i):
        ṁ                  -   mould like -> resized rows using repetition
              K€           - join each with space characters -> Rows
                     Ɗ     - last three links as a monad, f(n):
                  Ḷ        -   lowered range -> [0..n-1]
                   ⁶       -   space character
                    ẋ      -   repeat -> leading spaces for bottom half
                 "         - zip (Rows) and (leading spaces) applying, f(row, spaces):
                ṭ          -   tack (row) to (spaces)
                      Ṛ    - reverse -> top of the hexagon
                       ŒḄ  - bounce -> whole hexagon
                         Y - join with newline characters
                           - implicit, smashing print

```

---
Tags: code-golf, math, ascii-art, hexagonal-grid
---


# Question
Title: Flatten a parabola keeping the distances between points along the curve constant
### Background

Math SE's HNQ How to straighten a parabola? has 4,000+ views, ~60 up votes, 16 bookmarks and six answers so far and has a related companion HNQ in Mathematica SE How to straighten a curve? which includes a second part asking to move a point cloud along with the curve that we can ignore here.

From the Math SE question:

> Consider the function \\$f(x)=a\_0x^2\\$ for some \\$a\_0\in \mathbb{R}^+\\$. Take \\$x\_0\in\mathbb{R}^+\\$ so that the arc length \\$L\\$ between \\$(0,0)\\$ and \\$(x\_0,f(x\_0))\\$ is fixed. Given a different arbitrary \\$a\_1\\$, how does one find the point \\$(x\_1,y\_1)\\$ so that the arc length is the same?
>
> Schematically,
>
> In other words, I'm looking for a function \\$g:\mathbb{R}^3\to\mathbb{R}\\$, \\$g(a\_0,a\_1,x\_0)\\$, that takes an initial fixed quadratic coefficient \\$a\_0\\$ and point and returns the corresponding point after "straightening" via the new coefficient \\$a\_1\\$, keeping the arc length with respect to \\$(0,0)\\$. Note that the \\$y\\$ coordinates are simply given by \\$y\_0=f(x\_0)\\$ and \\$y\_1=a\_1x\_1^2\\$.

### Problem

Given a positive integer n and values a0 and a1 defining the original and new parabolas:

1. Generate \\$n\\$ equally spaced values for \\$x\_0\\$ from 0 to 1 and corresponding \\$y\_0\\$ values.
2. Calculate the new \\$x\_1\\$ and \\$y\_1\\$ such that their path distances along the new parabola are equal to their old distances.
3. Output the \\$x\_0\\$, \\$x\_1\\$ and \\$y\_1\\$ lists so that a user could plot the two parabolas.

**note:** The basis of the calculation can come from any of the answers to either linked question or something totally different. If you choose to use a numerical rather than analytical solution an error of \\$1 \times 10^{-3}\\$ would be sufficient for the user to make their plot.

Regular Code Golf; goal is shortest answer.

### Example

This is quite a bit late but here is an example calculation and results. I chose the same numbers as in Eta's answer in order to check my math.

```
s0: [0.00000, 0.13589, 0.32491, 0.59085, 0.94211, 1.38218, 1.91278, 2.53486, 3.24903]
x0: [0.00000, 0.12500, 0.25000, 0.37500, 0.50000, 0.62500, 0.75000, 0.87500, 1.00000]
x1: [0.00000, 0.13248, 0.29124, 0.46652, 0.64682, 0.82802, 1.00900, 1.18950, 1.36954]

```

script:

```
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root

def get_lengths(x, a): # https://www.wolframalpha.com/input?i=integrate+sqrt%281%2B4+a%5E2x%5E2%29+x%3D0+to+1
    return 0.5 * x * np.sqrt(4 * a**2 * x**2 + 1) + (np.arcsinh(2 * a * x)) / (4 * a)

def mini_me(x, a, targets):
    return get_lengths(x, a) - targets

a0, a1 = 3, 1.5

x0 = np.arange(9)/8

lengths_0 = get_lengths(x0, a0)

wow = root(mini_me, x0.copy(), args=(a1, lengths_0))

x1 = wow.x

fig, ax = plt.subplots(1, 1)

y0, y1 = a0 * x0**2, a1 * x1**2

ax.plot(x0, y0, '-')
ax.plot(x0, y0, 'ok')

ax.plot(x1, y1, '-')
ax.plot(x1, y1, 'ok')

np.set_printoptions(precision=5, floatmode='fixed')

things = [str(q).replace(' ', ', ') for q in (lengths_0, x0, x1)]
names = [q + ': ' for q in ('s0', 'x0', 'x1')]

for name, thing in zip(names, things):
    print('    ' + name + thing)

_, ymax = ax.get_ylim()
xmin, _ = ax.get_xlim()

ax.text(x0[-1:]+0.03, y0[-1:]-0.1, str(a0) + 'x²')
ax.text(x1[-1:]-0.04, y1[-1:]-0.1, str(a1) + 'x²', horizontalalignment='right')

title = '\n'.join([name + thing for (name, thing) in zip(names, things)])

ax.set_title(title, fontsize=9)

plt.show()

```

# Answer
# Mathematica, ~~108~~ 107 bytes

```
{n,a,b}=Input[];L=ArcLength;Subdivide@--n
x/.FindRoot[{t,t^2a}~L~{t,0,#}-{t,t^2b}~L~{t,0,x},{x,0}]&/@%
%^2b

```

(Assuming an interactive environment). Input is entered in the form `{n, a0, a1}`. Below is the output of a sample run with input `{9, 3, 1.5}`:

```
{0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1}
{0., 0.13247799662957596, 0.2912428843578418, 0.4665152489073556, 0.6468180849532895, 0.8280191118364263, 1.0089961907516996, 1.189503180997409, 1.369535545562379}
{0., 0.026325629386478908, 0.1272336265336128, 0.3264547161946379, 0.6275604525339613, 1.0284234743495764, 1.5271099694271602, 2.122376726404432, 2.8134414158382643}

```

## Explanation

This uses `FindRoot` to find `x`s where the `ArcLength` of the original equation to each point in x0 matches the `ArcLength` of the flattened equation up to each `x`.

Here is a visualization of the points in the example:

With the (identical) corresponding arc lengths at each point:

```
{0., 0.1358872650466621, 0.32491055615709175, 0.5908450391982809, 0.9421066199781004, 1.3821781999397988, 1.9127768947936938, 2.534864156640448, 3.249029586202852}

```
> 7 votes

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


title: Eric Angelini's "1995" puzzle

text:
# Question
Title: Eric Angelini's "1995" puzzle
The following puzzle was invented by Eric Angelini in September 2007.

As mentioned in A131744 :

> the sequence is defined by the property that if one writes the English names for the entries, replaces each letter with its rank in the alphabet and calculates the absolute values of the differences, one recovers the sequence.

To be precise, the alphabet starts at 1, so a is 1, b is 2, etc. Also, 15 is supposed to be treated as fifteen and 21 as twentyone (not twenty-one).

## Example :

Begin with 1 :

```
1 -> "one" -> 15,14,5 -> absolute(15-14),absolute(14-5) -> 1,9
1,9 -> "one,nine" -> 15,14,5,14,9,14,5 -> 1,9,9,5,5,9
1,9,9,5,5,9 -> "one,nine,nine,five,five,nine" -> 15,14,5,14,9,14,5,14,9,14,5,6,9,22,5,6,9,22,5,14,9,14,5 -> 1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9
1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9 -> ...

```

So the first 22 terms are : `1,9,9,5,5,9,9,5,5,9,1,3,13,17,1,3,13,17,9,5,5,9`

You can find the 40000 first terms here : b131744

## Challenge

Sequence I/O methods apply. You may use one of the following I/O methods:

* Take no input and output the sequence indefinitely,
* Take a (0- or 1-based) index i and output the i-th term,
* Take a non-negative integer i and output the first i terms.

The shortest code in bytes wins.

# Answer
> 4 votes
# Python 3, 119 bytes

Outputs the sequence indefinitely.

```
from unicodedata import*
p,*a=b'5NE'
for x in a:
 if x>45:n=abs(p-x);a+=name(chr(13144+n))[38:print(n%24)].encode();p=x

```

Try it online!

Python's `unicodedata.name` allows us to access the name of a unicode character. It happens that the characters with codepoints in the range `0x3358..0x336D` partially contain all of the required words (as can be seen in this list). The only nuance is at `twentyone`, of which `name()` gives us `twenty-one` instead. This is fixed with a simple `if x>45`, which ignores any existing `-`. This allows us to save over 70 bytes in total. Other than the sneaky `unicodedata.name`, it is essentially the same as the answer below.

# Python 3, 196 bytes

```
p,*a=b'Wne'
for x in a:n=abs(x-p);print(n%22);p=x;a+=b'zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,four,fif,,seven,eigh,,,twentyone,,'.split(b',')[n]+b'teen'*(12<n<20)

```

Try it online!

### Explanation

We start off with `a = b'ne'`, which will keep track of all the English words. Note that `ne` are the last two letters of `one` (the first number in the sequence). In the following for loop, we iterate over `a`, and in each iteration we add a word to the sequence based on the value of `abs(x-p)`, where `x` and `p` are the current and previous letters in `a`, respectively.

The illustration below, while not an exact model, roughly describes the algorithm I am using to construct the sequence:

```
'one',             n = abs(s[2]-s[1]) = abs('e'-'n') = 9 ->
'onenine',         n = abs(s[3]-s[2]) = abs('n'-'e') = 9 ->
'oneninenine',     n = abs(s[4]-s[3]) = abs('i'-'n') = 5 ->
'onenineninefive', n = abs(s[5]-s[4]) = abs('n'-'i') = 5 ->
...

```

One last thing to mention is the peculiar `W` in the initialization of `a`, or the strange `%22` within the `print` statement. These are both needed to print the initial `1`. We may get rid of them for **190 bytes**, but the `1` at the beginning would be omitted:

```
p,*a=b'ne'
for x in a:n=abs(x-p);print(n);p=x;a+=b'zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,four,fif,,seven,eigh,,,twentyone'.split(b',')[n]+b'teen'*(12<n<20)

```

This is currently the shortest fix I could find for eliminating this edge case, though there's likely a shorter approach (I'll exclude an explanation for it as an exercise to the reader).

# Answer
> 3 votes
# JavaScript (Node.js),  ~~240~~  228 bytes

*Thanks to @ovs for pointing out that 16, 19 and 20 are never used*

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

```
f=(n,a=[1])=>1/a[n]?a[n]:f(n,[...Buffer(a.map(x=>`ZeroOneTwoThreeFourFiveSixSevenEightNineTenElevenTwelveThirteenFourteenFifteenXSeventeenEighteenXXTwentyone`.match(/.[a-z]*/g)[x]).join``)].map(x=>Math.abs(a-(a=x&31))).slice(1))

```

Try it online!

# Answer
> 3 votes
# Jelly, ~~69~~ 64 bytes

```
ị“£3ṃ×ʋƁṘFqœ<ɦẎĠ_NɗṾDæ¢$⁽ċ¶Ọɦµ⁽ƭẈġȥ⁶J§GaĊƙ-ƬėƓjḢƥ4¶;»Ḳ¤FOạƝ
1Ç¡ḣ

```

Try it online!

A pair of links that is called as a monad with an integer input \\$n\\$ and returns the first \\$n\\$ terms. Slow for larger n (since it actually generates far more terms than needed before truncating the list). At a cost of a byte, this is much more efficient.

Thanks to @JonathanAllan for saving 5 bytes!

## Explanation

```
ị                | Index into:
 “£…;»Ḳ¤         | - "one two three four … twentyone zero", split on spaces
        F        | Flatten
         ØaiⱮ    | Index of each character in the lowercase alphabet
             ạƝ  | Absolute differences of neighbouring pairs

```

```
1                | Starting with 1:
 Ç¡              | Call the helper link n times
   ḣ             | First n values

```

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

outputs the first i terms

```
(s=#;NestWhile[Abs@Differences@Flatten[LetterNumber[Characters@IntegerName@#/."-"->""]&/@#]&,{1},Tr[1^#]<s&][[;;s]])&

```

Try it online!

# Answer
> 2 votes
# Vyxal, 83 bytes

```
1 9"£{`λḭ ƛ» ∧ḭ ⟇¯ ×² ß• ⌐≤ ƈḞ ∵‹ ¢Ṗ Ẇ„ ⟨ǐ t¥ẏ⟑⌈ ⟇¯⟑⌈ Ṡ□ ⌐≤⟑⌈ e⋏ṫ⟑⌈ ←⊍λḭ`⌈¥‹İṅC¯ȧ…£

```

Try it Online!

Outputs the values infinitely

# Answer
> 1 votes
# Factor \+ `math.text.english`, ~~109~~ 98 bytes

```
[ { 1 } [ [ number>text R/ \sand|,|-| / ""re-replace >array ] map-flat differences vabs ] repeat ]

```

Try it online!

Takes a 0-based index and outputs the i-th term.

* `{ 1 } [ ... ] repeat` Call a quotation a given number of times, transforming our starting sequence `{ 1 }` that many times.
* `[ ... ] map-flat` Apply a quotation to each element of a sequence, collecting each result into a flat sequence.
* `number>text` Convert a number to a string, like `2222 -> "two thousand, two hundred and twenty-two"`.
* `R/ \sand|,|-| / ""re-replace` Since number\>text produces commas, spaces, hyphens and `" and"`, strip them out with a regular expression.
* `>array` Convert the string to an array (e.g. `"hi" -> { 104 105 }`). This is necessary for `differences` to work properly.
* `differences` Take the first-order forward difference.
* `vabs` Take the absolute value of a sequence. (Like `[ abs ] map`, but shorter).

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


title: Rotate brackets until they're balanced

text:
# Question
Title: Rotate brackets until they're balanced
Take the string of brackets `]][][[`. When you rotate it to the right once, you get `[]][][`. If you rotate it again, you get `[[]][]`. All brackets in this string are balanced.

**The Task:**

Your program (or function) will be given a string of brackets, represented in any reasonable format (including using other things in place of the brackets, like `-1` and `1`). The numbers of opening and closing brackets will always be equal, so `[` or `][]` won't be given as inputs.

Output should be a rotation of those brackets which is balanced. You can check this by repeatedly removing pairs of brackets (`[]`). With a balanced string of brackets, none will be left over.

Rotating a string to the right involves taking the last character, and moving it to the beginning. For example, `01234567` rotated right 3 times would be `56701234`. The direction of rotation doesn't matter, but no brackets should be added, discarded, mirrored, etc. If multiple solutions are possible, such as `[][[]]` or `[[]][]`, you can return any of them.

**Test Cases:**

```
[]          ->  []
]][[        ->  [[]]
[][]][      ->  [[][]]
][][[]      ->  [[]][] OR [][[]]
[[[][][]]]  ->  [[[][][]]]
]]][][][[[  ->  [[[]]][][] OR [][[[]]][] OR [][][[[]]]

```

**Other:**

This is , so shortest answer in bytes per language wins!

# Answer
> 17 votes
# Husk, ~~7~~ 5 bytes

```
ṙ¹η◄∫

```

Try it online!

No loops, no recursion, just a straightforward simple operation. Encodes `[` as `1` and `]` as `-1`.

```
ṙ¹η◄∫
ṙ¹       Rotate the list left by
  η        the (1-based) index
   ◄         of the minimum
    ∫      in the list of cumulative sums

```

This comes from observing that the list of cumulative sums will have a minimum at the point where the most closed brackets are preceding open brackets. By moving all the previous brackets to the end, we can guarantee that there won't be any prefix containing more closed than open brackets.

---

## Previous answer, 7 bytes

```
Ωȯ¬▼∫ṙ1

```

Try it online!

Encodes `[` as `1` and `]` as `-1`, following HyperNeutrino's idea to use the cumulative sum, but then uses an additional observation:

Since we are working with an equal number of open and closed brackets, the total sum will always be `0`. If at any point the string is unbalanced, the cumulative sum at that point will be negative. From this, we can say that a string will be balanced if the minimum of its cumulative sum is exactly `0`.

```
Ω(¬▼∫)ṙ1
      ṙ1    Rotate by 1
Ω           until
   ▼         the minimum
    ∫        of the cumulative sums
  ¬          is 0

```

# Answer
> 11 votes
# Raku, ~~42~~ 34 bytes

```
{({S/.//~$/}...{try !.EVAL}).tail}

```

Try it online!

In Raku, a set of balanced square brackets is entirely valid syntax, so we can simply rotate the string until it `EVAL`s successfully, and take the last element.

### Explanation

```
{                                }  # Anonymous codeblock taking a string
  {S/.//   }                        # Remove the first character
        ~$/                         # And add it to the end
 (          ...            )        # Repeat until
               {try !.EVAL}            # The program can be eval'd
                                       # This returns ![] (true) if successful
                            .tail   # Return the last element

```

I thought this 31 byte program using the `-p` flag would work, but either TIO is too outdated or Raku has some sort of weird behaviour about `until`/`while` and `$_`. Until I can test it using the latest version, you can check it like so.

# Answer
> 10 votes
# Jelly, 4 bytes

```
ÄMṙ@

```

Try it online!

Similar approach to Leo's answer, give that an upvote!

Uses `-1` and `1` for `[` and `]` and returns all valid rotations

By swapping the signs from Leo's approach, we can operate on the maximal elements, rather than minimal, as Jelly has a builtin `M` to return the indices of maximal elements, thus saving a byte

## How it works

```
ÄMṙ@ - Main link. Takes a list of 1 and -1, A
Ä    - Take the cumulative sums
 M   - Yield the indices of the maximal elements
  ṙ@ - Rotate A that many times for each index

```

# Answer
> 9 votes
# Python 2, ~~74~~ ~~72~~ 69 bytes

```
def f(s):
 try:exec s.replace(')','),');print s
 except:f(s[1:]+s[0])

```

Try it online!

Tried a similar approach to *Jo King*'s Raku answer by evaluating the bracket string, only difference being an added `,` after every `)` so that the expression is valid.

Takes `(` and `)` instead of `[` and `]`.

*-2 bytes thanks to Sisyphus, -3 bytes thanks to dingledooper*

51 bytes if it's allowed to take ( and ), instead of ( and )

# Answer
> 9 votes
# Haskell, 37 bytes

```
until(all(>0).scanl(+)1)$drop<>take$1

```

Try it online!

*Saved 2 bytes using `<>`.*

Takes in a list of 1's and -1's. Actually pretty readable:

```
until            until
 (all(>0).       we get all positive values from
  scanl(+)1)     the cumulative sums of the list starting from 1,
 $drop<>take     rotate the list
 $1              by 1

```

The `drop<>take` rotates by using `<>` to concatenate the list with elements `drop`ped from the start and the list with that many elements `take`n from the start. The `(<>)` is imported in the TIO link but is available in base starting with 8.4.1; see this tip. We could also do `tail<>take 1` for the same length.

# Answer
> 9 votes
# APL (Dyalog Unicode), 10 bytes (SBCS)

This algorithm.

Anonymous prefix lambda, taking `-1` for `[` and `1` for `]`.

```
{⍵⌽⍨⊃⍒+\⍵}

```

Try it online! (This template)

`{``}` "dfn"; argument is :

`+\⍵` cumulative sum of the argument

indices that would sort that descending (i.e. index of the largest, index of the next-largest, etc.)

the first of that (i.e. the index of the largest)

`⍵⌽⍨` use that to rotate the argument to the left

# Answer
> 8 votes
# Jelly, 8 bytes

```
ṙJÄ-eƊÐḟ

```

Try it online!

-2 bytes thanks to ChartZ Belatedly + 1 byte saved from being allowed to return all valid configurations instead of just one

## Explanation

```
ṙJÄ-eƊÐḟ  Main Link
ṙ         Rotate by
 J        [1, 2, ..., len(input)]
      Ðḟ  Filter: keep all elements where the following is falsy (in this case, a list of all zeroes):
  Ä       Cumulative Sum
    e     equal to (vectorize)
   -      -1

```

Basically, keep all arrangements where the cumulative sum is never equal to -1 (clever observation from ChartZ that since the cumsum changes by 1 each time and starts at 0, if any value is negative, then there must be a -1 somewhere, so rather than doing `<0$` we can do `-e`. and then also that the filter quick accepts a list of zeroes as falsy so I don't have to use the `any` atom)

# Answer
> 8 votes
# Python 3.8, 57 bytes

```
f=lambda s,t=1:s*all((t:=t+n)for n in s)or f(s[1:]+s[:1])

```

Try it online!

Takes in a list of 1's and -1's.

# Answer
> 7 votes
# APL (Dyalog Unicode), 11 bytes

```
(⊢⌽⍨1∊+\)⍣≡

```

Try it online!

An APL port of Jonah's golfed answer, which in turn uses Leo's observation. Like Jonah's, the input is `-1` for `[` and `1` for `]`.

### How it works

```
(⊢⌽⍨1∊+\)⍣≡  ⍝ Input: a vector of -1s and 1s, -1 for open and 1 for close
(...)⍣≡  ⍝ Repeat until it does not change...
1∊+\     ⍝   1 if cumulative sum has a 1, 0 otherwise
⊢⌽⍨      ⍝   Rotate left ^ times (so it stops when the above result is zero)

```

# Answer
> 6 votes
# , 40 29 19 18 15 14 13 bytes

```
|.~1+0{&\:+/\

```

Try it online!

-11 after applying HyperNeutrino's scan sum idea

-10 after reading Leo's comment to HyperNeutrino: `while(any of the cumulative sum is negative)(rotate by 1)`

-3 thanks to a clever observation by Bubbler

Takes input as a list of integers, where `[ = _1` and `] = 1` -- reversing the more natural order saves 1 byte.

## how

* `|.~` Rotate by...
* `1+` 1 plus...
* `0{` the first element of...
* `\:` the grade down of...
* `+/\` the scan sum.

That is, take the index of the max element of the scan sum, add one to it, and rotate by that amount.

# Answer
> 6 votes
# Perl 5, 30 bytes

```
$_=chop.$_ while s/<(?R)*>//gr

```

Try it online!

Uses `<>` as the bracket delimiters.

The regex `s/<(?R)*>//gr` recursively substitutes bracket patterns with the empty string, and instead of mutating the string returns the final value. If this is empty, then all our brackets are fully matched and since the empty string is falsy, the loop stops. Else we rotate the string one using the construction `$_=chop.$_`.

-1 thanks to Dom Hastings by replacing the ugly `s/.//,$_.=$&` with the much more elegant `$_=chop.$_`.

# Answer
> 6 votes
# Scratch 3.0, 49 blocks/407 bytes

As SB Syntax:

```
define C
set[T v]to(0
set[i v]to(1
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1
define(s
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v]
set[i v]to((i)+(1
end
C
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v]
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C
end
say(S

```

Because rotating a string in Scratch/bracket matching is a really good idea. Use `a` for opening brackets and `b` for closing brackets.

## Explained

```
define C -- Helper function used for checking if the brackets are balanced
set[T v]to(0
set[i v]to(1 --- T = running tally, i = string index, Y = return value
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else                 ---- Opening brackets (a) increment the tally by 1. Closing brackets (b) decrement the tally by 1. If the brackets are balanced, this tally will never go below 0, as the brackets will cancel each other out
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1

define(s --- Main function
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v] --- Place every character of the input into a list
set[i v]to((i)+(1
end
C ---- Check if the inital input is balanced
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v]  --- Rotate the string once
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C   ---------- And check each rotation
end
say(S

```

# Answer
> 5 votes
# JavaScript (Node.js), 53 bytes

```
f=a=>([c,...r]=a).some(v=>(c+=v)>=0)?f([...r,a[0]]):a

```

Try it online!

Input array of \\$\pm 1\\$, output rotated array.

Thanks user81655 for -1 byte.

# Answer
> 5 votes
# Javascript, 52 bytes

(Sorry if i formatted my answer wrong, i'm brand new here.)

## Golf version

```
a=>{while(t=0,a.some(v=>(t+=v)<0))a.push(a.shift())}

```

## More readable version (and you can try it out)

```
function rotateArrayUntilBalanced(array) {
  var total; // Create a total variable
  while (total=0,array.some(value => (total += value) < 0)) { // This tests if the array is still unbalanced
    array.push(array.shift()); // Shift array right
  }
}

button.onclick = function () {
  const array = input.value.split('').map(value => (value == '[' ? 1 : -1));
  rotateArrayUntilBalanced(array);
  resultArea.innerText = array.map(value => (value == 1 ? '[' : ']')).join('');
}
```

```
<input id="input" placeholder="brackets go here">
<button id="button">Go</button>
<div id="resultArea"></div>
```

# Answer
> 4 votes
# , 80 bytes

```
function(x){while(min(cumsum(92-(y=utf8ToInt(x)))))x=intToUtf8(c(y[-1],y[1]));x}

```

Try it online!

Input is string of square-brackets.
Alternatively, a port of Leo's Husk answer using a vector of `1`s & `-1`s as input is only 48 bytes.

# Answer
> 3 votes
# Python 3, ~~74~~ 72 bytes

```
f=lambda a:min(sum(a[:i])for i in range(len(a)))<0and f([a.pop()]+a)or a

```

Try it online!

Takes input as a list of 1s and -1s, with 1 denoting `[` and -1 denoting `]`.

For a valid bracket sequence, no prefix of the array will have a sum less than 0, so if the current array is not a valid bracket sequence, rotate it by 1 and try again.

*-2 bytes thanks to tsh*

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

```
a=>eval("try{Function(a.replace(/]/g,'-1]'));a}catch{f(a.slice(1)+a[0])}")

```

Try it online!

Convert each `]` to `-1]`, and try to check if there are any syntax error...

This is ES2019.

# Answer
> 3 votes
# Python 3, 63 bytes

```
lambda a:min((sum(a[:i]),a[i:]+a[:i])for i in range(len(a)))[1]

```

Try it online!

---

# JavaScript (Node.js), 76 bytes

```
a=>a.map(v=>(++i,c+=v)<m?0:o=[...a.slice(i),...a.slice(0,i,m=c)],i=c=m=0)&&o

```

Try it online!

Input an array of \\$\pm 1\\$.

Count each `[` as \\$-1\\$, each `]` as \\$+1\\$. Find out the position \\$p\\$ where \\$\sum\_{i=0}^{p}a\_i\\$ has max value. And rotate it there. I believe this approach may be golfed more bytes, but I didn't find out an obvious way.

# Answer
> 3 votes
# Red, 50 bytes

```
func[s][while[error? try[load s]][move s tail s]s]

```

Try it online!

### Explanation

Red uses brackets for its `block!` datatype so every set of balanced brackets is a valid value. That's why I'm trying to load the string holding the brackets (that is to convert the string to a Red value) and if this throws an error, I move the leading character of the string at the tail.

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

*-2 thanks to @Command Master.*

```
ηOWk>._

```

Try it online! Takes input as a list, with `1` for `[` and `-1` for `]`.

```
ηOWk>._  # full program
     ._  # rotate...
         # implicit input...
     ._  # left...
    >    # 1...
   k     # -based index of...
  W      # maximum...
η        # cumulative...
 O       # sum...
η        # of...
         # implicit input...
   k     # in...
η        # cumulative...
 O       # sums...
η        # of...
         # implicit input...
     ._  # times
         # implicit output

```

`>._` can also be `._À` with no change in functionality.

As a bonus, this works too!

```
ηOWk>

._.

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~110~~ 108 bytes

```
x=>{for(s=x,i=0;++i<x.length;s=s.slice(1)+s[0])for(y=0,h=s;++y<s.length;h=h.replace('[]',''))if(!h)return s}

```

Try it online!

This was very tricky, but I managed to abuse for loops a lot.

Explained:

```
x=>{                      // declare function
  for(                    //repeat:
    s=x,i=0;              //initiate string and looper to 0
    ++i<x.length;         //repeat while i+1 is less than string length, and increment i at the same time
    s=s.slice(1)+s[0]     // loop string along by 1
  )
    for(                  //repeat:
      y=0,h=s;            //initiate looper, and string to use to check if matching
      ++y<s.length;       //repeat while incremented y is less than string length (since there are only so many brackets)
      h=h.replace('[]','')// remove a single occurrence of [] from h - if this is repeated enough and brackets match, it will eventually be empty.
)
if(!h)return s           // if h is an empty string, this means s's brackets match, so return s. No point in dealing with invalid input since it will always be valid.
}

```

# Answer
> 2 votes
# Ruby, 47 bytes

```
->s{s.rotate (0..s.size).min_by{|r|s[0,r].sum}}

```

Try it online!

# Answer
> 2 votes
# JavaScript, 56 bytes

```
q=>q.map(async _=>q.push(q.shift())|eval(q+'')|alert(q))

```

Try it online!

# Answer
> 2 votes
# K (Kona), 13 bytes

```
{(1+*>+\x)!x}

```

Try it online!

Uses -1 for \[ and 1 for \].

A port of Adám's APL answer

# Answer
> 2 votes
# Retina 0.8.2, 28 bytes

```
(.*?)(((<)|(?<-4>>))+)$
$2$1

```

Try it online! Takes input as a string of `<`s and `>`s but link includes test suite which maps `[` and `]` for convenience. Explanation: This is a fairly direct application of .NET balancing groups. The `<` character is captured into group `$4`, which works like a stack. Meanwhile, `>` characters can only be matched by popping `<`s from the `$4` stack. This ensures that we take the first suffix of the input that does not contain a mismatched `>`. (It can of course have a mismatched `<` but that will be matched by a `>` in the prefix.) It then remains to exchange the prefix with the suffix.

# Answer
> 2 votes
# PHP \< 7 -F, 59 bytes

```
for($a=$argn;eval($a)!==null;)$a=substr($a,1).$a[0];echo$a;

```

Try it online! (not working, PHP 7)

Try with onlinephpfunctions (working PHP 5.6)

Inspired by Jo King's answer. Works with `{}` braces instead of square ones.

From the docs:

> eval() returns null unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned false and execution of the following code continued normally.

# Answer
> 2 votes
# PowerShell, 89 bytes

This solution uses parenthesis rather than brackets.

```
for($n=$args){try{$n-replace"\(",",@("|iex *>0;break}catch{$n=-join$n[1..$n.Length+0]}}$n

```

Try it online!

## Bonus PowerShell, Regex-Based 129 127 bytes

Sure, the other way is shorter, but how often do I get a chance to use my balanced-bracket-matching regex?? Almost never!

```
for($n=$args;!($n-match'((\[(?=[^\]]*(?<s>\]))|\k<s>(?<-s>))+?(?(s)(?!)))*'-and$n-eq$Matches[0])){$n=-join$n[1..$n.Length+0]}$n

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~87~~ 86 bytes

Inspired by Zaelin Goodman

```
param($n)$n|% t*y|%{($n=($n|% S*g 1)+$n[0])}|?{try{$_-replace'\(',',(0'|iex;1}catch{}}

```

Try it online!

The script returns all solutions.

# Answer
> 2 votes
# Vyxal, 8 bytes

```
{:k[øo|Ǔ

```

Try it Online!

Takes as a string of `[]`.

```
{        # While...
    øo   # Removing until no change...
  k[     # The string `[]`
 :       # From the top of stack
    øo   # Eventually yields a truthy value (i.e. non-balanced)
      |Ǔ # Rotate left.

```

# Answer
> 1 votes
# Python 2, 147 bytes

```
def f(u):
 k=set()
 for x in permutations(u):
  s=''.join(x)
  try:eval(s)
  except:pass
  else:k.add(s)
 print "\n".join(k)
from itertools import*

```

Try it online!

Slow, permutation based approach

# Answer
> 1 votes
# Charcoal, 25 bytes

```
≔Ｅθ⁻№…θκ[№…θκ]η⭆θ§θ⁺κ⌕η⌊η

```

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

```
≔Ｅθ⁻№…θκ[№…θκ]η

```

Calculate the imbalance between `[`s and `]`s for every prefix.

```
⭆θ§θ⁺κ⌕η⌊η

```

Switch the prefix with the greatest imbalance with its suffix.

# Answer
> 1 votes
# Excel, 131 bytes

```
=LET(s,LEN(A1),x,SEQUENCE(s),y,INDEX(SORTBY(MOD(x,s),MMULT((x>=TRANSPOSE(x))*1,(MID(A1,x,1)="[")*2-1)),1),MID(A1,y+1,s)&LEFT(A1,y))

```

Converts brackets to 1, -1; finds the minimum cumulative sum y; then moves the first y characters to the end.

# Answer
> 1 votes
# Python 3, 123 bytes

`[n:=range(l:=len(s)),next(r for i in n if [r:=(2*s)[i:i+l],min(sum("]-[".index(c)-1 for c in r[:p]) for p in n)][1]>=0)][1]`

**Takes in string of square brackets. Should return first valid rotation:**

```
>>> s="]][][["
>>> [n:=range(l:=len(s)),next(r for i in n if [r:=(2*s)[i:i+l],min(sum("]-[".index(c)-1 for c in r[:p]) for p in n)][1]>=0)][1]
'[][[]]'

```

# Answer
> 1 votes
# Japt v2.0a0, ~~11~~ 8 bytes

Uses `1` for `[` & `0` for `]`.

```
ÈeA}f@éY

```

Try it \- header converts input from brackets and footer converts back to brackets.

```
ÈeA}f@éY     :Implicit input of string U
È            :Left function taking a string as argument
 e           :Recursively replace
  A          : "10"
   }         :End function
    f        :Return the first result of the right function that returns falsey (empty string) when passed through the left function
     @       :Right function with argument Y, 0-based Iteration index
      éY     :  Rotate U right Y times

```

---
Tags: code-golf, string, balanced-string
---


# Question
Title: Give the minimum Levenshtein distance to a string that matches the regex
Your task, at the moment that you choose to accept it, is to write a program that, when given a string and a PCRE-regex, calculates the minimum Levenshtein distance to another string that matches the regex (fully). All strings, as well as the regexes, should be in the Latin-1 character set.

This is `code-golf`, so the shortest program wins.

The Levenshtein distance (or edit distance) between two strings is the *closeness* of two strings, measured in operations needed to go from one string to another. One operation is one insertion, one deletion, or one substitution.

# Examples

`a, ab+ -> 1` because `ab` matches `ab+` and `levenshtein(a, ab) = 1`

`aaa, .* -> 0` because `aaa` matches

`aaaa, ab+a -> 2` because `aba` matches and `levenshtein(aaaa, aba) = 2`

`abcde, a.?b?.?a -> 2` because `abca` matches and `levenshtein(abcde, abca) = 2`

# Answer
> 3 votes
# PHP, 114 bytes

```
for($t=a,$r=INF;$c++<1e8;$t++)preg_match("/^$argv[2]$/",$t)&&($r>$l=levenshtein($argv[1],$t))?$r=$l+$c=0:0;echo$r;

```

Try it online!

This works with a smaller alphabet and some caveats, but passes the test cases:

* current version only works with lowercase letters (will try to improve this point)
* works by bruteforcing all strings using php strings increment
* uses a counter: the result is output if no smaller levenshtein value is found for a matching string after 100000000 (1e8) string increments (this limit was arbitrarily set to have a result in TIO, as 1e9 times out - can be set up to 9e9 with same byte count)
* following these points, current version will not be able to work if the input string is more than 100000000 (or up to 9e9) string increments from "a"

# Answer
> 3 votes
# Crystal, 129 bytes

```
require"levenshtein"
def f(s,r,d=1/0,a="`")while(a=a.succ).size-s.size<d
d=[d,Levenshtein.distance s,a].min if a[r]?==a
end
d
end

```

Try it online!

This fulfills the task if support for lowercase alphabet is enough. Theoretically, this shouldn't have an upper limit on length - the bruteforcing loop stops when the current test string `a` becomes so long that its Levenshtein distance from input `s` can never be smaller than the currently found minimal distance `d`. However, in practice, even the last test case is too big for TIO.

---
Tags: code-golf, string, regular-expression, edit-distance
---


title: Three other numbers

text:
# Question
Title: Three other numbers
Given three distinct numbers from \\$1\\$ to \\$7\\$, output three other distinct numbers from \\$1\\$ to \\$7\\$, that is having no numbers in common with the original numbers. Your code must produce a different output set for each possible input set. That is, no two inputs can produce the same output, treating both as unordered sets. Other than that, you can implement whatever mapping you want.

More mathematically, you're asked to give a bijection (one-to-one function) \\$f:S \to S\\$ where \\$S\\$ consists of three-element subsets of \\$\\{1,2,3,4,5,6,7\\}\\$, such that \\$f(s) \cap s = \emptyset\\$ for every \\$s\in S\\$. As a bijection, this mapping has to be invertible, though you don't have to provide the inverse function in your code.

Here are the 35 possible triples (written space-separated).

**I/O**

The format of the three-element sets is flexible. You can take the inputs in sorted order as three numbers or a three-element list/array/tuple, or as a set. You may not, however, require ordered inputs in a specific order other than sorted. You may zero index.

You may also use a sequence of seven bits of which three are on. This seven-bit sequence can also be represented as as a decimal number, byte, or character.

Output can be given in any of these formats, with the further allowance that ordered outputs don't have to be sorted.

# Answer
# Python 3, 43 bytes

```
lambda s:([*{*range(7)}-s]*4)[-sum(s):][:3]

```

**Try it online!**
> 14 votes

# Answer
# Python 3, 53 bytes

```
def f(b):c=[*{*range(7)}-b];del c[-sum(b)%4];return c

```

Try it online!

-3 bytes thanks to FryAmTheEggman
-4 bytes by zero-indexing
-1 byte thanks to xnor
> 13 votes

# Answer
# Jelly,  ~~9 8~~  7 bytes

```
7RṚḟṙSḊ

```

A monadic Link accepting a list of the three numbers, from \\$\[1,7\]\\$, in sorted order which yields a list of other numbers, from \\$\[1,7\]\\$, not necessarily sorted.

**Try it online!** Or see all 35 (I sorted the resulting values for easier comparison).

### How?

```
7RṚḟṙSḊ - Link: list A                   e.g.  [2,4,7]
7R      - seven range                          [1,2,3,4,5,6,7]
  Ṛ     - reverse                              [7,6,5,4,3,2,1]
   ḟ    - filter discard (A) -> B              [6,5,3,1]
     S  - sum (A)                              13
    ṙ   - rotate (B) left by (that)            [5,3,1,6]
      Ḋ - remove the leftmost                  [3,1,6]

```
> 8 votes

# Answer
# , ~~33~~ 31 bytes

*Edit: -2 bytes by using modulo `-4` (which returns the negative of modulo `4`)*

```
(1:7)[v<--scan()][sum(v)%%-4-1]

```

Try it online!

Finds the 4 digits in 1..7 that aren't in the input, and excludes the one corresponding to the input sum (wrapping around).

TIO link tests that outputs are unique for each input, and shows output for every input.

```
(1:7)                   # vector of digits 1..7
     [          ]       # select elements
         -scan()        # excluding (negative indexes) input
      v<-               # and define v as (negative) input
                        # (so up to here we have the 4 elements that aren't in the input)
     [              ]   # from these, select elements
      -                 # excluding (negative index)
       (sum(v)%%4+1)    # the sum of input, modulo 4, plus 1

```
> 7 votes

# Answer
# Japt, 14 bytes

As previously advertised, I'm a wee bit tipsy so this could well be wrong and, even if right, could probably be golfed a little.

```
7õ kU kÏ¶UxÍu4

```

Try it or view (what I think is) the proof
> 5 votes

# Answer
# Charcoal, ~~39~~ ~~38~~ ~~34~~ 32 bytes

```
ＮθＩ⁻¹²⁷⁺θＸ²⊟Φ⁷№ＥTXdhp﹪×℅λＸ²ι¹²⁷θ

```

Try it online! Link is to verbose version of code. I/O is as a 7-bit integer `7..112`. Explanation: The ordinals of the string `TXdhp` have five bit patterns which I have arbitrarily chosen to be such that the result excludes `1`. They are then cyclically rotated until one matches the input, at which point I have determined the excluded bit. This bit is then added to the original input, and finally the difference between `127` and the sum is printed.

```
Ｎθ                                  Cast input to integer
             ⁷                      Literal 7
            Φ                       Filter on implicit range
                TXdhp               Literal string `TXdhp`
               Ｅ                    Map over characters
                        λ           Current character
                       ℅            Ordinal
                      ×             Multiplied by
                          ²         Literal 2
                         Ｘ          Raised to power
                           ι        Outer index
                     ﹪              Modulo
                            ¹²⁷     Literal 127
              №                     Count (i.e. contains)
                               θ    Input
           ⊟                        Pop matching value
          ²                         Literal 2
         Ｘ                          Raised to that power
       ⁺                            Added to
        θ                           Input
   ⁻                                Subtracted from
    ¹²⁷                             Literal 127
  Ｉ                                 Cast to string
                                    Implicitly print

```

I arbitrarily chose the following five bit patterns to exclude `1` but any five even cyclically distinct patterns would work.

```
T   1010100
X   1011000
d   1100100
h   1101000
p   1110000

```
> 5 votes

# Answer
# JavaScript (ES6),  ~~66~~  65 bytes

Takes input as a 3-digit string. Returns a string in the same format.

```
f=(n,k=i=0)=>++k<8?(~n.search(k)||n*43%399%4==i++?'':k)+f(n,k):''

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
7LsKsO(._¨

```

**Try it online!**

### How?

```
7LsKsO(._¨ - (push the input)      e.g.: [2,4,7]
7          - push 7                      7,[2,4,7]
 L         - range                       [1,2,3,4,5,6,7],[2,4,7]
  s        - swap top two of the stack   [2,4,7],[1,2,3,4,5,6,7]
   K       - push a without bs           [1,3,5,6]
    s      - swap top two of the stack   [2,4,7],[1,3,5,6]  (implicit input swapped in)
     O     - sum                         13,[1,3,5,6]
      (    - negate                      -13,[1,3,5,6]
       ._  - rotate a left by b          [6,1,3,5]
         ¨ - remove rightmost            [6,1,3]
           - implicit print top of stack [6,1,3]

```
> 4 votes

# Answer
# C (gcc), ~~84~~ 83 bytes

Saved a whopping ~~16~~ ~~19~~ 23 bytes thanks to the man himself ceilingcat!!!
Saved a byte thanks to Neil!!!

```
p;i;f(m){for(p=i=0;(L"᰸ᨴᘬᤲᔪ"[p]>>i%7&m)-m;p+=++i%7<1);p=(64>>i%7)+m^127;}

```

Try it online!

Takes input as \\$3\\$ bits set in the least-significant-\\$7\\$-bits of an `int` and returns the three other numbers likewise.

### Explanation (before some golfs)

```
f(m){                                  // function taking an integer with
                                       // 3 bits set in its 7 lsb
                                       // representing the 3 input numbers
     for(                              // loop over
         p=L"ᔪᘬᤲᨴ᰸"                     // a sequence of 5 int values:
                                       //   5418,5676,6450,6708,7224
                                       // that are the 5 unique patterns of
                                       // 3 set bits per 7 bits shifted and
                                       // repeated over 13 bits so that their
                                       // 7th bit is unset:
                                       //   5418 = 1010100101010
                                       //   5676 = 1011000101100
                                       //   6450 = 1100100110010
                                       //   6708 = 1101000110100
                                       //   7224 = 1110000111000
                    ;;++p)             // no need to test for stopping
                                       // since we must match one
       for(i=7;i--;)                   // loop over shift values from 6 to 0
         if((*p>>6-i&m)==m)            // if a shifted 7-bit slice of one of
                                       // our patterns matches m we've found
                                       // the correct bit to exclude from m's
                                       // 4 unset bits
            return(1<<i)+m^127;        // add that bit to m and flip the 7
                                       // lsb so the 3 other unset bits are
                                       // now set to represent the 3 return
                                       // values
 }

```
> 4 votes

# Answer
# Ruby, 38 bytes

```
->s{n=s.sum;(([*1..7]-s)*9)[-n..-n+2]}

```

Try it online!

Stealing Eric's answer which based on Jonathan's answer. I would've commented to Eric, but i do not have enough reputation.

The actual difference: Using a range to get the three elemented slice.
> 4 votes

# Answer
# Pyth, 10 bytes

```
>3-%R7t*5s

```

Takes input as a 3-element list of {0, …, 6}.

Try it online! Or see all 35 inputs.

### How it works

```
         sQ   sum of input
       *5     multiply by 5
      t       subtract 1
   %R7        take each element of [0, that) mod 7
  -        Q  remove elements present in input
>3            last 3 elements

```

It’s helpful to preserve symmetry under rotations modulo 7, since that leaves just five equivalence classes to consider. A good starting point is the “average” \\$\frac{x + y + z}{3}\\$, where division by 3 is the same as multiplication by 5 modulo 7. It happens that if we start walking down from the average minus 2, taking the first three numbers that aren’t in the input set, the five equivalence classes are conveniently mapped one-to-one:

* {0, 1, 6} ↦ {3, 4, 5} = {0, 1, 6} + 4
* {0, 2, 5} ↦ {1, 3, 4} = {3, 5, 6} + 5
* {0, 3, 4} ↦ {1, 2, 5} = {0, 3, 4} + 5
* {1, 2, 4} ↦ {0, 3, 5} = {0, 2, 5} + 5
* {3, 5, 6} ↦ {1, 2, 4} = {1, 2, 4} + 0
> 3 votes

# Answer
# Husk, 9 bytes

```
hṙ_Σ¹`-ḣ7

```

Try it online!
> 2 votes

# Answer
# Ruby, 40 bytes

```
->s{(([*1..7]-s)*9).last(s.sum).first 3}

```

Try it online!

Ruby port of Jonathan's answer.
> 2 votes

# Answer
# Perl 5, 49 bytes

```
sub{@c=grep!/[@_]/,0..6;splice@c,-sum(@_)%4,1;@c}

```

Try it online!

Just a translation of the python answer from HyperNeutrino.
> 2 votes

# Answer
# Scala, 64 bytes

```
b=>1.to(7).diff(b).zipWithIndex.filter(_._2!=b.sum*3%4)map(_._1)

```

Try it online!
> 2 votes

# Answer
# Vyxal, 11 bytes

```
7ɾ$⊍?∑N$ǔṫ$

```

Try it Online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 13 bytesSBCS

```
1∘↓+/⌽(⌽⍳7)∘~

```

Try it online!

This is an atop of a train

```
1∘↓+/⌽(⌽⍳7)∘~
      (⌽⍳7)∘~ ⍝ Right side of the atop
        ⍳7    ⍝ Range
       ⌽     ⍝ Reverse
           ∘  ⍝ Composed with...
            ~ ⍝ ...without (to remove our arguments)
     ⌽        ⍝ Rotated by...
   +/         ⍝ ...the sum of the arguments
1∘↓           ⍝ Left side of the atop
1∘↓           ⍝ Drop leftmost (drop curried with 1)

```
> 1 votes

# Answer
# PowerShell, ~~35~~ 63 bytes

based on the hyper-neutrino♦'s solution

+28 bytes thanks @DLosc

```
param($a)$b=1..7|?{$_-notin$a}
$b|%{$s+=$_}
$b|?{$_-ne$b[$s%4]}

```

Try it online!
> 1 votes

# Answer
# Vyxal, 9 bytes

```
∑5*‹ʁ7%⊍Ḣ

```

Try it Online!

Porting Pyth saves two bytes.
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
7LIм{3.$IO(._Dg<£

```

Try it online!

It's a much longer version of the Jelly answer, so go upvote that too.
> 0 votes

# Answer
# APL+WIN, 20 bytes

Prompts for input of a vector of integers

```
3↑(-+/¯2↑n)⌽n←(⍳7)~⎕

```

Try it online! Thanks to Dyalog Classic
> 0 votes

---
Tags: code-golf, math, open-ended-function
---


title: Obfuscate my ><>

text:
# Question
Title: Obfuscate my ><>
\>\<\>, or Fish, is a two-dimensional esoteric programming language where the instruction pointer (IP) toroidally moves around the codebox, wrapping when it hits an edge.

\>\<\> has four basic movement instructions - `<`, `>`, `^`, and `v`, which respectively mean to change the IP's direction to left, right, up and down. It also has the termination instruction `;`, which halts the program.

For any program, some characters may never have the IP move through them. For example, with the program

```
> v

; <

```

The program starts at the `>`, changes direction at the `v` and `<`, and halts at the `;`. The squares marked with `#` are never passed through:

```
> v
##
; <

```

So if we wanted to obfuscate this program and make it harder to read, we could replace these with any printable ASCII characters and the program would still do exactly the same thing!

In this challenge, we will be working with a very limited set of \<\>\< - Just the four movement instructions, spaces, the terminator (`;`) and newlines.

Your challenge is to, when given a program in this subset of \>\<\> as input, output the same program with all characters that will never be passed through replaced with random printable ASCII characters - 0x20 to 0x7e. For each position, each printable ASCII character should have an equal chance of being printed, including \>\<\> instructions and spaces.

Note that this means replacing *all* characters that are never passed through, not just spaces.

You can assume that the \>\<\> program will always halt, and will always be a rectangle.

You may take input as a list of lines, a matrix of characters, ascii-art, etc.

The program will only ever contain said instructions.

The IP starts at 0,0, moving left to right.

# Scoring

This is , shortest wins!

# Testcases

In these testcases, `#` represent characters that should be replaced with random characters.

```
v;
> v
 ^< =>
v;#
> v
#^<

; v
  v
<<< =>
;##
###
###

> v
 ;
; < =>
> v
##
; <

>  v
v  >
> ^
  >; =>

>  v
v# >
> ^#
##>;

>v> ^
v<^v<
> v>; =>

>v> ^
v<###
> v#;

```

# Answer
# \>\<\>, 555 bytes

```
ffv   $@$f$+1~<
 $>i:1+?!v:a=?^}$:@@:@{@p$1+
@@:@(?$&$>~&l1=?v:
^}f-&0~~~~&<    >&1+$ff0       v
:@@=?v:@@=?^:@@=?v:@@=?v:@@=?vv>}$:@@:@{@g::0$-:@(?$~&">v<;^"&
v/~~&</     2~~~&/ 1~~&/  0~&/>~" "&>}$:@@:@{@0&-@p:&1$3=?v&:&1=?v$@&:&0=?+&:&2=?-$
v>~~~3>          >     >      !^  !0^!   <                >0$-   >+
>  :e=?v>:{:}=?v$>     :e=?v>:{{:@}}=?v$&^
^-1}:{~<^    f~< ^-1}}@:{{~<^       f~<
>$:{{:@}}=?v>$:@@:@4[1+r]g:0(?!v0$-o
^!}:{:$f+1~<^$oa;?=  >!   ]! o!0!
r v >l7=?v0           >   ~l]0$>$~[r
$>x0^>@:@0~(@:@)@@+?!^^
p >1^^@"~ "<
}{2*+l1= >?^

```

Try it online!

Note that there is a trailing space on line 11 (after `o!0!`).

\>\<\> programs can only access a stack of stacks for data storage, which would be difficult to use as a 2d array. Thus, this modifies the program grid to use as a 2d array, storing the input & tracing the path through it.

Additionally, the only source of randomness in \>\<\> is the `x` instruction, which sends the IP in one of 4 random directions. Printable ASCII has 95 (19 * 5) characters, which is not divisible by numbers less than 5. Thus, to generate the random characters, it generates 7 random bits, joins them into a number from 0 to 128, and then checks if the number is within printable ASCII. If not, it discards it, generates a new random number, and repeats until it is.
> 20 votes

# Answer
# Charcoal, ~~90~~ 55 bytes

```
ＷＳ⊞υιＰ⪫Ｅυ⭆ι‽γ¶≔¹ηＷ¬⁼;ψ«≔§§υⅉⅈψ≔∨⊕⌕>^<vψηη✳⊗⊖ηψＪ﹪ⅈＬθ﹪ⅉＬυ

```

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

```
ＷＳ⊞υι

```

Read the program.

```
Ｐ⪫Ｅυ⭆ι‽γ¶

```

Output a rectangle of random printable ASCII.

```
≔¹η

```

Start at the origin facing east.

```
Ｗ¬⁼;ψ«

```

Repeat until the end of the program is reached.

```
≔§§υⅉⅈψ

```

Get the current character of the program.

```
≔∨⊕⌕>^<vψηη

```

If the current character is a direction then update the direction variable.

```
✳⊗⊖ηψ

```

Replace the random character with the current character and update the position.

```
Ｊ﹪ⅈＬθ﹪ⅉＬυ

```

Wrap around the sides of the rectangle as necessary.
> 10 votes

# Answer
# , 120 bytes

```
(([:u:32+94?@$~#@[)`[`]})~($#:,@i.@$);/@-.[:{."2]($@[|"1{.@](+,:])(]0,~((,-)=i.2),~{:){~' v>^<'i.({~<@{.))^:a:0 0,:0 1"_

```

Try it online!

It's late, and this one kind of got away from me, but, what the hell, looks like it works. I have some ideas to improve it tomorrow.
> 6 votes

# Answer
# Python 3, ~~253~~ 212 bytes

Takes input as a character matrix.

```
from random import*
def f(g):
 r=x=y=a=0;b=1;N=[[chr(randint(32,126))for _ in t]for t in g]
 while';'!=r:N[y][x]=r=g[y][x];a,b=[0,1,0,2,-1,a,-1,0,1,2,0,b][ord(r)%9%6::6];x=(x+b)%len(g[0]);y=(y+a)%len(g)
 return N

```

Try it online!

**Commented:**

```
from random import*
def f(g):
  r=0    # last instruction
  x=y=0  # current position in the grid
  a=0    # y-direction
  b=1    # x-direction
  # grid of random characters of the same dimensions as g
  N=[[chr(randint(32,126))for _ in t]for t in g]

  # until the last instruction was a ;
  while';'!=r:
    # update instruction and random character
    N[y][x]=r=g[y][x]
    # update direction, ord(r)%9%6 maps
    # < -> 0, v -> 1, ^ -> 2, ^ -> 4, ' ' -> 5
    a,b=[0,1,0,2,-1,a,-1,0,1,2,0,b][ord(r)%9%6::6]
    # update position, modulo takes care of the wrapping
    x=(x+b)%len(g[0]); y=(y+a)%len(g)
  # return random matrix where visited indices are replaced with the program
  return N

```

Try it online!
> 6 votes

# Answer
# Jelly, ~~70~~ 59 bytes

```
O%19ịı*Ɱ6ḊḊŻƲÆiḞŻ¤4Ṭs2¤‘œị¥@ȯƭƒ+ḷƭⱮ⁸%⁹,ZẈW¤ʋƬḢ€‘ŒṬ¬aØṖX¤€€o

```

Try it online!

A link that is called as a monad with a list of Jelly strings and returns a list of Jelly strings.

Here’s a version that shows # in place of the random characters.

## Explanation (outdated)

Takes `[[pos_x, pos_y], [dir_x, dir_y]]` as its left argument and a converted grid as its right (see below) and returns an updated list of position and direction

```
   ¥1¦               | Do the following to the position component of the lost:
‘                    | - Add 1
 œị                  | - Multidimensional index into grid
      ȯ/             | Reduce using logical or
        ⁸            | Using the original left argument:
         +ṛƭ€        | - Add the new direction to the position, and append the new direction
             %       | Mod with:
              ⁹    ¤ | - The grid
               ,Z    | - Paired with its transpose
                 Ẉ   | - Lengths
                  W  | - Wrapped (which will mean only the position is affected)

```

```
“;>^<v”iⱮⱮ                                  | Positions of each character in the grid in ";>^<v"
          ‘                                 | Increase by 1
           ị          ¤                     | Index into:
            ı                               | - i
             *Ɱ4¤                           | - ** each of 1..4
                 Ż                          | - Prepend zero
                  Æi                        | - Convert from complex
                    Ḟ                       | - Floor
                     Ż                      | - Prepend zero
                           ¤                | Starting with:
                       4                    | - 4
                        Ṭ                   | - Untruthy ([0,0,0,1])
                         s2                 | - Split into lists length 2 ([[0,0],[0,1]])
                            çƬ              | Call the helper link with the grid as the right argument until no new value encountered
                              Ḣ€            | Head of each (i.e. positions)
                                ‘           | Add 1
                                 ŒṬ         | Multidimensional untruthy
                                   ¬        | Not
                                    aØṖX¤€€ | And with a list of lists of random printable characters for each original character in the grid
                                           o| Logical or with original grid

```
> 6 votes

# Answer
# , ~~217~~ ~~175~~ ~~178~~ ~~173~~ ~~155~~ 154 bytes

```
function(A,B=A,j=1:0,i=t(j+!j)){B[]=intToUtf8(runif(A,,95)+32,T);while(";"!=(B[i]=a=A[i]))i=(i-(j=switch(a,">"=1:0,"<"=1:2,v=0:1,"^"=2:1,j)))%%dim(A)+1;B}

```

Try it online!

Thanks to @Nick Kennedy for very nice golfs resulting in -42 bytes (!) and clarifying some issues with the OP.

-5 bytes inspired by @Neil's Charcoal answer, but as I understand this approach is also used in some other answers.

Thanks to @Dominic van Essen for -17 bytes.
> 5 votes

# Answer
# Excel VBA, 400 bytes

```
    Sub f()
    Set a=UsedRange
    m=a.Rows.Count
    n=a.Columns.Count
    r=1
    c=1
    Set u=[A1]
    While e=0
    Set x=Cells(r,c)
    Set u=Union(u,x)
    Select Case x
    Case">":s=0:d=1
    Case"<":s=0:d=-1
    Case"v":s=1:d=0
    Case"^":s=-1:d=0
    Case";":e=1
    End Select
    r=r+s
    c=c+d
    If r<1 Then r=m
    If r>m Then r=1
    If c<1 Then c=n
    If c>n Then c=1
    Wend
    For Each b In a.Cells
    If Intersect(b,u)Is Nothing Then b.Value=Chr(Int(113*Rnd+14))
    Next
    End Sub

```

Formatted code with comments explaining function:

```
    Sub f()

        Set a = UsedRange   'Save this here for shorter reference later
        m = a.Rows.Count    'Ditto
        n = a.Columns.Count 'Ditto
        r = 1               'Row
        c = 1               'Col
        Set u = [A1]        'Prime the collection with the first cell
        While e = 0
            ' Pick the cell we're going to examine and add it to the collection
            Set x = Cells(r, c)
            Set u = Union(u, x)

            ' Change the row / column shift if we hit a control character
            Select Case x
                Case ">": s = 0:  d = 1
                Case "<": s = 0:  d = -1
                Case "v": s = 1:  d = 0
                Case "^": s = -1: d = 0
                Case ";": e = 1   'Triggers the end of the While loop
            End Select

            ' Shift the row / cell and correct for edge (heh) cases
            r = r + s
            c = c + d
            If r < 1 Then r = m
            If r > m Then r = 1
            If c < 1 Then c = n
            If c > n Then c = 1
        Wend

        ' Loop through all the cells in the used range
        For Each b In a.Cells
            ' If that cell was not collected when moving through the program, fill it with a random character
            If Intersect(b, u) Is Nothing Then b.Value = Chr(Int(113 * Rnd + 14))
        Next

    End Sub

```

Input is one character per cell:

Output is editing in-place:
> 3 votes

# Answer
# JavaScript (Node.js),  ~~194~~  188 bytes

Expects and returns a matrix of characters.

```
m=>m.map((r,Y)=>r.map((C,X)=>(g=x=>(x%=W)-X|(y%=H)-Y?~(c="^<v> ".indexOf(m[y][x]))?g(x+(c<4?(v=--c%2,h=~-c%2):h)+W,y+=v+H):Buffer([Math.random()*95+32])+'':C)(W=m[0].length,y=H=m.length)))

```

Try it online!
> 2 votes

---
Tags: code-golf, grid, random, interpreter
---


title: Simulate a Game of Quagmire

text:
# Question
Title: Simulate a Game of Quagmire
# Background

Many moons ago, in a galaxy much like our own, a young BrainSteel attempted to invent a board game. He believed that he, too, could find an amazingly simple set of rules that would generate wonderfully strategic gameplay. He drew up the first set of rules--it looked promising. He played with his thoughts, and noticed a minor inconsistency here, or a slight balance issue there. One by one, the rules started piling up, until they were at best arbitrary. Try as he might, the beautiful simplicity of Checkers or Go failed to shine through. His final creation, one bad enough he would only refer to it when speaking in the 3rd person, was given the *temporary* name "Quagmire." While perhaps not a brilliant board game, it ought to be a fun code golf!

# The Rules of Quagmire

The game is played on an 8x8 board, and each player has 10 identical pieces. If player one has `O` pieces, and player 2 has `X` pieces, here is a portrayal of the game at the start (where `.` indicates a blank space):

```
 a b c d e f g h
+-+-+-+-+-+-+-+-+
|.|.|.|.|X|X|X|X| 8
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|X|X|X| 7
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|.|X|X| 6
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|.|.|X| 5
+-+-+-+-+-+-+-+-+
|O|.|.|.|.|.|.|.| 4
+-+-+-+-+-+-+-+-+
|O|O|.|.|.|.|.|.| 3
+-+-+-+-+-+-+-+-+
|O|O|O|.|.|.|.|.| 2
+-+-+-+-+-+-+-+-+
|O|O|O|O|.|.|.|.| 1
+-+-+-+-+-+-+-+-+

```

Note that every space on the grid can be named with a letter and number, e.g. there is an `O` character on `c2`.

Players take turns in an alternating fashion.

On a player's turn, they may move in two ways:

* The player may move any piece in a straight line vertically, horizontally, or diagonally at most until they meet either another wall or piece. e.g. `|X|.|.|O|.| => |.|.|X|O|.|` for one move of length 2 horizontally. Note that the `X` piece cannot move any farther right, because there is a piece in the way.
* The player may use a piece to jump over a **single, adjacent, and friendly** piece. Jumps, like ordinary moves, may be horizontal, vertical, or diagonal. Under *normal circumstances* an enemy piece may not be jumped. e.g. `|X|X|.| => |.|X|X|`

If a piece cannot move to any of its surrounding spaces, and at least one of those adjacent spaces is occupied by an enemy piece, that piece is said to be in a state of *Quagmire*. If a player ends his turn with a piece in Quagmire, they lose the game.

Now for the more arbitrary rules:

* The bottom left player goes first.
* Each player must make exactly one move per turn. (No pass!)
* A piece may not be moved twice in a row, **ever**. e.g. if, on the first turn, player one moves the piece on `c2`, he may not move the same piece on his following turn.
* If the player to move has one or more pieces in Quagmire which may move, they must move one of those pieces.
* A piece may jump an enemy piece in the same way that it jumps a friendly piece if and only if that enemy piece is part of a closed loop (which may or may not start and end at a wall) of pieces of one color, and that loop is impenetrable by normal moves. If a piece jumps in this way, it must jump from inside the loop to the outside, or vice versa. Since this rule is weird, here is an example board:

```

     a b c d e f g h
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|X|.|.|X| 8
    +-+-+-+-+-+-+-+-+
    |.|.|.|.|X|.|.|X| 7
    +-+-+-+-+-+-+-+-+
    |.|.|.|.|X|.|.|.| 6
    +-+-+-+-+-+-+-+-+
    |X|.|.|.|.|X|X|X| 5
    +-+-+-+-+-+-+-+-+
    |O|O|O|O|.|.|.|.| 4
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|X|.|.|.| 3
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|.|.|O|.| 2
    +-+-+-+-+-+-+-+-+
    |O|O|O|O|.|.|.|.| 1
    +-+-+-+-+-+-+-+-+

```

In this position, the `X` on `a5` may legally jump to `a3`. In contrast, the `O` on `d8` may NOT jump to `f8`, since the loop of `X` pieces is not fully closed -- the inside is accessible through the `e5` \- `g7` diagonal. Also, note that the 'X' on `e3` may not jump to `c5` because this jump does not cross from outside the loop to the inside.

# The Challenge

Your challenge is to allow two players at the same computer to play a game of Quagmire, adhering perfectly to the rules, against each other.

At every point in the game, your program should output the board as shown in the first example board, reflecting the current positions of all pieces on the board. You may choose any characters for the `O`, `X`, and `.` values, but the rest of the characters must be exactly as shown. **You should also display, in a reasonable manner, whose turn it is!**

# Input

On a players' turn, you should accept a string of at least 5 bytes in the form `X#<seperator>Y#`. You may make **reasonable** adjustment to this format to suit your programming language. You may also assume that the input, while not necessarily a legal move, will be formatted correctly (no numbers greater than 8, etc). Your program should evaluate whether or not a move from `X#` on the board to `Y#` is legal for this player. If it is legal, your program should make the move and output the next board accordingly. If it is not legal, your program should output some falsy value (`0` is perfectly reasonable--you do not need an explanation) and receive another input.

# Winning

A player wins when the other player fails to relieve one of his pieces from Quagmire. Alternatively, a player wins when it is their opponent's turn and their opponent has no legal moves. Note that the first win condition takes precedence over the second. If I leave a piece in Quagmire at the end of the turn and simultaneously leave my opponent with no legal moves, I still lose the game. If the game is over after a player's move, you should output the winning board, the winning player's piece character (e.g. 'X') and some truthy value (Again, `1` is sufficient). At this point, your program may either terminate or restart the game.

# Challenge Rules

# Answer
# Ruby 2.7, <sup>~~695...618~~</sup> 610 bytes

```
i=*0..7
t,*b={}
"?>=<765/.'".bytes{b[_1],b[~_1]=A=?X,E=?O}
loop{puts'
 '+[*?a..?h]*' ',a='+-'*8+?+,i.map{|j|"|#{b[8*~j,8].map{_1||?.}*?|}| #{8-j}
"+a}
eval"M,*m=->u,w=p,*s{Q=(0..8).map{c,r=u;z=c+8*r
#{$f='(v=c+=_1/3-1,r+=_1%3-1)-i==[]&&'}(k=#{$g='b[c+8*r]'}
w ?b[z]==A&&(t[A]!=z&&(#$f!#$g&&(k==A||k&&N[u]&N[v]==[])&&s<<u+v
c,r=u;s<<u+v while#$f!#$g);k):k!=E&&s<<v)};s}
N,*q=->o,n=M[o]{n==n|=n.flat_map{M[_1]}||redo;n}
i.product(i){#{h='M[_1,1];A,E=E,A;([p,A]&Q)[0]&&'}(p A;Z);m+=e=#{h}q+=e}
A,E=E,A
($><<A+?>;c,r,_,x,y=gets.bytes.map{~-_1%8})until[[c,r,x,y]]-(m[0]?q[0]?q:m:(p E;Z))==[]
#$g,b[t[A]=x+8*y]=p,A"}

```

Try it online! (620 bytes because the older Ruby on TIO doesn't support numbered block parameters.) A simple example game is included that illustrates most of Quagmire's rules. Just for clarity, the input is commented and invalid moves are indented.

Input is in the format `x# y#`, terminated either by newline or EOF. Any single byte is accepted as the separator. The input prompt is `O>` for player 1 and `X>` for player 2. (In an interactive terminal the input appears as it is typed, after the prompt.) The prompt is repeated until a valid move is entered, then the updated board is printed. When the game ends, the winning player's symbol is printed in double quotes; I like to imagine it is raising its arms in victory.

# Explanation

> While perhaps not a brilliant board game, it ought to be a fun code golf!

#### Steel your Brain

The first 3 lines perform initialisation. `i` is a fixed list of row/column numbers. The value of each square on the board (`O`, `X`, or `nil`) is stored in the (1D) array `b`. Empty squares, stored as `nil`, are replaced by `.` on output. The starting configuration is encoded by the 10-byte string `?>=<765/.'`, whose codepoints give the indices of squares containing X's. `t` is a hash that stores the index of the piece moved on each player's previous turn (this piece cannot be moved on the next turn). `A` and `E` store the 'active' and 'enemy' piece symbols and are interchanged each turn.

Being *constants* (uppercase names), `A` and `E` have global scope. Constants are abused throughout the program to avoid scoping issues that would arise with ordinary local variables. A side effect is that whenever a constant is reassigned, warnings are emitted to STDERR. (These warnings may be suppressed by calling Ruby with the `-W0` option.)

Now the main `loop` begins, running until one player wins. Following the 3 lines that display the board, the remainder of the program is enclosed in an `eval` string, which allows a few chunks of code (stored in the strings `$f`, `$g`, and `h`) to be recycled. The first 5 lines of this string contain the real meat of the program: the lambdas `M` and `N`.

#### Mary had a little lambda

Let's start with `N`. `N` finds the set of all squares that are *connected* to the square at co-ordinates `o` (co-ordinates are pairs of 0-indexed column and row numbers). Here, connected means that there is a path between all the squares that is not blocked by enemy pieces. Source and destination squares must be unconnected as a prerequisite for jumping an enemy piece. `N` fans out from the current square, adding its non-enemy neighbours (`n=M[o]`) and their neighbours (`n|=n.flat_map{M[_1]`) to the set `n` by calling `M` (see below). We `redo` this process, adding more neighbours of neighbours, until `n` no longer changes (i.e. until all connected squares have been found).

`M` probes the board around the square at co-ordinates `u`. Its exact behaviour is determined by the switch `w`, which takes a value of either `nil` (a.k.a. `p`) or `1`:

* When `w` is `nil`, `M` returns an array `s` of the co-ordinates of all neighbours (8-neighbourhood) of the square at `u` that do not contain enemy pieces (`k!=E`). Lambda `N` uses this information to find the set of all squares that are connected to the current square, as described above. The co-ordinates of each neighbour (column `c` and row `r`, stored as the pair `v`) are obtained by independently advancing `c` and `r` by -1, 0, or 1 (`(0..8).map...(v=c+=_1/3-1,r+=_1%3-1)`), ensuring that `c` and `r` both lie within the board (`(v=...)-i==[]`). This code for finding adjacent squares is required again later, so to save bytes it is stored as a string in `$f` and interpolated into the `eval` string. Similarly, the code that returns the value of the square at `v` is saved in `$g` (`$g='b[c+8*r]'`).
* When `w` equals `1` and the square at `u` contains one of the active player's pieces (`b[z]==A`), `M` does two things:

1. It returns an array `s` containing all possible moves for the active player originating from this square.
    2. It saves the values of all neighbouring squares in `Q`, which is used later to test for quagmire.

Moves are only allowed if the piece was not moved on the previous turn (`t[A]!=z`). For jumps, the destination square is found by advancing `c` and `r` in the same directions a second time (by interpolating `$f`) and testing whether this square is empty (`!#$g`). For a jump to be possible, there must either be an active piece to jump over (`k==A`) or, if an enemy piece is being jumped, the source and destination squares must be unconnected (`k&&N[u]&N[v]==[]`). For ordinary moves, `c` and `r` are reset (`c,r=u`) and then both variables are advanced in the same directions as before, one square at a time, until no further move along that path is possible (`while#$f!#$g`). Moves are saved (`s<<u+v`) in the format `[c,r,x,y]`, that is, the column and row numbers of the source square followed by the column and row numbers of the destination.

#### Into the quagmire

The last four lines of the program run the game according to the following steps:

1. Loop over all squares of the board by forming pairs of column and row numbers (`i.product(i)`).
2. For the current square, complete the following steps, all saved in `h`:

* Call `M` in move-finding mode (`M[_1,1]`). If the square contains an *enemy* piece, update `Q` with the values of the neighbouring squares. (Any possible moves for that piece are also returned, but we immediately discard them: it's not the opponent's turn to move, after all!)
    * Interchange the active and enemy pieces (`A,E=E,A`). The reason for interchanging players is that quagmire checks are performed twice per square, once (here in step 2) to find whether the opponent has left a piece in quagmire and again (in step 4) to find whether the active player has been quagmired by the opponent's previous move.
    * Test whether the current square contains a quagmired enemy piece (`([p,A]&Q)[0]`). `([p,A]&Q)[0]` is truthy only if there are no empty neighbours and at least one neighbour is an active piece.
3. If the current square contains a quagmired enemy piece then the game is won. Print the active player's symbol (`p A`) and terminate by throwing a tantrum (`Z` is not defined).
4. Repeat step 2, reading 'active' for 'enemy' and vice versa, but this time add all possible moves (neglecting quagmire for the moment) for the active player to `m` and keep a copy in `e` (`m+=e=#{h}`). If the current square contains a quagmired active piece then add `e` to `q` as well (`q+=e`).
5. Outside the loop, interchange the active/enemy pieces to advance the turn (`A,E=E,A`).
6. Finally it's time for some input!

* We now have two lists of moves for the active player: `m` contains all possible moves (neglecting quagmire) whereas `q` (a subset of `m`) contains possible moves by any quagmired pieces. `(m[0]?q[0]?q:m:(p E;Z))` decides which move list should be used. If `m` is empty (i.e. the active player has no possible moves) then the game is lost; print the opponent's symbol and terminate (`m[0]?...:(p E;Z)`). If `q` is nonempty it takes precedence over `m` (`q[0]?q:m`).
    * Until a valid move is entered correctly (`until[[c,r,x,y]]-(...)==[]`), display the prompt (`$><<A+?>`) and convert the input to 0-indexed column/row numbers (`gets.bytes.map{~-_1%8}`).
7. Update the source and destination squares, saving the destination index in `t` (`#$g,b[t[A]=x+8*y]=p,A`).
> 19 votes

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


title: Venn of \$n\$ statements

text:
# Question
Title: Venn of \$n\$ statements
Given a positive integer \\$n\\$, output \\$n\\$ 2D bool images with the same width and height such that:

1. Each image should be 4-connected, i.e. for each two pixels that are true, you can start from one and go up, down, left and right for some times to the other pixel, only passing through true pixels.
2. Each image should have no holes, i.e. the complement should be 4-connected.
3. If we choose itself or its complement for each image, their intersection should be non-empty and 4-connected.

## Examples (only a finite amount of solutions shown, but there are infinitely many more)

Input: 1

Possible output:

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

```

Input: 1

Possible output:

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

```

Input: 2

Possible output:

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

```

Input: 2

Possible output:

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

```

Input: 3

Possible output:

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

```

Input: 4

Possible output:

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

```

The shortest code in each language wins.

Reference

Sandbox

# Answer
> 8 votes
# Python, 62 bytes

```
lambda n:[[[0,j>>i&1,1]for j in range(1<<n)]for i in range(n)]

```

Try it online!

Generates \\$3 × 2^n\\$ images like these:

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

```

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

```
4,6Bṗz

```

Try it online!

Returns a list of binary matrices (that is, a 3D list).

Output for \\$n=6\\$, transposed and ASCII-artified:

```
################################################################
................................################################
................................................................

################################################################
................################................################
................................................................

################################################################
........########........########........########........########
................................................................

################################################################
....####....####....####....####....####....####....####....####
................................................................

################################################################
..##..##..##..##..##..##..##..##..##..##..##..##..##..##..##..##
................................................................

################################################################
.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#
................................................................

```

## Explanation

```
4,6Bṗz Main monadic link, taking n as the argument
4,6    [4,6]
   B   Convert to binary: [[1,0,0],[1,1,0]]
    ṗ  Cartesian power to n
     z Zip with filler n (since it's already a rectangle, the filler will be ignored)

```

# Answer
> 0 votes
# , 64 bytes

```
function(n)Map(function(i)rbind(1,(1:(2^n)-1)%/%2^i%%2,0),1:n-1)

```

Try it online!

Port of Anders Kaseorg's approach \- upvote that one!

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
46SbIãIζ

```

Try it online!

---
Tags: code-golf, binary-matrix, set-theory, open-ended-function
---


title: Square chunk my matrix

text:
# Question
Title: Square chunk my matrix
Your challenge is to write a function/program that takes a matrix of integers m and a number n as input and:

* Splits m into n by n chunks
* Replaces each chunk with the most common value in that chunk (In case of a tie, any of the tied values is fine).
* Outputs the resulting matrix.

Note: You can take either the size of a single chunk, *or* the number of chunks to a side.

Example:

```
0 1 0 1
0 0 1 1
0 0 0 0
0 0 1 1,
2

```

Divide into chunks:

```
0 1|0 1
0 0|1 1
---+---
0 0|0 0
0 0|1 1

```

Take the most common value in each sub-matrix

```
0|1
-+-
0|0

```

So

```
0 1
0 0

```

is the result!

Note: You can assume that there will always be an integer amount of chunks with integer size.

Input will always be square.

# Testcases

These are formatted as taking the size of a single chunk.

```
0 1 2 1 2 1
2 2 1 0 2 2
2 1 2 0 1 0
0 0 1 0 3 2
3 0 2 0 3 1
1 0 3 2 0 1,
3 =>
2 1
0 0
(The 1 is a tie, any of 012 are fine)

0 1 2 1 2 1
2 2 1 0 2 2
2 1 2 0 1 0
0 0 1 0 3 2
3 0 2 0 3 1
1 0 3 2 0 1,
2 =>
2 1 2
0 0 3
0 2 1
(The 3 is a tie, any of 0123 are fine)

1,
1 =>
1
(kinda obvious edgecase)

```

# Scoring

This is , shortest wins!

# Answer
> 2 votes
# MATL, 11 bytes

```
thZCtvXM[]e

```

Try it online! Or verify all test cases.

### How it works

```
th     % Implicit input: number n. Horizontally concatenate with itself to give [n n]
ZC     % Implicit input: matrix m. Im2col: arrange each [n n] block as a column of
       % length n*n
tv     % Vertically concatenate with itself. This makes columns twice as long without
       % affecting their mode. This is needed in case the previous result had a single
       % row (n=1), which would cause the subsequent mode function to compute the mode
       % of that row, instead of the mode of each column
XM     % Mode. This gives the mode of each column (the input has at least 2 rows)
[]e    % Reshape as a square matrix. Implicit display

```

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~40~~ 38 bytes (SBCS)

Anonymous tacit infix function taking chunk size as left argument and the input matrix as right argument.

```
{(∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,¨↑(⊂⊂¨⊂[1]∘⍵)(≢⍵)⍴⍺↑1}

```

Try it online!

`{``}`dfn;  is chunk size and  is matrix:
`2` and
`⎡0,1,0,1⎤`
`⎢0,0,1,1⎥`
`⎢0,0,0,0⎥`
`⎣0,0,1,1⎦`

`⍺↑1` take "chunk size" elements from 1, padding with zeros
`[1,0]`

`(≢⍵)⍴` cyclically reshape that to the number of rows in the matrix
`[1,0,1,0]`

`(``)` apply the following tacit prefix function:

`⊂[1]∘⍵` use the argument to partition the matrix vertically
`⎡0,1,0,1⎤ ⎡0,0,0,0⎤`
`[⎣0,0,1,1⎦,⎣0,0,1,1⎦]`

`⊂⊂¨` use the entire argument to partition each of those horizontally
`⎡0,1⎤ ⎡0,1⎤ ⎡0,0⎤ ⎡0,0⎤`
`[[⎣0,0⎦,⎣1,1⎦],[⎣0,0⎦,⎣1,1⎦]]`

mix into a matrix
`⎡ ⎡0,1⎤ ⎡0,1⎤ ⎤`
`⎢ ⎣0,0⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`

`(``)∘,¨` for each element, ravel (flatten) it and then apply the following tacit prefix function:
`⎡ [0,1,0,0],[0,1,1,1] ⎤`
`⎣ [0,0,0,0],[0,0,1,1] ⎦`

`⊢∘≢⌸` for each unique element, count the indices it occurs at
`⎡ [3,1],[1,3] ⎤`
`⎣ [4] ,[2,2] ⎦`

… with the unique elements…
`⎡ [0,1],[0,1] ⎤`
`⎣ [0] ,[0,1] ⎦`

`∘⊃∘⍒` get the index of the largest count (lit. first element of the permutation vector that would sort the counts descending), then…
`⎡1,2⎤`
`⎣1,1⎦`

`⊃⍨` use that to pick from the list of unique elements
`⎡0,1⎤`
`⎣0,0⎦`

# Answer
> 4 votes
# , 23 bytes

```
(0{~.\:1#.=)@,;.3~2 2&$

```

Try it online!

J's `u;.3` is pretty handy for this. It splits a matrix into rectangles. You just need to give the size of the rectangles and the offset between rectangles. So for `3x3`-tiles the input would be `[[3 3],[3 3]]`. That is handled by `2 2&$` (if we can take width and height of a tile as input, that would be `;.~` for -2 bytes). For each tile `;.3~` we flatten the tile `,` and sort `\:` the unique values `~.` by their occurences `1#.=` and take the first one `0{`.

# Answer
> 3 votes
# Japt `-h`, 17 bytes

```
2Æ=yòV)ËËc ü ñÊÌÌ

```

Try it

```
2Æ=yòV)ËËc ü ñÊÌÌ     :Implicit input of 2D-array U and integer V
2Æ                    :Map the range [0,2)
  =                   :Reassign to U
   y                  :  Transpose
    òV                :  Partition rows to length V
      )               :End reassignment
       Ë              :Map
        Ë             :  Map
         c            :    Flatten
           ü          :    Group & sort by value
             ñ        :    Sort by
              Ê       :      Length
               Ì      :    Last element
                Ì     :    Last element
                      :Implicit output of last element in the range

```

# Answer
> 2 votes
# Jelly, 13 bytes

```
Zs€Zs€ẎF€ÆṃḢ€

```

Try it online!

## How it works

```
Zs€Zs€ẎF€ÆṃḢ€ - Main link. Takes M on the left and n on the right
Z             - Transpose M
 s€           - Slice each row into n pieces
   Z          - Transpose
    s€        - Split each group of columns into n pieces
      Ẏ       - Flatten into a list of n x n matrices
       F€     - Flatten each matrix
         ÆṃḢ€ - Get the first mode of each

```

# Answer
> 2 votes
# Jelly, 12 bytes

```
sZ€FÆṃḢƊ⁹ÐƤ€

```

Try it online!

After several 13s, I found a 12. A dyadic link taking the grid as a list of lists of integers on the left side and the size of the split on the right.

## Explanation

```
s            | Split into sublists of the length specified by the right argument
 Z€          | Transpose each
       Ɗ⁹ÐƤ€ | For each sublist, do the following for each non-overlapping infix of the length specified by the original right argument:
   F         | - Flatten
    Æṃ       | - Mode
      Ḣ      | - Head

```

# Answer
> 2 votes
# , ~~130~~ ~~124~~ ~~121~~ ~~116~~ 111 bytes

*-5 bytes and another 3 thanks to @Dominic*

```
function(M,n,k=dim(M))array(Map(function(x)el(names(sort(-table(x))):0),split(M,t(a<-(row(M)-1)%/%n)*k+a)),k/n)

```

Try it online!

Longer approach than @Dominic's, but I thought it's worth a try.

Builds matrix mask `t(a<-(row(M)-1)%/%n)*dim(M)+a` used then in `split`, for example for matrix \\$6\times6\\$ and \\$n=2\\$:

```
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    6    6   12   12
[2,]    0    0    6    6   12   12
[3,]    1    1    7    7   13   13
[4,]    1    1    7    7   13   13
[5,]    2    2    8    8   14   14
[6,]    2    2    8    8   14   14

```

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

```
BlockMap[Commonest[Join@@#,1]&,#2,{#,#}]&

```

Try it online!

Input `[n, m]`. Returns a matrix of singleton lists.

# Answer
> 2 votes
# K (ngn/k), ~~29~~ 28 bytes

-1 byte from @Traws

```
{(*>#'=,/)''2(+(0N;y)#/:)/x}

```

Try it online!

Based off of @Shaggy's Japt answer. Takes the input matrix as `x` and the chunk size as `y`.

* `2(...)/x` set up a do-reduce, seeded with `x` and run twice
    + `(+(0N;y)#/:)` slice each row into `y`-length chunks, then transpose them
* `(...)''` run the code in `(...)` on each chunk in the transformed matrix
    + `(*>#'=,/)` group the flattened chunk contents, counting the number of times each distinct number appears, then sort descending and return the first value (i.e. the mode)

# Answer
> 1 votes
# APL (Dyalog Extended), 37 (SBCS)

Anonymous tacit infix function taking chunk count as right argument and the input matrix as right argument.

```
((∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,⍤2)1 3 2 4⍉⊣⍴⍨4⍴⊢,≢⍛÷

```

Try it online!

`{``}`dfn;  is matrix and  is chunk size:
`⎡0,1,0,1⎤`
`⎢0,0,1,1⎥`
`⎢0,0,0,0⎥`
`⎣0,0,1,1⎦`
and `2`

`≢⍛÷` the matrix size divided by the chunk size
`2`

`⊢,` prepend the matrix size
`[2,2]`

`4⍴` cyclically reshape to size 4
`[2,2,2,2]`

`⊣⍴⍨` use that to reshape the matrix
`⎡ ⎡0,1⎤ ⎡0,0⎤ ⎤`
`⎢ ⎣0,1⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`

`1 3 2 4⍉` switch the middle two axes
`⎡ ⎡0,1⎤ ⎡0,1⎤ ⎤`
`⎢ ⎣0,0⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`

`(``)∘,⍤2` on each 2D leaf, ravel (flatten) it and then apply the following tacit prefix function:
`⎡ [0,1,0,0],[0,1,1,1] ⎤`
`⎣ [0,0,0,0],[0,0,1,1] ⎦`

`⊢∘≢⌸` for each unique element, count the indices it occurs at
`⎡ [3,1],[1,3] ⎤`
`⎣ [4] ,[2,2] ⎦`

… with the unique elements…
`⎡ [0,1],[0,1] ⎤`
`⎣ [0] ,[0,1] ⎦`

`∘⊃∘⍒` get the index of the largest count (lit. first element of the permutation vector that would sort the counts descending), then…
`⎡1,2⎤`
`⎣1,1⎦`

`⊃⍨` use that to pick from the list of unique elements
`⎡0,1⎤`
`⎣0,0⎦`

# Answer
> 1 votes
# JavaScript (ES6),  ~~136~~  135 bytes

Expects `(matrix)(chunk_size)`.

```
m=>n=>m.slice(-m.length/n).map((_,y,a)=>a.map((_,x)=>eval("for(o=K={},i=n*n;i--;)(o[v=m[y*n+i/n|0][x*n+i%n]]=-~o[v])<K?0:K=o[V=v];V")))

```

Try it online!

### Commented

This is a version without `eval()` for readability.

```
m => n =>                     // m[] = matrix; n = chunk size
m.slice(-m.length / n)        // get an array of m.length / n entries
.map((_, y, a) =>             // for each value at position y in this slice:
  a.map((_, x) => {           //   for each value at position x in this slice:
    for(                      //     chunk loop:
      o =                     //       o is used to store all counts
      K = {},                 //       K is used to store the highest count
      i = n * n;              //       start with i = n * n
      i--;                    //       stop when i = 0 / decrement it
    ) ( o[                    //
          v = m[              //       v is the value in m[]
            y * n + i / n | 0 //       at row y * n + floor(i / n)
          ][                  //       and column x * n + (i mod n)
            x * n + i % n     //
          ]                   //
        ] = -~o[v]            //       increment o[v]
      ) < K ? 0               //       do nothing if it's less than K
            : K = o[V = v];   //       otherwise update V to v and K to o[v]
    return V                  //     implicit end of for(); return V
  })                          //   end of inner map()
)                             // end of outer map()

```

# Answer
> 1 votes
# , ~~113~~ ~~111~~ 108 bytes

*Edit: -2 bytes, and then -3 more bytes, thanks to pajonk*

(or 105 bytes by outputting a matrix of text strings representing the integers)

```
function(m,n)outer(o<-0:(nrow(m)/n-1)*n,o,Vectorize(function(x,y)el(names(sort(-table(m[x+1:n,y+1:n]))):0)))

```

Try it online!

# Answer
> 1 votes
# Python 2, 174 bytes

Quite long, very ugly, possibly the most comprehensions I've used in one statement. There is undoubtedly a better way to do this but I can't look at this thing anymore.

```
def f(m,n):l=len(m);r=range(0,l,n);b=l/n;print('%s '*b+'\n')*b%tuple(max(v,key=v.count)for v in[sum([x[k][j:j+n]for k in range(n)],[])for x in[m[i:i+n]for i in r]for j in r])

```

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 96 bytes

Takes as input an integer matrix \\$ m \\$, and an integer \\$ n \\$ denoting the chunk size.

```
lambda m,n:[[max(x:=sum(j,()),key=x.count)for j in zip(*[zip(*i)]*n)]for i in zip(*[iter(m)]*n)]

```

Try it online!

Very messy use of the split into chunks golfing tip.

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
2F¹δôø}εε˜.M

```

First input is chunk-size \\$n\\$, second input is matrix \\$m\\$.

Try it online or verify all test cases.

**Explanation:**

```
2F       # Loop two times:
   δ     #  Map over each row of the second (implicit) input-matrix:
  ¹ ô    #   Split it into parts equal to the first input-integer
     ø   #  Zip/transpose; swapping rows/columns
 }ε      # After the loop: map over each row of matrices:
   ε     #  Inner map over each matrix:
    ˜    #   Flatten this matrix to a list
     .M  #   Pop and only leave the most frequent integer in this list
         # (after which the mapped matrix is output implicitly as result)

```

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

```
n=>k=>n.flatMap((e,i)=>i%k?[]:e.flatMap((h,j)=>j%k?[]:(M=n.slice(i,i+k).map(K=>K.slice(j,j+k)).flat()).sort((a,b)=>(X=Y=>M.map(Z=>z+=Z==Y,z=0)|z)(b)-X(a))[0]))

```

Try it online!

Golfing languages which have built-ins for occurrence count or chunks have concise programs. Mine is 159 bytes long.

# Answer
> 0 votes
# Charcoal, 54 bytes

```
Ｆ⪪Ｅθ⪪ιηη«≔⟦⟧ζＦＬ§ι⁰«≔⟦⟧εＦι≔⁺ε§λκε≔Ｅε№ελδ⊞ζ§ε⌕δ⌈δ»⊞υζ»Ｉυ

```

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

```
Ｆ⪪Ｅθ⪪ιηη«

```

Split each column into chunks of size `n`, then split the rows into chunks of size `n` and loop over the chunks.

```
≔⟦⟧ζ

```

Start collecting the results for this chunk of rows.

```
ＦＬ§ι⁰«

```

Loop over the number of chunks of columns.

```
≔⟦⟧εＦι≔⁺ε§λκε

```

Collect all of the values in this chunk of matrix into a single array.

```
≔Ｅε№ελδ

```

Get the frequencies of all the values.

```
⊞ζ§ε⌕δ⌈δ

```

Collect the value with the greatest frequency (chooses the first such value in case of a tie).

```
»⊞υζ

```

Save the results for this chunk of rows.

```
»Ｉυ

```

Output all of the results using Charcoal's default array output format.

---
Tags: code-golf, matrix, set-partitions, statistics
---