title: How many umbrellas to cover the beach?

text:
# Question
Title: How many umbrellas to cover the beach?
You work at a beach. In the afternoon, the sun gets quite hot and beachgoers want to be shaded. So you put out umbrellas. When you put out umbrellas you want to shade the entire beach, with as few umbrellas as possible.

Umbrellas come in many sizes. However, larger umbrellas are susceptible to being pulled away by the wind, so in the morning you have to go to the beach and do a soil test. The soil test tells you, for each spot on the beach, the size of the largest umbrella that could be safely placed.

So after your soil test, you get back a list of positive integers. For example:

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

```

Each number represents the maximum radius of an umbrella that can be placed at that location. A radius \\$r\\$ umbrella covers itself, and \\$r-1\\$ spots to both its left and right.

For example a radius 3 umbrella covers:

* itself
* the two spaces directly adjacent to it,
* the two further spaces adjacent to those,

Your task is to write a computer program which takes the results of the soil test as a list of positive integers, and gives back the minimum number of umbrellas required to cover all the spots on the beach.

For example if the soil test gives back `[2,1,4,1,4,1,1,3,1]`, then you can cover the beach with 2 umbrellas:

```
            X X X X X
X X X X X X X   |
      |         |
 [_,_,4,_,_,_,_,3,_]

```

So the output of the program should be 2.

This is code-golf so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

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

```

# Answer
## C89, 89 bytes

**-11 bytes thanks to @Martin Kealey**

```
int m,i,x;f(v,n)int*v;{for(i=n;i--;m=abs(m-i)<x?x+i:m)x=v[i];return m>=n?m=0,1:1+f(v,n);}

```

Try it online!

```
int m, i, x;
int f(int *v, int n)
{
    for(i=n; i--;)
    {
        extern int abs();
        x = v[i];
        if (abs(m-i) < x) m = x+i;
    }

    if (m>=n){
        m = 0;
        return 1;
    }
    else {
        return 1 + f(v, n);
    }
}

```
> 5 votes

# Answer
# Charcoal, ~~30~~ ~~27~~ 26 bytes

```
Ｗ‹↨υ⁰Ｌθ⊞υ⌈Ｅθ∧‹⁻λ↨υ⁰κ⁺λκＩＬυ

```

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

```
Ｗ‹↨υ⁰Ｌθ

```

Until all of the beach has been covered, ...

```
⊞υ⌈Ｅθ∧‹⁻λ↨υ⁰κ⁺λκ

```

... filtering on those umbrellas whose left end is not to the right of the first uncovered index, pick the one that maximises the next uncovered index.

```
ＩＬυ

```

Output the number of umbrellas used.

Edit: Saved 1 byte by porting @tsh's optimisation. Example: Take the input `[1,4,1,1,3,1,1]`. Initially, five umbrellas lie to the right of index `0`, the valid two being the `1` at index `0` itself, and the `4` at index `1`, which also covers indices `1` to `4`. The maximum next uncovered index is therefore `5`, obtained by choosing the `4`. The `1` at index `6` is the only umbrella to the right of index `5`, and the maximum next uncovered index is therefore `7`, obtained by choosing the `3`. This completes the coverage of the beach using two umbrellas.

A port of @Jonas' J solution was also 27 bytes:

```
ＵＭθＥθ¬‹↔⁻μκιＷ⌈⌊θ«→≧×⌊θθ»Ｉ⊕ⅈ

```

Attempt this Online! Link is to verbose version of code. Explanation:

```
ＵＭθＥθ¬‹↔⁻μκι

```

Convert each umbrella into a list of `0`s and `1`s where the `0`s are the locations that are covered.

```
Ｗ⌈⌊θ«

```

Repeat until opening an umbrella will cover the beach.

Keep count of the number of umbrellas opened.

```
≧×⌊θθ

```

Zero out the locations covered by the largest remaining umbrella.

```
»Ｉ⊕ⅈ

```

Output the number of umbrellas required.

Previous 30-byte brute force solution:

```
Ｉ⌊ＥΦＸ²Ｌθ⬤θ⊙θ‹↔⁻μξ×ν﹪÷ιＸ²ξ²Σ⍘ι²

```

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

```
     ²                          Literal integer `2`
    Ｘ                           Raised to power
       θ                        Input array
      Ｌ                         Length
   Φ                            Filter over implicit range
         θ                      Input array
        ⬤                       All indices satisfy
           θ                    Input array
          ⊙                     Any value satisfies
               μ                Inner index
                ξ               Innermost index
              ⁻                 Difference
             ↔                  Absolute value
            ‹                   Is less than
                     ι          Outer value
                    ÷           Integer divided by
                       ²        Literal integer `2`
                      Ｘ         Raised to power
                        ξ       Innermost index
                   ﹪            Modulo
                         ²      Literal integer `2`
                 ×              Multiplied by
                  ν             Innermost value
  Ｅ                             Map over implicit range
                            ι   Current value
                           ⍘    Convert to base
                             ²  Literal integer `2`
                          Σ     Take the sum (i.e. popcount)
 ⌊                              Take the minimum
Ｉ                               Cast to string
                                Implicitly print

```
> 5 votes

# Answer
# 05AB1E, ~~16~~ 13 bytes

-3 thanks to @KevinCruijssen

```
gDδα›æʒøOß}øg

```

Try it online!

## Explanation

```
g         # push the length
D         # twice
δα        # create the 2D array a[i][j] = abs(i-j)
›         # compare each value to the correct value in the input
æ         # take the powerset
ʒ         # and keep sets such that:
 ø         # if transposed
 O         # and summed
 ß         # the minimum value
}         # (is 1)
ø         # transpose
g         # and return the length

```

Requiring that the minimum is 1 is valid because in an optimal solution exactly one umbrella covers the leftmost position.

Transposing and then taking the length finds the minimum length, due to the way transposing works on different-sized arrays.

`δ›Å\` really feels like it can be shorter, but I can't find anything.
> 4 votes

# Answer
# , 61 bytes

```
f=\(b,p=l,l=sum(b|1))sum(if(p>0)1+f(b,min((1:l-b)[1:l+b>p])))

```

Attempt This Online!

**Ungolfed code**

```
f=function(b,p=1){ # begin at position p=1
    l=length(b)
    s=1:l-b+1 # start positions of umbrellas
    e=1:l+b-1 # end positions of umbrellas
    if(p>l)0
    else 1+f(b,max(e[s<=p])+1)
              # update position to
              # furthest end of umbrella
              # with start before current position
}

```
> 4 votes

# Answer
# , <sup>36 34 33 31 </sup> 33 bytes

```
{{1>.#}.(OR>./)^:a:#.y>|@-/~#\y}}

```

Attempt This Online!

*-1 thanks to Bubbler suggesting a conversion to explicit fn.*

*Also thanks to Bubbler for pointing out a bug when a single umbrella covers everything, which must be handled as a special case.*

Inspired by Neil's idea, but with an array implementation.

Consider the example `2 1 4 1 4 1 1 3 1`:

* `y>|@-/~#\y` For each entry in the list, this shows what the beach would look like with only that umbrella open, using a `1 0` list. The full phrase returns a binary matrix, with each row showing one "isolated umbrella" version of the beach:

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

```
* `#.` Interpret those as binary numbers:

```
384 128 504 32 254 8 4 15 1

```

Conceptually, we'll still be working with `1 0` lists, but using integers will help us shorten the necessary computations.
* `(...^:a:)` Accumulate the results of `...` until a fixed point...
* `(...>./)` On each iteration, we find the row with the farthest rightward span of ones, provided that span starts at the left:

```
1 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0  <- farthest rightward span
0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 1 1 0  <- doesn't count since it starts with 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1

```

This row, however, is nothing but the largest integer in our list, because of how binary numbers work.
* `(OR...)` We then add that "farthest right" row elementwise to every row, essentially "blocking out" everything it covers from all rows. This is nothing but the bitwise `OR` operation. The transformation in this step corresponds to our chosen umbrella being deployed:

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

```

Then we continue. Our process will reach a fixed point (a matix of all ones) in `n + 1` steps, where `n` is the minimum number of covering umbrellas.
* `#}.` So we kill one element and get the length.
* `1>.` Finally, we return the max of that length and 1. This is needed for the case where a single umbrella covers the entire beach, because otherwise the algorithm above will return 0 in this case.
> 4 votes

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

```
a=>(g=i=>a[i]&&-~g(a.reduce((m,r,j)=>j-i<r&r+j>m?r+j:m)))(0)

```

Try it online!

---

# Python 3, 73 bytes

```
f=lambda a,i=0:i<len(a)and-~f(a,max(r+j for j,r in enumerate(a)if j-i<r))

```

Try it online!
> 4 votes

# Answer
# Nekomata, 13 bytes

```
Jᵐ{x:ᵒ≈>~}aş#

```

Attempt This Online!

```
Jᵐ{x:ᵒ≈>~}aş#
J               Split the list into parts
 ᵐ{x:ᵒ≈>~}      Check that each part can be covered by an umbrella:
 ᵐ{      }          For each part:
   x:ᵒ≈                 Create a table a[i][j] = abs(i-j)
       >~               Check that there is at least one row in the table
                        that is smaller than the corresponding item in the input
          aş    Find the shortest solution
            #   Take the length

```

This may output the same result multiple times. For example, the input `[2,1,4,1,4,1,1,3,1]` can be split into `[[2,1,4,1,4],[1,1,3,1]]` or `[[2,1,4,1,4,1],[1,3,1]]`, and the output is `2` in both cases.
> 3 votes

# Answer
# JavaScript, 62 bytes

```
f=(a,s=0)=>a[s]?1+f(a,Math.max(...a.map((v,i)=>i-v<s&&i+v))):0

```

Try it online!

Greedy algorithm: pick the umbrella that covers the most spaces while including the first uncovered space.
> 2 votes

# Answer
# Python3, 358 bytes

```
E=enumerate
F=lambda h,i,a:{*[i+j for j in range(1,a)if i+j<len(h)]+[i-j for j in range(1,a)if i-j>=0],i}
def f(h):
 q,m=[(F(h,i,a),1)for i,a in sorted(E(h),key=lambda x:x[1])[::-1]],-1
 while q:
  a,b=q.pop(0)
  if len(a)==len(h):m=b if m==-1 else min(m,b);continue
  for x,y in E(h):
   if x not in a and(m==-1or b+1<m):q=[({*a,*F(h,x,y)},b+1)]+q
 return m

```

Non-greedy (where is the fun otherwise?) with a basic heuristic for the sake of speed.

Try it online!
> 2 votes

# Answer
# Python, 182 bytes

*-2 bytes, thanks to xigoi*

```
lambda l:(S:={*range(L:=len(l))})and[len(c)for n in S|{L}for c in combinations([range(i-k+1,i+k)for i,k in enumerate(l)],n)if{L}.union(*({*r}for r in c))>S][0]
from itertools import*

```

Attempt This Online!

## ungolfed code:

```
import itertools
def f(l):
 l=[range(i-k+1,i+k)for i,k in enumerate(l)]
 S={*range(L:=len(l))}
 for n in range(len(l)+1):
  for c in itertools.combinations(l,n):
   s=set()
   for r in c:
    s|={*r}
   if s>S: # s=S not possible as L in s\S
    return len(c)

```

Brute force solution, goes through all possible sets of umbrellas ordered by size and picks the first one that covers the whole range
> 2 votes

# Answer
# JavaScript (ES6), 87 bytes

Brute force.

```
a=>(g=(i,b=a,v=a[i++])=>v?Math.min(g(i,b),1+g(i,b.map(q=>--i*i<v*v?0:q))):b.join``*i)``

```

Try it online!
> 2 votes

# Answer
# sed, 424 bytes

Thank you for restricting umbrella sizes to 9, otherwise `sed` stops to be the natural choice for solving this thing. (-; The maximum number of umbrellas is also limited to nine; you can upgrade to the big-beach-edition for a couple of extra bytes as an in-app-purchase.

I got distracted so often, that I decided to publish this initial version solving the problem, although I'm feeling that there are still ten to twenty bytes to golf away on a rainy day.

How it works:

* loop `1` creates all possible combinations of umbrellas used or not
* loop `2` sorts those combinations by their number of umbrellas used, which is awfully slow with this approach for 2^beachsize combinations!
* loop `3` takes one combination after the other to test whether they cover the beach with those sub-elements:
    + loop `4` makes a separate line for each umbrella
    + loop `5` opens the umbrellas by couting down there size and spreading `=`
    + loop `6` transposes the beaches from lines to columns (this will probably only work with wet sand)
    + if there is a line without umbrella, this means sun will hit the beach, so we have to start with the next combination of loop `3`
* loop `7` finally counts the number of umbrellas in the first shady combination

```
G
s/^/_/
:1
s/(\S*)_(\S)(\S*.)/\1-_\3\1\2_\3/
t1
:2
s/-(\S*_)/0\1#/
s/(\S*_(#*)\n)(\S*_\2#+\n)/\3\1/
t2
h
:3
s/\S*\n//
x
s/_.*/\n/
:4
s/^(-*)([0-9])(\S*.)/\1-\3\1\2_\3/
s/_\S/-_/
t4
s/-*/987654321#/
:5
s/((.)(.).*#.*)\2/\1x\3x/
s/(x=*)-/\1=/
s/-(=*)x/=\1/
s/x//g
t5
s/#./&!_/
s/\n//g
:6
s/!(.*_)([^x])/!\2\1x/
t6
s/_x*/_/g
s/!/!\n/
/__/!t6
s/!/!#/
/\n[-0]+(\n|_)/!b7
g
b3
:7
s/((.)(.).*!)\3(.*)1.*/\1\2\4/
t7
s/.*!(.).*/\1/

```

Try it online! *Note that beaches of 8 parts or bigger will time out on TIO. Adding a `g` flag in the sorting part of the second loop drastically reduces execution time, but still not enough for hard cases.*
> 2 votes

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

```
x<Ls-ā©+æʒ˜®åP}øg

```

-1 byte thanks to *@CommandMaster*.

Try it online or verify all test cases.

**Explanation:**

```
x<      # Calculate the width of each umbrella:
x       #  Double each value in the (implicit) input-list (without popping)
 <      #  Decrease each by 1
Ls-ā©+  # Convert each to 1-based ranges it can cover:
L       #  Convert each inner value to a [1,value]-ranged list
 s-     #  Subtract the values of the input-list from each value of the lists
   ā +  #  Add the 1-based indices
    ©   #  And also store the list of 1-based indices in variable `®`
æʒ˜®åP} # Get all combinations of umbrellas that cover the entire beach:
æ       #  Get the powerset of this list of lists
 ʒ    } #  Filter it by:
  ˜     #   Flatten the list of lists
   ®åP  #   Check whether it contains all 1-based indices of value `®`
øg      # Output the least amount of umbrellas necessary to cover the beach:
ø       #  Zip/transpose; swapping rows/columns,
        #  discarding any trailing items of unequal length lists
 g      #  Pop and push the length
        # (which is output implicitly as result)

```

Try it step-by-step.
> 1 votes

# Answer
# JavaScript (SpiderMonkey), 76 bytes

```
f=(a,k=0,b=-1)=>a[k]?1+Math.min(...a.map((v,i)=>i>b&v+k>i?f(a,v+i,i):1/0)):0

```

Try it online!

Try to fix m90's error
> 1 votes

# Answer
# Desmos, ~~169~~ 168 bytes

```
L=l.count
I=[1...L]
B=mod(floor(2n/2^I),2)
k=i-l[i]
H=[1...k]0
A=[min(∑_{i=1}^Ljoin(H[k>H],[1...2l[i]-1+min(k,0)]0+1,I0)[I]B[i])B.totalforn=[1...2^L]]
f(l)=A[A>0].min

```

Try It On Desmos!

Try It On Desmos! - Prettified

This brute forces every single umbrella combination, so expectedly this is very slow. In fact, this took about 40 or so seconds to finish running on my computer LOL.

Also, the code is absolutely horrendous and can definitely be golfed. I mean, just look at it....
> 1 votes

# Answer
# Ruby, ~~102 100~~ 97 bytes

```
->l{(r=*1..l.size).find{|c|r.combination(c).any?{|x|r&x.flat_map{|a|[*a-l[-a]+1...a+l[-a]]}==r}}}

```

Try it online!

Thanks value ink for some good ideas (-2/-3 bytes)
> 1 votes

# Answer
# APL (Dyalog Unicode), 78 bytes

```
⌊/b/⍨×b←{(+/⍵)×∧/(1@(∊{n(1⌈⌊)(⍳¯1+2×⍵⌷v)+⍵-⍵⌷v}¨⍵/⍳n))n⍴0}¨{⍵⊤⍨n⍴2}¨⍳¯1+2*n←⍴v

```

Another brute force attack. The index origin is set to 1 (⎕IO←1). The variable v contains the integer vector to be evaluated.

I have some more work to do on this one. It is a bit convoluted as it is. I think I'm missing something obvious.

Try it on TryAPL.org!
> 1 votes

# Answer
**Raku 68 bytes**

```
map({$^a-$^b+1..^$^a+$^b},@_.kv).combinations.grep(^@_⊆*)>>.elems.min

```

simple brute force approch Try it online!
> 0 votes

# Answer
# Scala, 113 bytes

Port of @tsh's Python code in Scala.

---

Golfed version. Try it online!

```
def f(a:Seq[Int],i:Int=0):Int=if(i<a.length)1+f(a,(0 to a.length-1).filter(j=>j-i<a(j)).map(j=>a(j)+j).max)else 0

```

Ungolfed version. Try it online!

```
object Main {
  def f(a: List[Int], i: Int = 0): Int = {
    if (i < a.length) {
      val maxJump = (0 until a.length)
        .filter(j => j - i < a(j))
        .map(j => a(j) + j)
        .max
      1 + f(a, maxJump)
    } else {
      0
    }
  }

  def main(args: Array[String]): Unit = {
    println(f(List(9,2,1,3,2,4,2,1))) // 1
    println(f(List(1,1,1,1,1,1,1,1))) // 8
    println(f(List(2,1,4,1,4,1,1,3,1))) // 2
    println(f(List(5,1,3,1,3,1,1,1,6))) // 2
    println(f(List(4,1,1,3,1,1))) // 2
  }
}

```
> 0 votes

# Answer
# Python, 200 bytes

Not a very competitive answer, but it's the best I can do with the baseline python functions.

* l: is list of the beach spaces
* r: radius of already covered spaces
* p: amount of umbrellas and the final answer

Function goes through the beach from the left, finds the right most umbrella placing which covers all uncovered space to its left and reaches the farthest right. The function then starts again with the spaces to the right of the last placed umbrella and now with info of which spaces on the left are already covered. When all spaces are covered prints out number of placed umbrellas.

Any tips for making this more streamlined are welcome, thank you.

```
def f(l,r=0,p=0):
    m=r
    for u in range(len(l)):
        s=l[u]-1
        if u-s-r<1 and u+s>=m:
            m=u+s
            t=u
    if m>len(l)-2: return p+1
    else: return f(l[t+1:],m, p+1)

```

Attempt This Online!
> 0 votes

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


title: How many twisted corners?

text:
# Question
Title: How many twisted corners?
Your challenge is to output the number of twisted corners given a 2x2 Rubik's Cube scramble.

For the purpose of this challenge, twisted corners are defined as corners where the colour of the top/bottom face before (usually white or yellow) is not facing the top/bottom after the scramble.
Eg. if the cube were to be oriented yellow top/white bottom, then the number of corners where yellow/white isn’t on the top/bottom after the scramble should be returned.

A scrambled cube is represented as a list of moves, where each move is denoted by the letters `UDRLFB` corresponding to clockwise turns of the faces: Up, Down, Right, Left, Front, and Back.
You have the option to replace the moves `UDRLFB` with a predefined set of constants. You may assume the scramble list is non-empty.

This is , so the shortest answer wins!
Standard loopholes apply, this loophole in particular is forbidden too.

## Test cases

Example gif with scramble "L U U U F" | Top and bottom face after scramble

```
[In]: R
[Out]: 4
[In]: L U U U F
[Out]: 3
[In]: R R D D D B B U L F
[Out]: 6
[In]: B U U D D F
[Out]: 0

```

# Answer
# Charcoal, 67 bytes

```
≔Ｅχ⁰θＦＥＳ⌕DBRUFLι«≔Ｉ⪪§⪪”)⧴∧\ⅈNυSＢ⊞ae”⁴ι¹ηＵＭθ⎇№ηλ﹪⁻ι§θ§η⊖⌕ηλ³κ»Ｉ№Ｘ⁰θ⁰

```

Try it online! Link is to verbose version of code. Takes a string of `DBRUFL` as input. Explanation:

```
≔Ｅχ⁰θ

```

Start with an array of zeros representing the untwisted corners. (There are ten rather than eight to save a byte.)

```
ＦＥＳ⌕DBRUFLι«

```

Map the input string into the integers `0-5` and loop over them. (The mapping is contrived to make the calculation below shorter, which is why I didn't require that as the input format.)

```
≔Ｉ⪪§⪪”)⧴∧\ⅈNυSＢ⊞ae”⁴ι¹η

```

Look up the corner permutation for this move, which is a list of indices of the corners that move in clockwise order.

```
ＵＭθ⎇№ηλ﹪⁻ι§θ§η⊖⌕ηλ³κ

```

For those corners that move, find the corner that moves to this corner, and subtract its value from the move index, modulo `3`.

```
»Ｉ№Ｘ⁰θ⁰

```

Output the final number of twisted corners.

22 bytes if I abuse the input format:

```
≔Ｅ⁸ιθＦＡＵＭθ§⮌↨ιφκＩ№÷θχ⁰

```

Takes input as an array of integers which represent a mapping to apply to the positions of the eight white and yellow stickers. No TIO link because I haven't actually bothered to compute suitable integers.
> 3 votes

# Answer
# Jelly,  ~~13~~  12 bytes

Pushes the I/O rules to the edge (confirmed that it is acceptable)

```
œ?@ƒ24s3I§ḂS

```

A monadic Link that accepts a list of permutation indices of the 24 showing *facelets** and yields the number of *twisted corners*.

* i.e. the stickers on older cubes.

**Try it online!** (The footer converts the usual characters to the defined constants.)

### How?

We label the eight corners using the three faces to which they belong in some arbitrary order, starting each with their U/D face and reading anticlockwise (again an arbitrary choice):

```
    UFR  URB  UBL  ULF  DRF  DBR  DLB  DBR

```

Now we label these stickers when in a solved state:

```
    ABC  DEF  GHI  JKL  MNO  PQR  STU  VWX

```

Now we record the six face-turn permutations:

```
D:  ABC  DEF  GHI  JKL  VWX  MNO  PQR  STU
L:  ABC  DEF  UST  HIG  MNO  PQR  WXV  LJK
B:  ABC  RPQ  EFD  JKL  MNO  TUS  IGH  VWX
U:  DEF  GHI  JKL  ABC  MNO  PQR  STU  VWX
F:  KLJ  DEF  GHI  XVW  CAB  PQR  STU  NOM
R:  OMN  BCA  GHI  JKL  QRP  FDE  STU  VWX

```

Now we find the index of each of these in all permutations of the solved state labelling by using code that I wrote that was added to Jelly many moons ago (along with its family including `œ?`, see below) - TIO:

```
D:                395176321
U:         5246483101592279
B:     35597574695850514081
F:  81089009208703431936001
U: 270227677129672827133894
R: 376031890064925569220481

```

Now with a list of these constants as our input, we can perform the permutations in turn and find the number of *twisted corners*:

```
œ?@ƒ24s3I§ḂS - Link: list of the defined constants, Scramble
    24       - twenty four
   ƒ         - start with State=24 and reduce using Scramble's Constants:
  @          -   with swapped arguments:
œ?           -     permutation at index {Constant} of the items in {State}
                     (when State=24 it's implicitly cast to [1..24])
      s3     - slice into threes (first of every triple is the U/D facelet)
                 (when Scramble="" the 24 we have is cast to [1..24] giving
                  us [[1,2,3],...,[22,23,34]])
        I    - forward differences of each
         §   - sums
          Ḃ  - modulo two
           S - sum

```
> 2 votes

---
Tags: code-golf, array, rubiks-cube
---


title: Landmine Number I

text:
# Question
Title: Landmine Number I
## Background

You have been given the task of calculating the number of landmines in a field.

You must calculate the landmine score given a list/string of numbers and the landmine number.

The landmine number tells you where landmines are.

For each digit:

1. if the left digit plus the right digit is equal to the landmine number, add one to the landmine score.
2. if the left digit times the right digit is equal to the landmine number, add two to the landmine score.
3. if both 1 and 2 are satisfied, add three to the landmine score.

Note: The very first and last digits cannot have landmines because there are no adjacent numbers to the left and right of them respectively.

## Your Task

* Sample Input: Two strings/numbers/lists. The length of the first number will be maximum 256 characters/numbers long. It will only contain numbers. The second number will tell you the landmine number.
* Output: Return the landmine score.

**Explained Examples**

```
Input => Output
18371 4 => 2

```

There are only two landmines here:

* One on 8, because 1+3 = 4.
* One on 7, because 3+1 = 4.

```
Input => Output
2928064 4 => 4

```

There are four landmines here:

* Three on 9, because 2+2 = 2x2 = 4.
* One on 6, because 0+4 = 4.

```
Input => Output
33333 9 => 6

```

There are six landmines here:

* Two on each of the second, third, and fourth threes.

```
Input => Output
9999999999 100 => 0

```

No combination of addition and multiplication will yield 100.

```
Input => Output
1234567890 8 => 4

```

There are four landmines here:

* Two on 3, because 2x4 = 8
* One on 4, because 3+5 = 8
* One on 9, because 8+0 = 8

**Test Cases**

```
Input ~> Output

18371 4 ~> 2
2928064 4 ~> 4
33333 9 ~> 6
9999999999 100 ~> 0
1234567890 8 ~> 4

22222 4 ~> 9
00000000000000 0 ~> 36
12951 10 ~> 4
123123123123 3 ~> 11
828828828 16 ~> 11

```

This is , so shortest answer wins.

...

**Landmine Number Series**

# Answer
> 6 votes
# Husk, 13 bytes

```
#Σz§:+o´e*↓2¹

```

Try it online!

```
#             # how many times is arg 2 present in:
 Σ            # flatten the results of
  z           # zipping together
              #   arg 1 and
          ↓2¹ #   arg 1 without its first 2 elements
              # using the function
   §:         #   join together
     +        #     sum of each pair of elemnts
      o´e     #     and 2 copies of
         *    #     product of each pair of elements

```

# Answer
> 5 votes
# 05AB1E, 13 bytes

```
Ð¦¦©+s®*D)QOO

```

Try it online!

I feel like at least one byte can be golfed, but I can't figure out how

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

Expects `(n)(array)`.

```
n=>a=>a.map(p=v=>s+=p+v==n|2*(p*(p=a,a=v)==n),s=0)|s

```

Try it online!

# Answer
> 5 votes
# Husk, 11 bytes

```
#ṁMzė+**↓2¹

```

Try it online!

Inspired by Dominic van Essen's answer, with some added functional trickery to make it shorter.

## Explanation

A necessary introduction: `z+` is a function that vectorizes the `+` operation to sum two lists element by element. If a list is longer than the other, extra elements are dropped. `z*` does the same thing with multiplication.

For example (in pseudocode) `z+[1,2][3,6,9]` = `[4,8]`

```
#ṁMzė+**↓2¹   Example input: [1,2,3,2] 4
    ė+**      A) a list of three functions: [+,*,*]
        ↓2¹   B) the first input without its first two values: [3,2]
  Mz          For each function f in A, do zfB
                this will result in a list of partially-applied functions
                missing the second argument for the vectorized sum (or multiplication):
                  [z+[3,2], z*[3,2], z*[3,2]]
 ṁ            Apply each of these functions to the (implicit) first input:
                  [z+[3,2][1,2,3,4], z*[3,2][1,2,3,4], z*[3,2][1,2,3,4]] =
                  [[4,4], [3,4], [3,4]]
                and concatenate the results: [4,4,3,4,3,4]
#             Count how many times the (implicit) second input appears in this list: 4

```

# Answer
> 4 votes
# Vyxal `s`, 75 bitsv2, 9.375 bytes

```
3lƛy$₍Π∑⁰=B

```

Try it Online!

Takes long number as a list of digits then landmine number. Didn't almost accidentally call it a landline number.

## Explained

```
3lƛy$₍Π∑⁰=B
3l           # Get all overlapping windows of size 3 of the long input
  ƛ          # To each window:
   y$        #   Remove the middle item
     ₍Π∑     #   Push a list of [product, sum]. I love parallel apply.
        ⁰=   #   And check whether each item equals the landmine number
          B  # Convert from binary
# The s flag sums the resulting list

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

# Answer
> 4 votes
# Racket \- 251 bytes

```
#!racket
(let*([L(map(λ(c)(-(char->integer c)48))(filter char-numeric?(string->list(read-line))))][M(read)][R(curry list-ref L)])(for/sum([i(range 1(-(length L)1))])(let*([l(R(- i 1))][r(R(+ i 1))][m(=(* l r)M)])(count(λ(c)c)(list(=(+ l r)M)m m)))))

```

Input must be on separate lines, first input is the landscape, and the second input is the number representing the landmine.

Try it online!

---

## Explanation

### Input, filtering, mapping

First the program splits the landscape string into a list of characters. It filters out any characters that aren't digits then proceeds to map over the list, turning all the characters into their respective numeric digits.

### Looping

We then create a `for/sum` loop that iterates over the list from indices 1 through length - 2 (length - 1 is the last index of the list, but it can't have a landmine). As the loop iterates, it collects the landmine count for each digit. Once it has completed the iteration, the loop returns the summed-up counts.

### Counting landmines

The way we count the landmines for a digit is simple. We create a boolean list that contains the results of two different equality checks: addition of the left and right digits and the multiplication of the left and right digits must both be the same as the number representing the landmine in order to return `#t`. Since the multiplication of the left and right digits give two points instead of one, we repeat the check.

```
(list (= (+ left right) landmine)
      (= (* (left right) landmine)
      (= (* (left right) landmine))

```

Once we have created the list, we can pass it to the `count` function. But there is still one ingredient we need because `count` requires two inputs, a `proc` and a `list`. The `proc` function returns a boolean value as `count` iterates the loop. If the value is `#t`, then `count` adds it to the total count.

But we already have the `#t` and `#f` values, and we don't need to change them. That is where the `identity` function comes in handy. The identity function takes a value and returns it the same way as it is. This is how the function looks like in Python:

```
def identity(value):
    return value

```

### Putting it all together and testing

This is the final resulting code:

```
#lang racket

(require (only-in rackunit check-eq?))

; count-landmines: String Number -> Number
; Counts the number of landmines in a string.
(define (count-landmines landscape landmine)
  (let* ([-landscape (map (lambda (char) (- (char->integer char) 48))
                          (filter char-numeric? (string->list landscape)))])
         (for/sum ([index (range 1 (sub1 (length -landscape)))])
           (let* ([left (list-ref -landscape (sub1 index))]
                  [right (list-ref -landscape (add1 index))]
                  [multeq (= (* left right) landmine)])
             (count identity (list (= (+ left right) landmine) multeq multeq))))))

(displayln "Tests are running...")
(check-eq? (count-landmines "18371" 4) 2 "18371 4")
(check-eq? (count-landmines "2928064" 4) 4 "2928064 4")
(check-eq? (count-landmines "33333" 9) 6 "33333 9")
(check-eq? (count-landmines "9999999999" 100) 0 "9999999999 100")
(check-eq? (count-landmines "1234567890" 8) 4 "1234567890 8")

(check-eq? (count-landmines "22222" 4) 9 "22222 4")
(check-eq? (count-landmines "00000000000000" 0) 36 "00000000000000 0")
(check-eq? (count-landmines "12951" 10) 4 "12951 10")
(check-eq? (count-landmines "123123123123" 3) 11 "123123123123 3")
(check-eq? (count-landmines "828828828" 16) 11 "828828828 16")
(displayln "Tests are complete!")

```

## Conclusion

Hope you enjoyed reading my explanation! I had fun with both writing the code and the answer :D

Have a wonderful weekend ahead everyone!

# Answer
> 4 votes
# Charcoal, 26 bytes

```
ＮθＩΣＥＥΦη‹¹κ⁺ι§ηκ№⟦ΣιΠιΠι⟧θ

```

Try it online! Link is to verbose version of code. Takes the landmine number as the first input. Explanation:

```
Ｎθ                          First input as a number
       η                    Second input
      Φ                     Filtered where
         ¹                  Literal integer `1`
        ‹                   Is less than
          κ                 Current index
     Ｅ                      Map over digits
            ι               Current digit
           ⁺                Concatenated with
              η             Second input
             §              Indexed by
               κ            Current index
    Ｅ                       Map over digit pairs
                   ι        Current pair
                  Σ         Digital sum
                     ι      Current pair
                    Π       Digital product
                       ι    Current pair
                      Π     Digital product
                 ⟦      ⟧   Make into list
                №           Count matches of
                         θ  First input
   Σ                        Take the sum
  Ｉ                         Cast to string
                            Implicitly print

```

# Answer
> 4 votes
# C (clang), 64 bytes

```
f(*a,l,n){return--l>1?(*a+a[2]==n)+2*(*a*a[2]==n)+f(a+1,l,n):0;}

```

Try it online!

# Answer
> 4 votes
# Thunno 2 `S`, 12 bytes

```
D2ỵZıçpS¹=2ḋ

```

Try it online!

#### Explanation

```
D2ỵZıçpS¹=2ḋ  # implicit input
D             # duplicate the first input
 2ỵ           # remove the first two items
   Z          # zip them together
    ı         # map:
     ç        #  parallelly apply:
      p       #   product
       S      #   sum
        ¹=    #  equals second input?
          2ḋ  #  convert from binary
              # implicit output

```

# Answer
> 3 votes
# JavaScript (V8), 57 bytes

```
x=>k=>x.reduce((r,t,i)=>r+(t+x[i+=2]==k)+2*(t*x[i]==k),0)

```

Try it online!

`map` and `reduce` same length

# Answer
> 3 votes
# Nial, ~~39~~ 36 bytes

```
++mate team[+,[+,*,*][2drop,-2drop]]

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~98 75~~ 58 bytes

```
lambda n,l:sum((x+y==l)+2*(x*y==l)for x,y in zip(n,n[2:]))

```

Try it online!

The inputs are the string of numbers (as a list of ints) and the landmine number (as an int). The function loops through each each pair of valid (i, i+2) indices in the list and calculates the landmine score using boolean addition.

Edit: used zip to save 17 bytes (credit to c--)

# Answer
> 3 votes
# , ~~50~~ 47 bytes

*Edit: -3 bytes thanks to @Dominic van Essen.*

```
\(x,n){h=t=x[-1:-2];h[]=x;sum(h+t==n,2*!h*t-n)}

```

Attempt This Online!

Defines explicitly both head and tail to add/multiply, because of usually handy (and here annoying) R recycling of vectors.
Uses also a trick that `!a-b` is the same as `a==b` with the same byte-count, but due to precedence, we can multiply the former without extra parentheses.

# Answer
> 3 votes
# Haskell, 51 bytes

```
n%(a:t@(b:c:l))=0^(a+c-n)^2+2*0^(a*c-n)^2+n%t
_%_=0

```

Try it online!

Uses `0^(x-y)^2` as an arithmetic version of the indicator function `sum[1|x==y]`. Recursing turned out shorter than my attempts to use `zip`.

**53 bytes**

```
n%l=sum$do(a,c)<-zip l$drop 2l;[1|a+c==n]++[2|a*c==n]

```

Try it online!

**53 bytes**

```
n%l=sum[1|(a,c)<-zip l$drop 2l,x<-[a+c,a*c,a*c],x==n]

```

Try it online!

# Answer
> 3 votes
# Raku, 59 bytes

```
->$_,\n{sum n X==m:ov/(.).(.)/».&{|(.sum,[*] @$_)[0,1,1]}}

```

Try it online!

* `m:ov/(.).(.)/` finds all `ov`erlapping matches for sequences of three digits in the input number.
* `».&{ ... }` passes each match object to the brace-delimited code block. (It's one byte shorter than using `map`.)
* `(.sum, [*] @$_)` produces a two-element list of the sum and product of the first and last digits in each match.
* `[0, 1, 1]` slices into that list, to append an extra copy of the second element (the product).
* `|` flattens that list into the map output.
* `n X== ...` crosses the landmine number with each sum and product using the numeric equality operator `==`, producing a list of booleans. Each product contributes two of the same boolean, thanks to the slice above.
* `sum` sums those booleans, treating `True` as 1 and `False` as 0.

# Answer
> 3 votes
# Swift 5.9, 112 106 103 92 81 bytes

Edit: First solution was actually 112 bytes, not 114.

```
(1...m.count-2).reduce(0){$0+(m[$1-1]+m[$1+1]==n ?1:0)+(m[$1-1]*m[$1+1]==n ?2:0)}

```

Where `m` is an `[Int]` representing the minefield, and `n` is an `Int` representing the mine number.

Ungolfed (plus header):

```
func landmineScore(mines: [Int], mineNumber: Int) -> Int {
    (1...(mines.count - 2)).reduce(0) { result, index in
        result + (mines[index - 1] + mines[index + 1] == mineNumber ? 1 : 0) + (mines[index - 1] * mines[index + 1] == mineNumber ? 2 : 0)
    }
}

```

I can't remove the spaces to the left of the `?`s, because a trailing `?` is interpreted as an optional-chain.

# Answer
> 2 votes
# Retina 0.8.2, 83 bytes

```
 \d+|\d
,;,$&$*
&`(,?;)?,(1*),;,1*,;,((1)*),;,(1*,;,)*(?(1)(?<-4>\2)*(?(4)^)|\3\2)$

```

Try it online! Link includes test cases. Explanation:

```
 \d+|\d
,;,$&$*

```

Convert the landmine number and each of the numbers in the list to unary. Each unary number is preceded by three characters to allow three places for the following expression to match for each number, one for when the two numbers sum to the landmine number and two for when their product equals the landmine number.

```
&`

```

Count all overlapping matches.

```
(,?;)?,(1*),;,1*,;,((1)*)

```

For each interior number, match the numbers on the left and right. The number on the right is matched in two different ways so it can be both added and multiplied. Also allow the match to start up to three separator characters before the left number.

```
,;,(1*,;,)*

```

Skip ahead to the landmine number.

```
(?(1)(?<-4>\2)*(?(4)^)|\3\2)$

```

If there were at least two separator characters then check that the product of the two matched numbers equals the landmine number otherwise check that the sum does.

The regular expression would be 84 bytes without the conditional, but it still needs .NET capture groups in order to perform the multiplication:

```
 \d+|\d
,;,$&$*
&`(,?;?,)(1*),;,1*,;,((1)*)(,;,1*)*(,?\1(?<-4>\2)*(?(4)^)|,;\1\3\2)$

```

Try it online! Link includes test cases.

# Answer
> 2 votes
# Scala, ~~170~~ 163 bytes

Golfed version. Try it online!

```
(f,m)=>(0/:f.zipWithIndex.slice(1,f.size-1)){case(s,(n,i))=>val l=f(i-1)-48;val r=f(i+1)-48;if((l+r==m)&&(l*r==m))s+3 else if(l+r==m)s+1 else if(l*r==m)s+2 else s}

```

Ungolfed version. Try it online!

```
object Main {
  def landmineScore(field: String, mineNumber: Int): Int = {
    field.zipWithIndex.slice(1, field.length - 1).foldLeft(0) {
      case (score, (num, idx)) =>
        val left = field(idx - 1).asDigit
        val right = field(idx + 1).asDigit
        val current = num.asDigit

        if ((left + right == mineNumber) && (left * right == mineNumber))
          score + 3
        else if (left + right == mineNumber) score + 1
        else if (left * right == mineNumber) score + 2
        else score
    }
  }

  def main(args: Array[String]): Unit = {
    println(landmineScore("18371", 4)) // Output: 2
    println(landmineScore("2928064", 4)) // Output: 4
    println(landmineScore("33333", 9)) // Output: 6
    println(landmineScore("9999999999", 100)) // Output: 0
    println(landmineScore("1234567890", 8)) // Output: 4
    println(landmineScore("22222", 4)) // Output: 9
    println(landmineScore("00000000000000", 0)) // Output: 36
    println(landmineScore("12951", 10)) // Output: 4
    println(landmineScore("123123123123", 3)) // Output: 11
    println(landmineScore("828828828", 16)) // Output: 11

  }
}

```

# Answer
> 2 votes
# Arturo, 63 bytes

```
$[a n][0i:0loop drop a 2'x[if=x+a\[i]n[1+]if=x*a\[i]n[2+]'i+1]]

```

Try it!

```
$[a n][                 ; a function taking a list a and integer n
    0                   ; push landmine score
    i:0                 ; assign 0 to i
    loop drop a 2'x[    ; loop over a sans first 2 elements; assign current elt to x
        if=x+a\[i]n[1+] ; add 1 to score if x + a[i] equals n
        if=x*a\[i]n[2+] ; add 2 to score if x * a[i] equals n
        'i+1            ; increment i in place
    ]                   ; end loop
]                       ; end function

```

# Answer
> 2 votes
# Excel, 84 bytes

```
=SUM(TOCOL(LET(a,LAMBDA(b,MID(A1,ROW(A:A)+b,1)),(a(0)+a(2)=B1)+2*(a(0)*a(2)=B1)),2))

```

String in `A1`; landmine number in `B1`.

# Answer
> 2 votes
# Nekomata, 12 bytes

```
ᵉpttᵋ+*:,,$Ĉ

```

Attempt This Online!

```
ᵉ               Parallelly apply the following two unary functions:
 p                  Choose a prefix
  tt                Tail of tail
    ᵋ           Parallelly apply the following two binary functions:
     +              Add
      *             Multiply
                    (This step forces the prefix to have the same length as the tail of tail)
       :,       Duplicate and join
         ,      Join
          $     Swap
           Ĉ    Count

```

# Answer
> 2 votes
# Pyth, 17 bytes

```
/smmvXk1d.:z3"**+

```

Try it online!

### Explanation

```
/smmvXk1d.:z3"**+"Q    # implicitly add "Q
                       # implicitly assign Q = eval(input)
                       #                   z = input() (second input)
  m          "**+"     # map lambda d over "**+"
   m     .:z3          #   map lambda k over all substrings of length 3 in z
     Xk1d              #     replace the middle char of k with d
    v                  #     and evaluate
 s                     # flatten nested list
/                 Q    # count occurrences of Q

```

# Answer
> 2 votes
# Q, 33 bytes

implemented as a function with two implicit arguments, **x** and **y**. **x** is a list of ints (the "field") and **y** is an int (the landmine score).

```
{sum(y=sum x)+2*y=prd x:2 -2_\:x}
q) f: {sum(y=sum x)+2*y=prd x:2 -2_\:x}
q) f[10 vs 1234567890; 8]
4
q) f[1 2 3 1 2 3 1 2 3 1 2 3; 3]
11

```

# Answer
> 2 votes
# Desmos, 319 bytes

https://www.desmos.com/calculator/n5dzd6tvqr

Input is a list of numbers.

`f(a,b)=\sum_{n=1}^{\operatorname{length}(a)}\left[\left\{i=1:0,\left\{i=\operatorname{length}(a):0,\left\{a\left[i-1\right]+a\left[i+1\right]=b:1,0\right\}+\left\{a\left[i-1\right]a\left[i+1\right]=b:2,0\right\}\right\}\right\}\ \operatorname{for}\ i\ =\ \left[1,...\operatorname{length}(a)\right]\right]\left[n\right]`

# Answer
> 2 votes
# BQN, 25 bytes

```
+´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸=

```

Try it at BQN online!

### Explanation

```
+´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸=
  (                    )⊸   Using the left argument (array of digits):
                    3⊸↕       Get all windows (contiguous subarrays) of length 3
                              as rows of a 2D array
                   ⍉         Transpose rows and columns
             0‿2⊏·           Keep the first and last rows
   (+˝∾×˝∾×˝)                 Make a 1D array containing their sums, products, and
                              products again
                         =  Equality with the right argument (1s when equal, 0s
                            otherwise)
+´                          Sum

```

# Answer
> 2 votes
# Uiua, 21 bytes

```
/+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3

```

Try it!

```
/+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3
                   ◫3  # windows of length three
                  ⍉    # transpose
                ↻1     # rotate one
              ↘1       # drop one
         ⊃/+/×         # sum and product of columns
        ⊟              # couple
       =               # where is it equal to input?
   ×1_2                # multiply by [1 2]
  ♭                    # deshape
/+                     # sum

```

# Answer
> 1 votes
# Java, ~~120~~ 112 Bytes

`var l=range(2,n.length).filter(i->n[i-2]+n[i]==t).count()+range(2,n.length).filter(i->n[i-2]*n[i]==t).count()*2;`

-8 Thanks to @ceilingcat

Try It!

---
Tags: code-golf, number
---


# Question
Title: Print the banned characters based on the most common characters
This is an post, so in this challenge every answer (except the first answer) depends on the previous answer.

The goal of this challenge is to output the restricted characters. The restricted characters are the most common `n - 1` characters of **all answers**, if happens to be a tie, then the characters with the lowest UTF-8 range is restricted.

The max bytes for every answer is:

\begin{align}2n+60\end{align}

where `n` is answer number.

## Rules

* The answers only output the restricted characters, no newlines, no other characters like that.

+ The code may output the restricted characters exactly once, in any order.
* Standard loopholes are forbidden by default.
* No answerer may answer twice in a row.
* No languages may be reused in the last 5 answers.
* Every answer takes empty or no input, and outputs to STDOUT.
* The wrong answers (that break rules or don't do that this challenge say) are completely ignored if this answer is 10 minutes old, and should be deleted.

The last answer after 5 days of the challenge not getting answers wins.

## Example

First answer

```
# 1: Python 3, 13 bytes

    print(end="")

Next charset: `"` [link]()

```

The second answer should output `"`. If the second answer's code is `ppaaa`, then the third answer should output either `pa` or `ap` (because these are the most common characters in all answers), and doesn't use these characters.

Note: The scoring formula is based on the byte count and the answer number. The goal is to output the restricted characters efficiently while adhering to the specified byte limits.

Have a great day!

### Clarifications

* The banned character set is the N most common characters of the concatenation of all answers.

# Answer
> 3 votes
# 9: Brachylog, 43 bytes (37 characters)

```
[32,43,9,92,114,99,101,10]~ạw

```

Try it online!

Prints `<space>+<tab>\rce<newline>`. Next set: `<space>+<tab><newline>1\r,c`

# Answer
> 4 votes
# 4: Uiua, 10 bytes

```
&pf-1$ ,=?

```

Uiuapad

New banned characters: +-\<\>

# Answer
> 3 votes
# 3: brainfuck, 42 bytes

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

```

Try it online!

Outputs `er`. Can't fit in js

# Answer
> 3 votes
# 6: C# (Shell), 54 bytes

```
$"{(char)43}{(char)62}{(char)101}{(char)46}{(char)92}"

```

Prints `+>e.\`. Has to be in a shell rather than standalone, since there's no way to output in C# without `e` otherwise.

Next set is `+r()ac` (link)

Try it online!

# Answer
> 2 votes
# 1: Python 3, 18 bytes

```
while True:
	break

```

Try it online!

```
e - 3 (Now banned)
r - 2
<tab> - 1
<newline> - 1
<space> - 1
: - 1
T - 1
a - 1
b - 1
h - 1
i - 1
k - 1
l - 1
u - 1
w - 1

```

This code I stolen from ChatGPT makes easier to make the character list, but you have to combine answers manually.

# Answer
> 2 votes
# 2: Keg, 2 bytes

```
Ɛ

```

Try it online!

Simply prints the letter `e` and exits.

# Answer
> 2 votes
# 7: Whitespace, 73 bytes

The byte-count is 1 below the limit of \\$2\times7+60\\$. :)

```
[S S S T    T   T   S S T   N
_Push_57_c][S S S T T   S T T   T   N
_Push_55_a][S S T   T   N
_Push_-1_)][S S T   T   S N
_Push_-2_(][S S S T S S T   S S S N
_Push_72_r][S S S T N
_Push_1_+][N
S S N
_Create_Label_LOOP][S S S T S T S T S N
_Push_42][T S S S _Add_top_two][T   N
S S _Print_as_char][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Push the codepoint-integers minus 42 of string "ca)(r+"
Start LOOP:
  Add 42 to the top integer
  Print it as character to STDOUT
  Go to next iteration of LOOP

```

The constant `42` is generated by this Java program, based on this Whitespace tip of mine.

---

The next set is `<space>+<tab><newline>r()`.

# Answer
> 2 votes
# 8: Python 2, 34 bytes

```
exec"p\162int'\40\t\53\50\51\162'"

```

Explanation:

```
exec                               # run (in Python 2, this is a statement)
   "p\162int'\40\t\53\50\51\162'"  # <space><tab>+()r (r is replaced twice)
                                   # and then a newline (which is implicit)

```

Prints `<space><tab>+()r<newline>`. Next set: `<space>+<tab><newline>\rce`

# Answer
> 1 votes
# 5: JavaScript (Node.js), 36 bytes

```
process.stdout.write("\53\55\74\76")

```

Attempt This Online!

This prints `+-<>`. I previously had a more interesting GolfScript solution here, but I realized that it contained a `+` which made it invalid.

Next charset is `+>e.\` (link)

---
Tags: code-challenge, restricted-source, answer-chaining
---


# Question
Title: The worst ever phone number entry screen
The name of the challenge was prompted by this GIF and the GIF also gave me the idea.

Your challenge today is to take a input guaranteed to be \\$2\<=n\<=100\\$ and output a sequence of `x` and `-` characters.

The output for a number N represents a sequence of operations applied to 1 where `x` means "multiply by 2" and `-` means "subtract 1". Starting from 1, reading left to right and doing them in order will give you the number N that was inputted.

If you want, you can output using characters other than x and - so long as the choice is consistent through all outputs.

Your strings may be outputted in reverse so long as all are reversed or there is some indication of which are in reverse.

Your score is the source code's size in characters plus the total length of all outputs (again in characters). Have fun everyone!

# Answer
> 5 votes
# Python 2, 37 bytes (+830 char output = 867)

```
f=lambda n:2/n*"0"or`n%2*10`+f(-~n/2)

```

Try it online!

0 for double, 1 for decrement, in reversed order. -1 byte thanks to dingledooper for the base case.

---

# Python 2, 39 bytes

```
lambda n:bin(n-1)[2:].replace('0','10')

```

Try it online!

1 for double, 0 for decrement

# Answer
> 3 votes
# Python 2, 42 bytes, score = 872 (42 + 830)

```
f=lambda x:x>1and f(-~x/2)+"x"+x%2*"-"or""

```

Try it online!

This can be 43 bytes in python 3 by replacing `/`by `//`

# Answer
> 3 votes
# Charcoal, 11 bytes, score 841

```
⭆↨⊖Ｎ²…x-⁻²ι

```

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

```
   Ｎ        Input number
  ⊖         Decrement
 ↨  ²       Convert to base 2
⭆           Map over digits and join
      x-    Literal string `x-`
     …      Truncated to length
         ²  Literal integer `2`
        ⁻   Subtract
          ι Current digit
            Implicitly print

```

# Answer
> 2 votes
# JavaScript (Node.js), 28 bytes + 830 chars in output = 858

```
f=n=>n^1?n%2*10+f(n+1>>1):''

```

Try it online!

"0" represents \*2, "1" represents -1, Output is reversed.

Simple, but quite effective approach. Divides the number by two if it is even, else subtracts 1 from it.

Thanks to @A username for -3 bytes!

Thanks to @xnor for -2 bytes!

# Answer
> 2 votes
# Vyxal, 6 bytes

```
‹bṅ0₀V

```

Try it Online! Xnor port. -2 thanks to Aaron Miller.

# Answer
> 1 votes
# Python 3, 129 bytes, score = 129+830 = 959

```
def f(n,x=1):
 for y in range(2**x):
  c,s=1,''
  for i in' '*x:c+=~y%-2|c;s+='-x'[y%2];y//=2
  if c==n:return s
 return f(n,x+1)

```

Try it online!

Brute force all strings of all lengths starting from length 1.

*thanks to ovs for -12 bytes*

# Answer
> 1 votes
# Retina 0.8.2, 33 bytes, score 863

```
.+
$*
+`(1+)(\1(1)?)
$2x$#3$*-
1

```

Try it online! Link includes test cases. Try it online! Link is to test suite that counts the score. Explanation:

```
.+
$*

```

Convert to unary.

```
+`(1+)(\1(1)?)
$2x$#3$*-

```

Keep dividing by `2`, rounding up, inserting an `x` each time but also a `-` if the result was rounded up, until the remainder is `1`.

```
1

```

Delete the remaining `1`.

# Answer
> 1 votes
# Japt, ~~7~~ 5 bytes, score: ~~837~~ 835

Uses `1` for `x` and `0` for `-`.

```
´¢rTA

```

Try it (footer converts output to `x`s and `-`s) or run all test cases

```
´¢rTA     :Implicit input of integer U
´         :Prefix decrement the U that's contained in the next shortcut
 ¢        :Convert U to binary string
  r       :Replace
   T      :  0 with
    A     :  10

```

# Answer
> 1 votes
# 05AB1E, 6 bytes, score 836

```
<b0T.:

```

Port of most other answers.
Outputs `1` for `x` and `0` for `-`.

Try it online.

Would be **11 bytes** if we'd use `x-` instead:

```
<b0T.:T„x-‡

```

Try it online.

Or alternatively:

```
<bε_>„x-s∍?

```

Try it online.

**Explanation:**

```
<            # Decrease the (implicit) input by 1
 b           # Convert it to a binary string
  0T.:       # Replace all "0"s with "10"s
             # (after which the result is output implicitly)

<b0T.:       # Same as above
      T„x-‡  # Transliterate "10" to "x-"
             # (after which the result is output implicitly)

<b           # Same as above
  ε          # For-each over each digit:
   _         #  Invert the bit (1 if 0; 0 if 1)
    >        #  Increase it by 1 (2 if 0; 1 if 1)
     „x-     #  Push string "x-"
        s    #  Swap so the earlier integer is at the top of the stack
         ∍   #  Shorten the "x-" string to this length
          ?  #  Pop and output it without trailing newline

```

# Answer
> 0 votes
# A0A0, 186 161 152 bytes + 5841 output = 6027 6012 6003

```
P50P45
P50P50
P50P45
P45P50
P50P50
G-5I0A3V0G0P45S1A0
G-1A0A0
A0C3G1G1A0
A0L100S2M6
A0A1G-3G-3A0
G-3
A0A0
G1G1A0C3G1G1A0
G-4A0G-4A0
A1G-3G-3A0A1G-3G-3A0

```

We're making use of the fact that the challenge doesn't require us to give a shortest length sequence, just *a* sequence. For a language like A0A0, any math operation more fancy than multiplication already gets annoying to implement, so no complicated stuff here. Instead we generate a sequence by first going up to one hundred (with the sequence `xxx-x-x-xx`) and then just going down by one repeatedly until we hit the right number.

This penalizes us heavily in the output score, but it saves a lot of work in the actual code. (It does make for an even worse phone entry screen, though, so there's that.)

```
P50P45
P50P50
P50P45
P45P50
P50P50
G-5

```

This prints `222-2-2-22`. I chose a different character than `x` (allowed per the challenge), since `x` has an ascii value of 120, which is three characters, whereas `2` is only two characters (ascii value 50). You could technically do unprintable ascii values to get into the single digits, but in my opinion that is a bit against the spirit of the question. This is split across two columns, which gives the same amount of bytes as a single column, but two columns makes it easier to read on this site.

```
I0 A3 V0 G0 P45 S1 A0
G-1 A0  A0
    A0  C3   G1  G1  A0
    A0  L100 S2  M6
    A0  A1   G-3 G-3 G-3 A0
    G-3

```

We now need to loop. We first take the input, so we can generate the right amount of dashes for the sequence. We then put this in the operand and append this operand, as well as the rest of the instructions into the loop below. This completes a loop that loops starting from the input until the value one hundred and prints a dash every single time. These are the actual instructions in the loop.

```
L100 S2 M6 V0 G0 P45 S1
L100                    ; compare the operand to value one hundred, store result in operand
     S2                 ; add two to the operand
        M6              ; multiple the operand by six
           V0           ; the operand
              G0        ; goto the offset of the operand
                 P45    ; print a dash
                     S1 ; add one to the operand

```

The jumping always jumps to either the loop below it, or to nothing which halts the program. The loop below simply jumps back up to this loop.

```
A0  A0
G1  G1  A0  C3  G1  G1  A0
G-4 A0  G-4 A0
A1  G-3 G-3 A0  A1  G-3 G-3 A0

```

This is the loop that jumps back up to the first loop. It looks a bit weird, but that's because this loop doesn't do anything other than jump back up top, so we can manually evaluate the loop until it gets into a position that has the shortest amount of bytes. This configuration saves one byte from the next best configuration and thirteen bytes compared to the worst configuration.

Once the value is equal to one hundred (or greater, but that will never happen), the loop will jump down to a place beyond this loop which is empty and will thus halt the program.

Edit: Optimized by 15 bytes. I misunderstood the default loop template I make use of in the code. I was under the impression that the amount of G1 and G-3 instructions on line 2 and 4 of the loop resp. needed to match the amount of instructions inside the loop. This is not the case, you only need two of them (although more also work, as long as each line has an equal amount of them). This change removes these extra instructions.

Edit 2: Optimized by 9 bytes. Because of edit two, it turns out that there's actually no minimum of three instructions in the loop. This allows us to drop three instructions, totalling nine bytes.

# Answer
> 0 votes
# Haskell, 50 bytes

```
g 1=""
g n|(d,m)<-divMod n 2="x-"!!m:g([d,n+1]!!m)

```

Attempt This Online!

String is outputted in reverse.

---
Tags: math, code-challenge
---


# Question
Title: Manufactoria: generate the slowest possible accepting program
Write a Manufactoria program that will accept the empty input tape. But don't do it quickly! I mean, write the program quickly, but don't let it run quickly. The slower the program, the better, as long as it terminates eventually. The example program below takes 3:51 (the "total time" reported by the simulator).

http://pleasingfungus.com/Manufactoria/?lvl=36&code=g12:5f3;r9:8f1;p12:9f3;c13:9f0;r11:9f0;r10:9f0;r9:9f1;b11:8f0;b10:8f1;r9:7f2;c10:7f2;c11:7f2;c12:7f3;q12:8f3;y13:8f2;y14:8f2;y15:8f1;y15:7f0;y14:7f0;y13:7f0;g12:6f3;&ctm=Slow\_Accepter!;Generate\_the\_slowest\_possible\_accepting\_machine;:;7;3;0;

Your program starts with the empty tape. It must doodle around a bit, but eventually reach the output square. You may leave data on the tape if you wish. The slowest program on the 7x7 Manufactoria board wins!

Your right arrow key is your friend, it speeds up the simulator.

Bonus points for crashing the simulator!

# Answer
## ~1023 iterations ~~~1015 iterations~~ ~~~108 iterations~~

http://pleasingfungus.com/Manufactoria/?lvl=32&code=g9:7f2;b12:8f2;p13:8f5;p11:8f3;r14:8f0;q11:10f3;q13:7f1;y13:9f1;r10:10f1;c12:9f2;c9:9f2;i11:9f7;i10:9f4;c9:8f3;i10:8f2;c14:9f0;c15:9f0;c15:8f3;c15:7f3;c14:7f2;g12:7f0;c11:7f3;c10:7f2;q9:6f7;r10:6f1;r9:5f3;c11:6f0;r10:5f2;r11:5f1;r9:4f3;r10:4f0;r11:4f0;y12:5f2;y13:5f2;y14:5f3;y14:6f0;y13:6f0;y12:6f0;&ctm=Slow\_Accepter!;Generate\_the\_slowest\_possible\_accepting\_machine;:;7;3;0;

The machine is basically an odometer running in base three, using the red, blue and yellow symbols to stand for the digits 0, 1, and 2 respectively. The green symbol is used to mark the end of the number. At the start, the tape is initialized with 49 red symbols. This is done by the parts in the top three rows of the machine. The bottom four rows handle the task of incrementing the number in a loop. On each iteration, the two branch cells on left-hand side work out how to apply the increment to current number, and then the branch cells on the right-hand side copy the remaining, unaffected digits.

Previously I've tried to estimate the machine's running time, were it allowed to run to completion, but at this level it makes more sense to just go by the number of iterations. Roughly speaking, it takes about a minute to complete one iteration -- but even if it took a second that would only decrease the running time by a single order of magnitude.
> 22 votes

# Answer
## 603:25

Online test

I was re-reading through the Manufactoria questions today, and suddenly had an idea which would dramatically slow down the process: instead of just having 50 values and changing colours 3 times, the new program does that, but then after that, it decrements the number of values by 1, and goes through the colour-changing again, until there is an empty tape at which time the program stops.

The queue won't store any more than 50 values at one time, so there's no use trying to push too many values onto the tape - they just get pushed off straight away. As before, the conveyor belts aim to maximise the time taken for the thing to run. In fact, there was minimal tweaking down to achieve a tremendous increase in run-time.

Still nowhere near breadbox's answer though.
> 8 votes

# Answer
# 33:33

Worked on this for quite a while (Volatility set the bar pretty high), but once I hit 33:33, I thought it was a neat time to stop at.

The strategy is pretty blunt: basically fill up the tape with one colour, then another, then another, and always try to traverse as many cells as possible between each write (or group of writes).

I'm sure there are ways to be found that we can go a lot further with this.

Level link
> 5 votes

# Answer
# 3^49\*c in 5x5

```
?lvl=33&code=c10:7f2;c10:8f1;r10:9f2;i11:7f7;p11:8f3;q11:9f5;r12:6f0;y12:7f2;b12:8f2;r13:6f0;q13:7f3;p13:8f5;r13:9f1;r14:7f1;r14:8f3;r14:9f0;r14:6f1;r14:5f0;r13:5f3;i11:6f6;c10:6f1;c10:5f2;g11:5f3;&ctm=Long_Runtime;Level_description!;:*;5;3;0;

```
* Red = 0
* Blue = 1
* Yellow = 2
* After a few cycles, tape is full and, erasing one red add at most one red, the red path(right-up) do nop
* Left-top circle only add some cycles
> 0 votes

---
Tags: manufactoria, busy-beaver
---


# Question
Title: Advent Challenge 2: The Present Vault Raid!
\<\< Prev Next \>\>

# Challenge

Now that Santa has finally figured out how to get into his present vault, he realises that somehow the elves got in there before him and stole some of his presents! They haven't figured out how to leave the vault yet though, so Santa has to try and catch them all. Santa and the elves both have infinite energy to run around but unfortunately the elves have a higher infinity of energy, so if they end up running in loops everywhere, the elves have gotten free.

Given a graph of `n` nodes and `e` edges with a walk existing between any two nodes, and the positions of the elves and Santa, determine how many elves Santa can catch before he gets tired.

The chase is turn-based. Each cycle, the elves first all move simultaneously (they can move through each other and onto the same node as well), and then Santa will move. If Santa moves onto the same node as an elf, then he has caught that elf. Each elf may only move from one node to its neighbour in one step. The same goes for Santa in the beginning, but for every elf he has caught, Santa can take one extra step. So, if Santa has caught an elf, then he can move from a node to its neighbour's neighbour. This means he could move to a node and then back. However, since Santa is running too quickly during this time period, he will not catch any elves that passes in the intermediate steps (so if he is on A, A is connected to B, B is connected to C, there is an elf on B, and Santa moves from A -\> B -\> C, the elf has not yet been caught). However, Santa doesn't have to move that many steps at once; he moves up to 1 + (number of elves caught) each turn.

Note that all of the elves must move each turn, and if an elf moves onto Santa's node, they get caught.

All entities (elves, Santa) will be on distinct nodes in the beginning.

# Specifications and Rules

Your program should theoretically work for input of any size. The input will be given as a graph, the positions of the elves, and the position of Santa. You may take the graph in any reasonable format (list of nodes + list of edges, list of edges, adjacency matrix, cycle notation, etc), and you may take the positions in any reasonable format that works with your graph input format (index in the list of nodes, etc). The output should be a single positive integer indicating the maximum number of elves that Santa can catch.

# Test Cases

These are given as lists of edges and node numbers for positions.

```
Input -> Output
[(0, 1), (1, 2)], [0, 2], 1 -> 2 # Easy win for Santa, the elves get themselves caught :P
[(0, 1), (1, 2), (2, 3), (3, 0)], [0, 1], 2 -> 2 # The elf opposite of Santa cannot escape but the other one can always just run away each turn, until Santa catches the first elf. Then he can easily just catch the rest.
[(0, 1), (1, 2), (2, 3), (3, 0)], [1], 0 -> 0 # Santa will never catch up
[(0, 1), (1, 2), (2, 3), (3, 0), (1, 4), (4, 5), ..., (10, 11), (11, 3)], [2, 6], 0 -> 2 # The first elf moves to either 1 or 3 and then gets caught. Then, Santa can use his 2-step move to catch up to the second elf no matter what.

```

I think Santa can catch either no elves or all the elves, so this challenge might just be "can he catch an elf" *hint hint*

# Rules

* Standard Loopholes Apply
* This is a challenge, so the shortest answer in bytes wins
* No answers will be accepted

Happy Golfing!

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

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

```
Block[{a=#},Clear@f;s_~f~e_:=If[s==e,1,s~f~e=0;s~f~e=Min[(hMax[#~f~h&/@a@s,Boole[h==s]])/@a@e]];Tr[Max[(e#3~f~e)/@#2]^#2]]&

```

Try it online!

Similar approach to my answer to this question.

The function takes 3 arguments as input: adjacency list represented as an association (tool to generate adjacency list from edge list), elves position and santa position.

Note that `Clear[f]` is necessary, because function submissions must be reusable.

The code below is ungolfed code with partial explanation. More explanation later.

```
reverseBoole = # != 0 &

(* Or@@{a, b} === reverseBoole[booleOr[Boole[{a, b}]]] *)
booleOr = Max

booleAnd = Min

(* Boole@f[s, e] = Santa can catch Elf ? *)

mainfunc = Block[{adjlist = #},
  Clear[f];
  f[s_, e_] := If[ s == e, f[s, e] = 1,
    f[s, e] = Boole[False];
    f[s, e] = booleAnd[
      (e1  booleOr[
        ( s1  f[s1, e1] ) /@ adjlist[s],
        Boole[e1 == s]
      ]) /@ adjlist[e]
    ]
  ];
  If [ 0 == booleOr[ ( e  f[#3, e] ) /@ #2 ] , 0, Length[#2] ]
]&

```

---

# Answer
> 0 votes
# Python3, 691 bytes

```
R=range
def T(g,s):
 q=[[s]]
 while q:A=q.pop(0);yield(l:={b for i in A for a,b in g if a==i});q+=[l]
def f(g,e,s):
 q,a,D,v=[(e,0,s,0)],[(e,s)],{},[]
 while q:
  E,c,S,B=q.pop(0);v+=[B]
  if c<len(E):
   if E[c]==-1:q+=[(E,c+1,s,B)];continue
   J=1
   for i in next(T(g,E[c])):
    O=[*E];J=0
    if i!=S:
     O[c]=i
     if(O,S)not in a:J=0;q+=[(O,c+1,S,B)]
    else:O[c]=-1;q+=[(O,c+1,S,B+1)]
   if J:q+=[(O,c+1,S,B)]
  else:
   t,L=T(g,S),0
   for i in R(max(sum(k==-1for k in E)+1,1)):
    for I in R(L,i+1):M=next(t)
    L=i+1
    for I in M:
     O=[*E];x=B
     for y in R(len(E)):G=O[y]==I;O[y]=[O[y],-1][G];x+=G;v+=[x]
     if(O,I)not in a:q+=[(O,0,I,x)];a+=[(O,I)]
 return max(v)

```

Try it online!

Also, a 808 byte solution that uses caching for faster execution: try it online

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


title: Add two natural numbers

text:
# Question
Title: Add two natural numbers
Given two natural numbers (less than 100) as input print the sequence of intermediate results obtained when computing the sum of the two numbers using only the following operations1:

* `n <-> (m+1)` for integers `n`and `m` satisfying that equation
* `(a+b)+c <-> a+(b+c)` for integers `a`,`b` and `c` (associative law)

*You are **not** allowed to use the commutative law (swapping the arguments of `+`)*

## Example

```
5+3           # Input
5+(2+1)       # 3 = 2+1
(5+2)+1       # Associative law
(5+(1+1))+1   # 2 = 1+1
((5+1)+1)+1   # Associative law
(6+1)+1       # 5+1 = 6
7+1           # 6+1 = 7
8             # 7+1 = 8

```

## Rules

* Input: two natural numbers (positive integers)
* Output list of all intermediate steps in the calculation of the sum (using the rules defined above), you may omit the final result
* The expressions can be output in any reasonable format (the left and right operands of each `+` should be clearly determinable)
* You can choose the order in which the operations are applied as long as you reach the final result
* Each expression in the output has to be obtained from the previous expression by applying **exactly one** allowed operation to the previous operation
* This is the shortest code wins

## Test cases

infix notation:

```
2+2 -> 2+(1+1) -> (2+1)+1 -> 3+1 -> 4
3+1 -> 4
1+3 -> 1+(2+1) -> 1+((1+1)+1) -> (1+(1+1))+1 -> ((1+1)+1)+1 -> (2+1)+1 -> 3+1 -> 4
1+3 -> 1+(2+1) -> (1+2)+1     -> (1+(1+1))+1 -> ((1+1)+1)+1 -> (2+1)+1 -> 3+1 -> 4
5+3 -> 5+(2+1) -> (5+2)+1     -> (5+(1+1))+1 -> ((5+1)+1)+1 -> (6+1)+1 -> 7+1 -> 8

```

postfix notation:

```
 2 2+ -> 2 1 1++ -> 2 1+ 1+ -> 3 1+ -> 4
 3 1+ -> 4
 1 3+ -> 1 2 1++ -> 1 1 1+ 1++ -> 1 1 1++ 1+ -> 1 1+ 1+ 1+ -> 2 1+ 1+ -> 3 1+ -> 4
 1 3+ -> 1 2 1++ -> 1 2+ 1+    -> 1 1 1++ 1+ -> 1 1+ 1+ 1+ -> 2 1+ 1+ -> 3 1+ -> 4
 5 3+ -> 5 2 1++ -> 5 2+ 1+    -> 5 1 1++ 1+ -> 5 1+ 1+ 1+ -> 6 1+ 1+ -> 7 1+ -> 8

```

Example implementation

---

1 The operations are based on the formal definition of additon but modified to work without the concept of a successor function.

# Answer
> 7 votes
# Jelly, 22 bytes

```
FṖ.ịoƲ€2¦ṁ¥,/ƭ$ƬṪ§Ƭ;@Ɗ

```

A monadic Link that accepts a pair of positive integers and yields a list of nested lists representing (much like the reference implementation) one way to perform their sum.

**Try it online!**

### How?

```
FṖ.ịoƲ€2¦ṁ¥,/ƭ$ƬṪ§Ƭ;@Ɗ - Link: pair of positive integers, A = [n, m]
               Ƭ       - starting with X=A collect up while distinct under:
              $        -   last two links as a monad - f(X):
F                      -     flatten X
             ƭ         -     alternate between:
          ¥            -     (1) last two links as a dyad - F(Flat_X, X):
      €2¦              -           apply to second element, V, of X:
     Ʋ                 -             last four links as a monad - f(V):
 Ṗ                     -               pop -> [1 .. V-1]        or [] if V == 1
  .                    -               0.5
   ị                   -               index into -> [V-1, 1]   or [] if V == 1
    o                  -               logical OR V -> [V-1, 1] or  V if V == 1
            /          -     (2) reduce Flat_X by:
           ,           -           pair -> ...[[[[a,b],c],d],...]
                     Ɗ - last three links as a monad - f(StepsSoFar):
                Ṫ      -   tail -> removes and yields PreviousStep
                  Ƭ    -   starting with PreviousStep collect up while distinct under:
                 §     -     sums
                   ;@  -   append to the tailed StepsSoFar

```

---

Seems like the sums (`§`) could be performed within the first collect-loop (`Ƭ`), but I've not figured out a good way to do so...

# Answer
> 6 votes
# Python, 98 bytes

```
f=lambda m,n:[f"{m}+{n}"]+([n:=n-1]*n and[f"{m}+({n}+1)",*(f"({x})+1"for x in f(m,n)),f"{m+n}+1"])

```

Attempt This Online!

-1 thanks to @STerliakov

### Original Python, 100 bytes

```
f=lambda m,n:[f"{m}+{n}"]+(n-1and[f"{m}+({n-1}+1)",*(f"({x})+1"for x in f(m,n-1)),f"{m+n-1}+1"]or[])

```

Attempt This Online!

Outputs a list of strings in infix notation.

# Answer
> 4 votes
# Charcoal, 64 bytes

```
ＮθＮηＦ⊖ηＥ²⪫⟦×(ιθ+×(κＩ⁻η⁺ικ×+1)κ×)+1ι⟧ω⮌Ｅη⪫⟦×(ι⁻⁺θη⊕ι+1×)+1ι⟧ωＩ⁺θη

```

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

```
ＮθＮη

```

Input the two numbers.

```
Ｆ⊖ηＥ²⪫⟦×(ιθ+×(κＩ⁻η⁺ικ×+1)κ×)+1ι⟧ω

```

Output the steps that split the second number into units and associate them with the first number.

```
⮌Ｅη⪫⟦×(ι⁻⁺θη⊕ι+1×)+1ι⟧ω

```

Output the steps that add the units to the first number.

```
Ｉ⁺θη

```

Finish with the final sum.

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

```
x=>g=(y,a='',b=`
`)=>(--y?a+x+`+${y+1+b+a+x}+(${y}+1)`+b+g(y,'('+a,')+1'+b)+a:a)+x+++`+1${a?b:b+x}`

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 90 bytes

```
\d+
$*
+`\+1(1+)(.*$)
$&¶$%`+($1+1)$2¶($%`+$1)+1$2
+`\(?(1+)\+1\)?(.*$)
$&¶$%`1$1$2
1+
$.&

```

Try it online! Link is to test suite that outputs all the test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
+`\+1(1+)(.*$)
$&¶$%`+($1+1)$2¶($%`+$1)+1$2

```

Repeatedly convert `x+<1y>` into `x+(y+1)` and then `(x+y)+1` until `y` is `1`.

```
+`\(?(1+)\+1\)?(.*$)
$&¶$%`1$1$2

```

Repeatedly convert `(x+1)` into `<1x>`.

```
1+
$.&

```

Convert to decimal.

# Answer
> 1 votes
# Python, ~~140~~ 137 bytes

```
lambda x,y,a='',b='':(a+f"{x}+{y}{b}\n{a}{x}+({y-1}+1){b}\n{f(x,y-1,'('+a,b+')+1')}\n"if~-y else'')+a+f"{x+y-1}+1{b or chr(10)+str(x+y)}"

```

Attempt This Online!

A port of l4m2's JavaScript answer

# Answer
> 1 votes
# Perl 5 (`-lp`), 135 bytes

```
1while print,s/\+(?!1\b)\d+/"+(".($&-1)."+1)"/e||s/(\d+)\+\((\d+)\+(\d+)\)/($1+$2)+$3/||(s/^[^+\d]*\K(\d+)\+1\b/$1+1/e,s/\((\d+)\)/$1/)

```

Try it online!

# Answer
> 1 votes
# Scala 3, 153 bytes

```
def f(m:Int,n:Int):Seq[String]=n match{case 1=>Seq(s"$m+1");case _=>Seq(s"$m+$n")++Seq(s"$m+(${n-1}+1)")++f(m,n-1).map(x=>s"($x)+1")++Seq(s"${m+n-1}+1")}

```

Attempt This Online!

---
Tags: code-golf, integer
---


title: Sorting rectangular matrices

text:
# Question
Title: Sorting rectangular matrices
Given a matrix `A`, we can say that it is "sorted" if each row and column of `A` is sorted (ascending left-to-right for rows and top-to-bottom for columns). Thus, this matrix is sorted:

```
[ 1 2 3 4 5 ]
[ 2 2 3 4 5 ]
[ 3 3 3 4 5 ]
[ 4 4 4 4 5 ]
[ 5 5 5 5 5 ]

```

However, this matrix is not sorted:

```
[ 1 2 3 4 5 ]
[ 2 1 3 4 5 ]
[ 3 3 3 4 5 ]
[ 4 5 4 5 5 ]
[ 5 5 5 5 5 ]

```

The second column (transpose of `[2, 1, 3, 5, 5]`) and fourth row (`[4, 5, 4, 5, 5]`) are not sorted in ascending order.

Given a matrix (either as a 2D rectangular nested list or a string with consistent, distinct delimiters between rows and between values) and optionally the width and/or height of the matrix, output a sorted matrix (in the same format) with the same dimensions and containing the same values as the input matrix.

The values in the matrix will always be in the inclusive range `[-128, 127]` (8-bit signed two's complement integers). There is no limit on the dimensions of the input matrix.

## Examples

Because there are multiple valid outputs for each input, these are possible outputs. Any output that fulfills the conditions is valid. The examples are given with Python list notation.

```
[[0, -29]] -> [[-29, 0]]
[[-36, -18, 0], [8, 99, 112], [14, 6, -12]] -> [[-36, -18, 0], [-12, 6, 14], [8, 99, 112]]
[[-20, -102, -41, -57, -73, 58], [49, 82, 60, -53, 58, 60], [-32, -127, -23, -70, -46, -108], [-56, -15, 98, -90, 73, -67], [97, 74, 59, 126, -7, 46], [-101, 42, -39, -52, 89, 29]] -> [[-127, -108, -101, -70, -53, -32], [-102, -90, -67, -52, -23, 42], [-73, -57, -46, -20, 46, 59], [-56, -41, -15, 49, 60, 74], [-39, -7, 58, 60, 82, 97], [29, 58, 73, 89, 98, 126]]
[[23, 82, 94, 7, -39, 70, -31, -120], [-13, 78, -70, 28, -10, 30, 101, 48], [60, -111, 32, 93, 91, 77, -27, 7], [-37, -41, -8, 80, 102, 18, -16, -48], [97, -14, -102, -53, 108, -92, -83, 108], [-67, -121, -15, -9, 91, -89, -127, -109], [-127, -103, -48, -2, -106, 3, -114, 97], [28, -78, -40, 52, 39, 115, -88, 10]] -> [[-127, -127, -120, -109, -92, -70, -40, -14], [-121, -114, -106, -89, -67, -39, -13, 7], [-111, -103, -88, -53, -37, -10, 10, 32], [-102, -83, -48, -31, -9, 18, 39, 77], [-78, -48, -27, -8, 23, 48, 78, 91], [-41, -16, -2, 28, 52, 80, 93, 97], [-15, 3, 28, 60, 82, 94, 101, 108], [7, 30, 70, 91, 97, 102, 108, 115]]
[[85, 90, -65, -38, -58, -71, 123, -83, 44], [55, -34, 21, 103, -10, 59, -109, 30, -41], [108, -106, -90, 74, 117, 15, -63, 94, -37], [43, -118, -126, -45, 77, -62, 22, 76, 9], [56, 31, 58, 51, -64, 125, -48, -123, -108], [77, -53, -61, 99, -16, -21, -98, -50, 60], [127, -113, -9, 33, -6, -102, -47, -122, 31], [-59, -23, 0, 21, 14, 61, 83, 47, -6], [97, -120, -111, 113, -68, -128, -81, 68, 88]] -> [[-128, -126, -122, -113, -106, -81, -62, -47, -16], [-123, -120, -111, -102, -71, -61, -45, -10, 21], [-118, -109, -98, -68, -59, -41, -9, 21, 44], [-108, -90, -65, -58, -38, -6, 22, 47, 60], [-83, -64, -53, -37, -6, 30, 51, 61, 77], [-63, -50, -34, 0, 31, 55, 68, 83, 94], [-48, -23, 9, 31, 56, 74, 85, 97, 108], [-21, 14, 33, 58, 76, 88, 99, 113, 123], [15, 43, 59, 77, 90, 103, 117, 125, 127]]
[[-80, -42, 1, 126, -42, -34, 81, 73, 6, 9, 72], [-98, -98, -82, 63, -16, -116, 29, 61, 119, 20, 19], [-99, -70, 41, 44, 117, 61, 89, -117, 92, -3, -49], [18, 122, 126, 84, 79, 114, -61, 45, 80, 109, -107], [-77, 73, -62, -58, -25, -24, 126, -14, -13, -90, -60], [84, 1, 95, 21, -13, 26, 75, 78, -36, -76, -91], [54, -58, 79, -128, 63, 119, 79, 106, 103, 125, 98], [126, 37, -77, -15, -57, 63, 22, -98, 93, 67, 41], [93, -45, -91, 34, 29, -38, -103, 109, -92, 6, -115], [32, -112, -29, -65, 61, 20, 80, -41, -68, 28, 25], [56, -112, 47, -88, 56, -35, -26, 13, 122, 27, -70], [108, -69, -42, 24, 94, -20, -46, 90, -98, 112, 32]] -> [[-128, -117, -115, -107, -98, -91, -77, -62, -45, -29, -3], [-116, -112, -103, -98, -90, -76, -61, -42, -26, 1, 21], [-112, -99, -98, -88, -70, -60, -42, -25, 1, 22, 34], [-98, -92, -82, -70, -58, -42, -24, 6, 24, 37, 61], [-91, -80, -69, -58, -41, -20, 6, 25, 41, 61, 73], [-77, -68, -57, -38, -16, 9, 26, 41, 61, 75, 81], [-65, -49, -36, -15, 13, 27, 44, 63, 78, 84, 93], [-46, -35, -14, 18, 28, 45, 63, 79, 84, 94, 108], [-34, -13, 19, 29, 47, 63, 79, 89, 95, 109, 117], [-13, 20, 29, 54, 67, 79, 90, 98, 109, 119, 122], [20, 32, 56, 72, 80, 92, 103, 112, 119, 125, 126], [32, 56, 73, 80, 93, 106, 114, 122, 126, 126, 126]]
[[53, 109, -41, 66, 63, -108, -24, 85, 28, 57, -11, -94, -16], [-28, -113, 58, 115, -28, -124, 71, -109, -65, 45, 75, 97, 107], [124, 23, 101, 112, -64, 19, 21, 34, 6, -2, -70, -92, 122], [19, 94, 80, -105, -3, -125, -2, 44, -24, 41, -30, 64, 32], [36, -44, 59, -28, -36, -11, 111, -64, 78, 120, 1, 102, 49], [-128, 67, 17, -9, -64, -86, 117, 7, 118, 7, -11, -82, 124], [5, -36, 22, 98, -78, -33, 100, 92, -55, 125, -28, 24, -6], [97, 31, -106, -15, 8, 80, -86, -107, -105, -5, -71, 76, 124], [-83, 24, -116, 66, 82, -32, -19, 111, -84, -77, -14, 67, -70], [77, -111, -101, -91, -23, 36, 24, -33, 13, -90, -9, 32, -54], [51, -31, 125, -25, -61, 5, 71, -81, -3, -39, 109, -17, -97], [61, -46, -122, 76, 13, -101, 24, 97, 39, -29, -22, -3, -116], [56, 0, -4, 71, -116, 115, 79, -83, 74, 44, -77, 42, -30], [-72, 45, -109, -82, 43, 38, -117, 1, 69, -66, -18, 108, 8]] -> [[-128, -125, -122, -116, -109, -105, -92, -83, -71, -55, -32, -24, -9], [-124, -117, -116, -109, -105, -91, -82, -70, -54, -31, -23, -9, 5], [-116, -113, -108, -101, -90, -82, -70, -46, -30, -22, -6, 5, 22], [-111, -107, -101, -86, -81, -66, -44, -30, -19, -5, 6, 23, 36], [-106, -97, -86, -78, -65, -41, -29, -18, -4, 7, 24, 38, 51], [-94, -84, -77, -64, -39, -28, -17, -3, 7, 24, 39, 53, 66], [-83, -77, -64, -36, -28, -16, -3, 8, 24, 41, 56, 67, 76], [-72, -64, -36, -28, -15, -3, 8, 24, 42, 57, 67, 76, 85], [-61, -33, -28, -14, -2, 13, 28, 43, 58, 69, 77, 92, 100], [-33, -25, -11, -2, 13, 31, 44, 59, 71, 78, 94, 101, 109], [-24, -11, 0, 17, 32, 44, 61, 71, 79, 97, 102, 111, 115], [-11, 1, 19, 32, 45, 63, 71, 80, 97, 107, 111, 117, 122], [1, 19, 34, 45, 64, 74, 80, 97, 108, 112, 118, 124, 124], [21, 36, 49, 66, 75, 82, 98, 109, 115, 120, 124, 125, 125]]
[[47, -58, 7, -88, 126, -87, 103, 125, 83, 32, 116, 107, -92, -96, 110, -102], [-75, -81, 53, -93, 91, -5, -4, 104, 88, -73, -114, -113, 126, 78, -114, -3], [125, -68, -88, -17, 1, 53, -124, -59, -19, 87, -60, 55, -30, -6, 39, 37], [-38, -123, 125, 119, -43, 11, -25, -89, -57, 112, 123, 9, -76, -125, 118, 68], [-119, -97, -42, 73, 80, 108, -96, -54, -110, 115, -58, -67, -9, 94, 71, -56], [-25, 109, -51, 71, 61, 12, 122, -99, -16, -87, -127, -76, 46, 102, 52, 114], [97, 26, -112, 49, -44, -26, -93, -119, 21, 101, 83, -112, 14, 41, 120, 37], [90, 95, 89, 73, 51, -33, 3, -125, -106, -83, -5, -26, 33, -119, -74, 41], [9, -81, 116, -124, -8, -15, 65, 104, 41, -92, 2, 51, 33, 115, -47, 30], [87, -127, 121, 42, 33, -22, 28, -74, 26, 55, 126, -70, 0, -63, -40, -51], [-117, 79, -113, -4, 78, -33, -54, -40, -1, -48, 60, 91, 119, 117, -75, 114], [7, 102, 6, 77, -112, -128, 34, 112, -82, -17, -120, -96, -101, -79, -27, -84], [-74, -77, 67, -78, -72, 80, 59, 115, -76, -7, 66, -28, 120, 117, 56, -46], [80, 42, -121, -5, 73, -82, -115, -72, 10, -120, -26, -82, -22, 110, -7, -119], [10, -88, 39, 92, -16, 58, -40, 79, 116, 75, 96, -102, 4, 93, 46, -95], [20, -61, 110, 18, -103, -87, -67, -26, -74, -22, 1, -106, -81, -20, 10, 87]] -> [[-128, -127, -125, -124, -120, -117, -112, -102, -95, -87, -81, -74, -59, -43, -26, -7], [-127, -125, -123, -119, -115, -112, -102, -93, -87, -79, -74, -58, -42, -25, -7, 6], [-124, -121, -119, -114, -112, -101, -93, -87, -78, -73, -58, -40, -25, -6, 7, 26], [-120, -119, -114, -110, -99, -92, -84, -77, -72, -57, -40, -22, -5, 7, 28, 41], [-119, -113, -106, -97, -92, -83, -76, -72, -56, -40, -22, -5, 9, 30, 42, 55], [-113, -106, -96, -89, -82, -76, -70, -54, -38, -22, -5, 9, 32, 42, 56, 73], [-103, -96, -88, -82, -76, -68, -54, -33, -20, -4, 10, 33, 46, 58, 73, 80], [-96, -88, -82, -75, -67, -51, -33, -19, -4, 10, 33, 46, 59, 73, 83, 91], [-88, -81, -75, -67, -51, -30, -17, -3, 10, 33, 47, 60, 75, 83, 92, 102], [-81, -74, -63, -48, -28, -17, -1, 11, 34, 49, 61, 77, 87, 93, 103, 110], [-74, -61, -47, -27, -16, 0, 12, 37, 51, 65, 78, 87, 94, 104, 110, 115], [-60, -46, -26, -16, 1, 14, 37, 51, 66, 78, 87, 95, 104, 112, 115, 117], [-44, -26, -15, 1, 18, 39, 52, 67, 79, 88, 96, 107, 112, 116, 118, 120], [-26, -9, 2, 20, 39, 53, 68, 79, 89, 97, 108, 114, 116, 119, 121, 125], [-8, 3, 21, 41, 53, 71, 80, 90, 101, 109, 114, 116, 119, 122, 125, 126], [4, 26, 41, 55, 71, 80, 91, 102, 110, 115, 117, 120, 123, 125, 126, 126]]
[[-88, -62, -59, -18, 118, -13, -93, 75, 44, 67, -122, -1, 117, -121, 118, 13, -33, 44], [-4, -75, 95, 25, 9, -104, 6, 79, -110, 3, -108, 117, 96, 113, 69, 55, 75, -95], [-69, 11, 87, -78, -18, -17, -52, 6, 88, 31, 39, 45, 61, -75, -83, 117, 85, -3], [-27, 83, -86, -69, -29, -15, 62, -90, -127, 53, -71, 77, -95, -86, -20, 69, 103, -111], [3, -6, -70, -121, -58, -72, 88, 105, 68, -31, 86, -28, 69, 78, 13, 88, 19, 75], [69, 73, 116, -2, -93, 15, 74, 58, 98, -100, -54, 95, 47, -126, -71, 63, 84, 113], [110, -42, -33, -87, 109, 86, -75, 25, 83, -25, -76, 84, -42, -57, -93, -9, -90, 3], [-100, 36, -83, 10, -85, 88, -15, 107, -76, -37, 109, 79, -120, 118, -60, 113, -124, -15], [123, 122, -94, 14, -16, 118, -57, -111, 80, 62, 56, 66, 27, -44, -53, -13, 94, -28], [116, -67, 8, -70, -54, -1, 53, 40, -78, 15, -121, -30, -125, -16, -74, 119, 97, 43], [-24, 109, -72, 16, 55, -51, -87, 46, -62, 69, -106, -49, -112, 71, -55, 104, -110, 62], [67, 13, -75, 106, -35, -54, 15, -104, 34, 93, 39, -126, -29, 61, 29, 4, 70, -28], [27, -89, -15, -32, -82, -72, 53, -22, -23, 49, -16, 76, -25, 31, 115, -88, -57, -97], [1, 29, 54, 88, 86, 77, -58, 100, -125, 117, 102, 41, 99, 115, 24, -16, -99, -116], [-85, -47, -108, 26, 18, -107, -88, 110, 27, -118, 88, -122, -85, -94, -33, 51, 40, 77], [-3, 52, -20, 12, 117, 101, 34, -8, -100, -23, 45, 83, -88, -90, -47, 70, 29, -111], [26, -68, 7, 38, -118, -53, -79, -48, 41, -88, 35, 86, 66, 24, 37, 72, -66, -77]] -> [[-127, -126, -125, -122, -121, -112, -108, -100, -93, -88, -83, -75, -68, -54, -37, -25, -15, 4], [-126, -125, -122, -120, -111, -108, -100, -93, -88, -83, -75, -67, -54, -35, -24, -15, 6, 18], [-124, -121, -118, -111, -107, -99, -93, -88, -82, -74, -66, -54, -33, -23, -13, 6, 19, 34], [-121, -118, -111, -106, -97, -90, -87, -79, -72, -62, -53, -33, -23, -13, 7, 24, 34, 45], [-116, -110, -104, -95, -90, -87, -78, -72, -62, -53, -33, -22, -9, 8, 24, 35, 45, 58], [-110, -104, -95, -90, -86, -78, -72, -60, -52, -32, -20, -8, 9, 25, 36, 46, 61, 69], [-100, -94, -89, -86, -77, -71, -59, -51, -31, -20, -6, 10, 25, 37, 47, 61, 69, 75], [-94, -88, -85, -76, -71, -58, -49, -30, -18, -4, 11, 26, 38, 49, 62, 69, 76, 83], [-88, -85, -76, -70, -58, -48, -29, -18, -3, 12, 26, 39, 51, 62, 69, 77, 84, 88], [-85, -75, -70, -57, -47, -29, -17, -3, 13, 27, 39, 52, 62, 70, 77, 84, 88, 96], [-75, -69, -57, -47, -28, -16, -2, 13, 27, 40, 53, 63, 70, 77, 85, 88, 97, 104], [-69, -57, -44, -28, -16, -1, 13, 27, 40, 53, 66, 71, 78, 86, 88, 98, 105, 110], [-55, -42, -28, -16, -1, 14, 29, 41, 53, 66, 72, 79, 86, 88, 99, 106, 110, 115], [-42, -27, -16, 1, 15, 29, 41, 54, 67, 73, 79, 86, 93, 100, 107, 113, 116, 117], [-25, -15, 3, 15, 29, 43, 55, 67, 74, 80, 86, 94, 101, 109, 113, 116, 117, 118], [-15, 3, 15, 31, 44, 55, 68, 75, 83, 87, 95, 102, 109, 113, 117, 117, 118, 119], [3, 16, 31, 44, 56, 69, 75, 83, 88, 95, 103, 109, 115, 117, 118, 118, 122, 123]]
[[84, 18, -122, 74, -47, 17, -69, 121, -79, 110, 10, 122, 84, 19, 77, -57, 25, 87, -42], [95, 89, 10, -1, -24, -93, -26, -39, 11, -15, 47, 23, 114, 36, 121, -87, 106, 120, -86], [48, 66, 65, 28, 74, -22, -67, 77, -77, 19, 88, -24, -88, 85, -34, 13, 103, -102, 86], [108, -17, -122, -13, 63, 61, -56, 24, -48, -3, -85, -57, 11, -52, -26, -24, 48, 100, 18], [-91, -126, 124, 5, -118, 93, 94, -100, -24, 15, 77, -43, 64, 51, 64, 7, -22, -47, 79], [98, 80, 117, -19, -55, -95, -35, -48, -56, -122, -120, 52, 54, 37, -101, -38, -35, 101, -6], [72, 68, 26, -79, -1, 25, -3, -40, 2, 56, 119, 17, -95, 83, -94, -79, -88, -110, 85], [55, 39, 75, 127, 110, 0, 56, -1, 39, 116, 44, 120, -113, 81, 113, 10, 78, 114, -79], [103, 121, 78, -121, -17, 33, 117, 110, -26, 2, -79, 27, -117, 62, -27, -17, -20, 104, 115], [-11, 67, 76, 62, -14, 78, -94, -8, -71, 15, 77, 98, 127, 109, 61, 33, -51, 65, -103], [-91, 97, 83, -61, 22, -31, 20, -119, 40, -48, -3, 34, -70, 23, -80, -73, 5, 23, -102], [109, 78, 124, 118, -39, -3, -114, -50, 0, 79, -68, -34, -96, 104, -120, 41, 2, 108, -17], [-90, -30, -25, -29, -52, -37, -49, 20, 91, -48, -91, 80, -117, -6, -88, -68, 69, 103, 118], [-79, -118, -122, -112, 71, -4, 28, 78, -77, -33, 10, 21, -125, 69, -88, 18, 99, 11, -127], [-124, -53, -4, 80, -94, -44, -124, 94, 97, -55, -89, -78, -37, -38, -40, -11, -116, 84, 18], [44, 32, -44, 76, -101, 85, -67, 69, -4, 20, -89, -103, 117, 18, -121, 84, 18, -91, -106], [107, 58, 6, -72, 112, 96, 39, 77, -4, 104, 60, 112, 39, -102, -4, -11, 80, 36, -117], [96, -79, 119, -65, 80, -35, -60, 4, -63, 92, 76, -46, -2, 59, -86, -105, -76, 106, -102], [-88, -89, 69, -5, 63, 75, -59, -93, 101, 33, 64, 114, -126, -106, 33, 113, 50, 71, 82], [-94, 9, -3, 11, 115, -121, 111, -34, -11, 96, -34, 51, -44, -56, -20, -14, 1, 49, 100]] -> [[-127, -126, -125, -122, -121, -119, -116, -105, -101, -93, -88, -79, -71, -57, -48, -38, -26, -14, -3], [-126, -124, -122, -121, -118, -114, -103, -100, -93, -88, -79, -70, -56, -48, -37, -26, -14, -3, 10], [-124, -122, -121, -118, -113, -103, -96, -91, -88, -79, -69, -56, -47, -37, -25, -13, -3, 10, 19], [-122, -120, -117, -112, -102, -95, -91, -88, -79, -68, -56, -47, -35, -24, -11, -2, 10, 19, 33], [-120, -117, -110, -102, -95, -91, -88, -79, -68, -55, -46, -35, -24, -11, -1, 10, 20, 33, 48], [-117, -106, -102, -94, -91, -87, -79, -67, -55, -44, -35, -24, -11, -1, 11, 20, 33, 48, 62], [-106, -102, -94, -90, -86, -78, -67, -53, -44, -34, -24, -11, -1, 11, 20, 33, 49, 62, 69], [-101, -94, -89, -86, -77, -65, -52, -44, -34, -22, -8, 0, 11, 21, 34, 50, 63, 71, 77], [-94, -89, -85, -77, -63, -52, -43, -34, -22, -6, 0, 11, 22, 36, 51, 63, 71, 77, 80], [-89, -80, -76, -61, -51, -42, -34, -20, -6, 1, 13, 23, 36, 51, 64, 72, 78, 81, 86], [-79, -73, -60, -50, -40, -33, -20, -5, 2, 15, 23, 37, 52, 64, 74, 78, 82, 87, 96], [-72, -59, -49, -40, -31, -19, -4, 2, 15, 23, 39, 54, 64, 74, 78, 83, 88, 96, 101], [-57, -48, -39, -30, -17, -4, 2, 17, 24, 39, 55, 65, 75, 78, 83, 89, 97, 103, 107], [-48, -39, -29, -17, -4, 4, 17, 25, 39, 56, 65, 75, 78, 84, 91, 97, 103, 108, 111], [-38, -27, -17, -4, 5, 18, 25, 39, 56, 66, 76, 79, 84, 92, 98, 103, 108, 112, 114], [-26, -17, -4, 5, 18, 26, 40, 58, 67, 76, 79, 84, 93, 98, 104, 109, 112, 115, 117], [-15, -3, 6, 18, 27, 41, 59, 68, 76, 80, 84, 94, 99, 104, 109, 113, 115, 118, 120], [-3, 7, 18, 28, 44, 60, 69, 77, 80, 85, 94, 100, 104, 110, 113, 116, 118, 120, 121], [9, 18, 28, 44, 61, 69, 77, 80, 85, 95, 100, 106, 110, 114, 117, 119, 121, 122, 124], [18, 32, 47, 61, 69, 77, 80, 85, 96, 101, 106, 110, 114, 117, 119, 121, 124, 127, 127]]

```

Huge thanks to Sp3000 for helping me out with this challenge in chat

# Answer
# Jelly, 3 bytes

```
FṢs

```

Takes matrix and width as left and right arguments. Try it online!

### How it works

```
FṢs  Main link. Arguments: M (matrix), w (width)

F    Flatten M.
 Ṣ   Sort.
  s  Split into rows of width w.

```
> 6 votes

# Answer
## Retina, ~~8~~ ~~6~~ 5 bytes

*Thanks to randomra for saving 3 bytes.*

```
O#`.+

```

Input format is a bit awkward. Both the delimiter within rows and between rows needs to consist of line-terminating characters (i.e. those not matched by `.`). E.g. you could use single linefeeds within rows and double linefeeds between rows. Output is printed in the same format.

Try it online!

### Explanation

The perfect challenge to show off Retina's latest addition: sort stages!

Sort stages work as follows: the regex is matched against the entire string. The matches are then the things that are being sorted, whereas everything around them is treated as "list delimiters" and left unchanged. This challenge can be solved if we treat the input as a flat list, sort that and reshape it into the original matrix form. That's exactly how sort stages work, except there are no explicit steps for flattening and reshaping - Retina just ignores the 2D structure altogether.

As for this code in particular, the regex is `.+` which simply matches all runs of non-linefeed characters, which is all the numbers due to the input format. By default, the matches are sorted lexicographically, but the `#` option tells Retina to sort them numerically (by the first signed integer that appears in the match).

For three additional bytes, this could support any input format whatsoever, by using the regex `-?\d+`.
> 12 votes

# Answer
# Pyth, ~~6~~ 5 bytes

*1 byte thanks to DenkerAffe*

```
cSsQE

```

Demonstration

Input is the matrix, followed by its width.

To sort the matrix, I simply flatten it into a list, sort the list, and chop it into a matrix again. Since every subsequence of a sorted list is sorted, this results in a sorted matrix.
> 10 votes

# Answer
## Python, 43 bytes

```
lambda M:eval("map(sorted,zip(*"*2+"M))))")

```

The interesting question is how to apply `mapsort-transpose` twice. The shortest I found was to `eval` a string that has it twice. Compare some alternatives:

```
lambda M:eval("map(sorted,zip(*"*2+"M))))")
lambda M:map(sorted,zip(*map(sorted,zip(*M))))
s="map(sorted,zip(*%s))";lambda M:eval(s%s%M)
g=lambda M:map(sorted,zip(*M));lambda M:g(g(M))
f=lambda M,n=-1:n*M or f(map(sorted,zip(*M)),n+1)
def f(M):exec"M=map(sorted,zip(*M));"*2;return M

```

(The second and fourth can be shortened by 1 byte by aliasing `sorted`, but it's not enough.)

An alternative approach of converting to 1D, sorting, and reshaping to 2D, is very close, at 44 bytes. The width `w` is taken as an input.

```
lambda M,w:zip(*[iter(sorted(sum(M,[])))]*w)

```
> 6 votes

# Answer
# Pyth, 7 bytes

```
CSMCSMQ

```

Try it here!

First we sort all rows of the matrix, transpose the result, sort all rows again and transpose it back.
> 2 votes

# Answer
# CJam, 8 bytes

```
{:$z:$z}

```

Try it online!

An unnamed block which expects a matrix on the stack and leaves the sorted matrix on the stack.

Also just sorts each row (`:$`), transposes the result (`z`), sorts again and transposes it back.
> 2 votes

# Answer
## JavaScript (ES6), 67 bytes

```
a=>a.map(b=>c.splice(0,b.length),c=[].concat(...a).sort((d,e)=>d-e))

```

Port of @isaacg's Pyth answer.
> 2 votes

# Answer
# Octave, 19 bytes

Isn't nice when two programs fulfill the requirement

```
@(a)sort(sort(a')') % or
@(a)sort(sort(a)')'

```

Anonymous function that transposes the matrix twice to get the original dimensions back. I'm going to claim that this will be the shortest entry in a non-golfing language. Let's see if anyone proves me wrong :)
> 2 votes

# Answer
# Mathematica, 26 bytes

```
Nest[Sort@*Transpose,#,2]&

```

Function names are long. That sucks.
> 2 votes

# Answer
# APL, ~~11~~ 9 bytes

```
⍴⍴⊂∘⍋∘,⌷,

```

Hooks of three functions composed together :).

example:

```
    (⍴⍴⊂∘⍋∘,⌷,) 2 2⍴10 5 4 8
4  5
8 10

```
> 2 votes

# Answer
# RETURN, 10 bytes

```
[{␇␌}␅␆␎␉]

```

`Try it here.`

Anonymous lambda that leaves result on stack. Usage:

```
""{1 2 3 4}""{1 3 4 2}""{4 1 2 3}""{3 1 2 4}[{␇␌}␅␆␎␉]!

```

# Explanation

```
[            ]  lambda
 {␇␌}          push matrix width to stack2
      ␅␆      flatten, sort
          ␎␉   chunk by matrix width (popped from stack2)

```
> 2 votes

# Answer
# MATL, 4 bytes

```
S!S!

```

Try it online!

This just sorts (`S`) column-wise (sorting the contents of each column seperately) then transposes (`!`) and sorts the input again, quite straightforward. This program needs a semicolon (`;`) instead of a comma (`,`) as delimiter of rows.
> 1 votes

# Answer
## Python 3, 52 bytes

A solution using numpy

```
from numpy import*
lambda s:sort(sort(array(s)).T).T

```

*(`sort(s,None)` is longer as we need to reshape after sort)*

## Results

```
>>> f([[-5, -4, -3, -2, -1, 0], [-60, -70, -80, -9, 100, 110], [5, 4, 3, 2, 1, 0], [6, 7, 8, 9, 10, 11]])
array([[-80, -70, -60,  -9,  -1,   0],
       [ -5,  -4,  -3,  -2,   4,   5],
       [  0,   1,   2,   3,  10,  11],
       [  6,   7,   8,   9, 100, 110]])

```
> 1 votes

# Answer
# Ruby, 42 bytes

```
(m,w)->{m.flatten.sort.each_slice(w).to_a}

```

Arguments are the matrix and its width. It works exactly like it reads :)
> 1 votes

# Answer
# Perl 6, ~~28~~ 25 bytes

```
{.flat.sort.rotor(+.[0])}

```

This takes a list of lists (not arrays).
> 1 votes

# Answer
# CJam, 6 bytes

```
{e_$/}

```

This is a code block (unnamed function) that expects the width and matrix on the stack, pops them and pushes the sorted matrix in return. Try it online!

### How it works

```
     e# STACK: w (width), M (matrix)
     e#
e_   e# Flatten M.
  $  e# Sort the resulting, flat array.
   / e# Split the sorted array into rows of length w.

```
> 1 votes

# Answer
# C, 39 Bytes

```
f(x,m,n){qsort(x,m*n,4,"YZZ+QQQÃ");}

```

If the out-of-range char can't show use this instead, though longer

```
f(x,m,n){qsort(x,m*n,4,"YZ\x8B\2Z+\2QQQ\xC3");}

```

Usage:

```
int m, n, i, j;
scanf ("%d%d", &m, &n);
int arr[m][n];
for (i=0; i<m; i++) {
    for (j=0; j<n; j++) {
        scanf("%d", &arr[i][j]);
    }
}
f(arr,m,n);
for (i=0; i<m; i++) {
    for (j=0; j<n; j++) {
        printf("%d ", arr[i][j]);
    }
    puts("");
}

```

Text's disassembler: `00000000: 59 POP ECX
00000001: 5A POP EDX
00000002: 8B02 MOV EAX,[EDX]
00000004: 5A POP EDX
00000005: 2B02 SUB EAX,[EDX]
00000007: 51 PUSH ECX
00000008: 51 PUSH ECX
00000009: 51 PUSH ECX
0000000A: C3 RETN`
> 1 votes

# Answer
# Uiua, 7 bytes

```
⍜♭(⊏⍏.)

```

Try it!

```
⍜♭(⊏⍏.)
⍜♭(   )  # under deshape (apply a function to a flattened array, but keep the shape)
   ⊏⍏.   # sort

```
> 1 votes

# Answer
# Japt v2.0a0, 4 bytes

```
mÍyÍ

```

Try it
> 1 votes

# Answer
**Clojure, 39 bytes**

```
(fn[M w](partition w(sort(flatten M))))

```

`M` is a nested list (the matrix) and `w` is its width (number of columns).

```
(f [[1 3 2 3][5 1 3 7][4 3 6 5]] 4)

((1 1 2 3)
 (3 3 3 4)
 (5 5 6 7))

```
> 0 votes

---
Tags: code-golf, array, sorting, matrix, integer
---