# Question
Title: Solve a matrix equation by Jacobi's method (Revised)
**Mathematical Background**

Let A be an N by N matrix of real numbers, b a vector of N real numbers and x a vector N unknown real numbers. A matrix equation is Ax = b.

Jacobi's method is as follows: decompose A = D + R, where D is the matrix of diagonals, and R is the remaining entries.

if you make an initial guess solution x0, an improved solution is x1 = inverse(D) * (b - Rx) where all multiplications are matrix-vector multiplication and inverse(D) is the matrix inverse.

---

**Problem Specification**

* **Input**: Your complete program should accept as input the following data: the matrix A, the vector b, an initial guess x0, and an 'error' number e.
* **Output**: The program must output the minimum number of iterations such that the latest solution differs by the true solution, by at most e. This means each component of the vectors in absolute magnitude differ by at most e. You must use Jacobi's method for iterations.

How the data is inputted is *your choice*; it could be your own syntax on a command line, you could take input from a file, whatever you choose.

How the data is outputted is *your choice*; it can be written to a file, displayed in the command line, written as ASCII art, anything, as long as it is readable by a human.

**Further Details**

You are not given the true solution: how you calculate the true solution is up to you entirely. You may solve it by Cramer's rule for example, or computing an inverse directly. What matters is that you have a true solution to be able to compare to iterations.

Precision is an issue; some people's 'exact solutions' for comparison may differ. For the purposes of this code golf the exact solution must be true to 10 decimal places.

To be absolutely clear, if even one component of your present iteration solution exceeds its corresponding component in the true solution by e, then you need to keep iterating.

The upper limit to N varies based on what hardware you're using and how much time you're willing to spend running the program. For the purposes of this code golf, assume maximum N = 50.

**Preconditions**

When your program is called, you are free to assume that the following holds at all times:

* N \> 1 and N \< 51, i.e. you will never be given a scalar equation, always a matrix equation.
* All inputs are over the field of real numbers, and will never be complex.
* The matrix A is always such that the method converges to the true solution, such that you can always find a number of iterations to minimise the error (as defined above) below or equal to e.
* A is *never* the zero matrix or the identity matrix, i.e. there is one solution.

---

**Test Cases**

```
A = ((9, -2), (1, 3)), b = (3,4), x0 = (1,1), e = 0.04

```

The true solution is (0.586, 1.138). The first iteration gives x1 = (5/9, 1), differing by more than 0.04 from the true solution, by at least one component. Taking another iteration we find, x2 = (0.555, 1.148) which differs by less than 0.04 from (0.586, 1.138). Thus the output is

```
2

```

---

```
A = ((2, 3), (1, 4)), b = (2, -1), x0 = (2.7, -0.7), e = 1.0

```

In this case the true solution is (2.2, -0.8) and the initial guess x0 already has error less than e = 1.0, thus we output 0. That is, whenever you do not need to make an iteration, you simply output

```
0

```

---

**Submission Assessment**

This is code golf, with all standard loopholes hereby disallowed. The shortest correct *complete program* (or function), i.e. lowest number of bytes wins. It is *discouraged* to use things like Mathematica which wrap up a lot of the necessary steps into one function, but use any language you want.

# Answer
# APL (Dyalog), ~~78~~ ~~68~~ ~~65~~ 49 bytes

*Exactly the type of problem APL was created for.*

-3 thanks to Erik the Outgolfer. -11 thanks to ngn.

Anonymous infix function. Takes A b e as left argument and x as right argument. Prints result to STDOUT as vertical unary using `1` as tally marks, followed by `0` as punctuation. This means that even a 0-result can be seen, being no `1`s before the `0`.

```
{⎕←∨/e<|⍵-b⌹⊃A b e←⍺:⍺∇D+.×b-⍵+.×⍨A-⌹D←⌹A×=/¨⍳⍴A}

```

Try it online!

### Explanation in reading order

Notice how the code reads very similarly to the problem specification:

`{``}` on the given A, b, and e, and and the given x,
`⎕←` print
`∨/` whether there is any truth in the statement that
`e<` e is smaller than
`|⍵-` the absolute value of x minus
`b⌹` b matrix-divided by
`⊃A b e` the first of A, b, and e (i.e. A)
`←⍺` which are the left argument
`:` and if so,
`⍺∇` recurse on
`D+.×` D matrix-times
`b-` b minus
`⍵+.×⍨` x, matrix multiplied by
`A-` A minus
`⌹D` the inverse of D (the remaining entries)
where D is
A where
`=/¨` there are equal
coordinates for
`⍴A` the shape of A (i.e. the diagonal)

### Step-by-step explanation

The actual order of execution right-to-left:

`{``}` anonymous function where  is A b e and ⍵ is x:
`A b c←⍺` split left argument into A, b, and e
pick the first (A)
`b⌹` matrix division with b (gives true value of x)
`⍵-` differences between current values of x and those
`|` absolute values
`e<` acceptable error less than those?
`∨/` true for any? (lit. OR reduction)
`⎕←` print that Boolean to STDOUT
`:` and if so:
`⍴A` shape of A
matrix of that shape where each cell is its own coordinates
`=/¨` for each cell, is the vertical and horizontal coordinates equal? (diagonal)
multiply the cells of A with the that (extracts diagonal)
matrix inverse
`D←` store in D (for **D**iagonal)
inverse (back to normal)
`A-` subtract from A
`⍵+.×⍨` matrix multiply (same thing as dot product, hence the `.`) that with x
`b-` subtract that from b
`D+.×` matrix product of D and that
`⍺∇` apply this function with given A b e and that as new value of x
> 4 votes

# Answer
# Python 3, 132 bytes

```
f=lambda A,b,x,e:e<l.norm(x-dot(l.inv(A),b))and 1+f(A,b,dot(l.inv(d(d(A))),b-dot(A-d(d(A)),x)),e)
from numpy import*
l=linalg
d=diag

```

Try it online!

Uses a recursive solution.
> 1 votes

# Answer
# , 138 bytes

```
function(A,x,b,e){R=A-(D=diag(diag(A)))
g=solve(A,b)
if(norm(t(x-g),"M")<e)T=0
while(norm((y=solve(D)%*%(b-R%*%x))-g,"M")>e){T=T+1;x=y}
T}

```

Try it online!

*thanks to NikoNyrh for fixing a bug*

It's also worth noting that there is an R package, `Rlinsolve` that contains a `lsolve.jacobi` function, returning a list with `x` (the solution) and `iter` (the number of iterations required), but I'm not sure that it does the correct computations.
> 1 votes

# Answer
## Clojure, ~~212~~ ~~198~~ 196 bytes

```
#(let[E(range)I(iterate(fn[X](map(fn[r b d](/(- b(apply +(map * r X)))d))(map assoc % E(repeat 0))%2(map nth % E)))%3)](count(for[x I :while(not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))]x)))

```

Implemented without a matrix library, it iterates the process 1e9 times to get the correct answer. This wouldn't work on too ill-conditioned inputs but should work fine in practice.

Less golfed, I was quite happy with the expressions of `R` and `D` :) The first input `%` (A) has to be a vector, not a list so that `assoc` can be used.

```
(def f #(let[R(map assoc %(range)(repeat 0))
             D(map nth %(range))
             I(iterate(fn[X](map(fn[r x b d](/(- b(apply +(map * r x)))d))R(repeat X)%2 D))%3)]
          (->> I
               (take-while (fn[x](not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))))
               count)))

```
> 1 votes

---
Tags: code-golf, matrix, linear-algebra
---


title: Reduce the list to a final number

text:
# Question
Title: Reduce the list to a final number
**Inputs**

A list (array) of numbers, or numerical strings if that makes it easier. You can assume there will always be at least two elements in the list and every element will be a natural number (integer larger than zero).

### Outputs

A single number, or again, a numerical string.

### Problem

The idea is to reduce the list of numbers by removing the last digit of the largest number at that current stage of the list, eventually ending with one number (only one number should be returned, even if there are multiple instances)

### Example

```
[123,343,121,76,465,786] -- The last digit in 786 is dropped, so it becomes 78
[123,343,121,76,465,78]  -- New largest number is 465, so the 5 is dropped, making it 46
[123,343,121,76,46,78]   -- Repeat until left with one number
[123,34,121,76,46,78]
[12,34,121,76,46,78]
[12,34,12,76,46,78]
[12,34,12,76,46,7]
[12,34,12,7,46,7]
[12,34,12,7,4,7]
[12,3,12,7,4,7]
[1,3,1,7,4,7]            -- If there are multiple max numbers, you **must** remove the last digit from all of them
[1,3,1,4]
[1,3,1]
[1,1]                    -- You have your answer when there is one number, or multiple numbers that are equal
1                        -- Result

```

### Loopholes

Standard loopholes apply

### Other constraints

Your program **must** work for any list of random numbers (within reason of course)

### Test Cases

```
[24,72,4]
[24,7,4]
[2,7,4]
[2,4]
[2]
2

[14, 7]
[1, 7]
[1]
1

[1278,232,98273,2334]
[1278,232,9827,2334]
[1278,232,982,2334]
[1278,232,982,233]
[127,232,982,233]
[127,232,98,233]
[127,232,98,23]
[127,23,98,23]
[12,23,98,23]
[12,23,9,23]
[12,2,9,2]
[1,2,9,2]
[1,2,2]
[1]
1

```

### Scoring

This is , so shortest answer in every language wins!

# Answer
> 10 votes
# Haskell, 16 bytes

```
minimum.map head

```

Try it online!

# Answer
> 4 votes
# Python 2, 24 bytes

*-4 bytes thanks to notjagan.*

```
lambda l:min(zip(*l)[0])

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~24, 21~~, 18 bytes

```
lambda l:min(l)[0]

```

Try it online!

~~Three~~ Six bytes saved thanks to @totallyhuman!

# Answer
> 3 votes
# Mathematica, 29 bytes

```
Min[First@*IntegerDigits/@#]&

```

# Answer
> 3 votes
# Japt, ~~8~~ ~~6~~ 5 bytes

*-1 byte thanks to @Shaggy*

```
n g g

```

Takes input as an array of numeric strings. Try it online!

## Explanation

```
        // implicit input: array of strings
n       // sort the array
  g     // get the first element
    g   // get the first character
        // implicit output

```

# Answer
> 2 votes
# , ~~11~~, 5 bytes

```
ÚxV}p

```

Try it online!

I was making this *waaay* more complicated than it actually is. This answer simply sorts every line by ASCII values, and then returns the very first character. Since this is kind or a boring answer, here is a more interesting answer that actually implements the algorithm originally described:

# , 11 bytes

```
òún
/äîä
Lx

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 3 bytes

```
€нW

```

Try it online!

# Answer
> 2 votes
# PHP, 45 bytes

```
<?foreach($_GET as$v)$r[]=$v[0];echo min($r);

```

Try it online!

# Answer
> 2 votes
# Jelly,  ~~3~~  2 bytes

```
ṂḢ

```

A full program which takes a list of lists of characters (strings) and prints the result.

**Try it online!**

### How?

We just need to return the smallest leading digit...

```
ṂḢ - Main link: list of lists of characters
Ṃ  - minimum (lexicographical ordering ensures this will start with the minimal digit)
 Ḣ - head (get that first digit character)

```

# Answer
> 2 votes
# JavaScript (ES6), 17 bytes

Takes input as an array of strings.

```
a=>a.sort()[0][0]

```

---

## Try it

Input a comma separated list of numbers.

```
o.innerText=(f=
a=>a.sort()[0][0]
)((i.value="1278,232,98273,2334").split`,`);oninput=_=>o.innerText=f(i.value.split`,`)
```

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

# Answer
> 1 votes
# ,,,, 3 bytes

```
⫰1⊣

```

## Explanation

```
⫰1⊣

⫰    pop the whole stack and push the minimum element
 1   push 1
  ⊣  pop the minimum and 1 and push the first character of it

```

# Answer
> 1 votes
# Braingolf, 17 bytes

```
VVR{Mvd<M&$_R}vvx

```

Try it online!

## Explanation

```
VVR{Mvd<M&$_R}vvx  Implicit input from commandline args
VVR                Create stack2 and stack3, return to stack1
   {.........}     Foreach item in stack..
    M              ..Move item to next stack
     v             ..Switch to next stack
      d            ..Split item into digits
       <M          ..Move first item to next stack
         &$_       ..Clear stack
            R      ..Return to stack1
              vv   Switch to stack3
                x  Reduce to lowest value
                   Implicit output of last item on stack

```

In other words, it constructs a stack consisting of only the first digit of each item, then outputs the lowest.

This challenge gave me a bunch of useful ideas for builtins to add to Braingolf, and now thanks to the addition of the "special" foreach loop, Braingolf can do it in 5 bytes:

# Braingolf, 5 bytes \[non-competing\]

```
(d<)x

```

## Explanation

```
(d<)x  Implicit input from commandline args
(..)   Special foreach loop, iterates over the stack, moving each item to a special
       Sandboxed stack environment, and prepends the last item of the sandboxed
       stack to the real stack at the end of each iteration
 d<    Split into digits, move first digit to end of stack
    x  Reduce to lowest value
       Implicit output of last item on stack

```

Try it online!

I'm normally against adding builtins *just* to complete one challenge, but I can see a plethora of uses for the new `(...)` foreach loop, so I don't really consider it adding a feature just for this challenge.

# Answer
> 1 votes
# Funky, 18 bytes

```
x=>x::sort()[0][0]

```

Takes input as a list of strings.

Try it online!

# Answer
> 0 votes
# Pyth, ~~9~~ 7 bytes

```
hSmsh`d

```

Try it online!

**Explanation**

This basically return the smallest leading digit.

```
       Q    # Implicit input
  msh`d     # For each number in Q, convert to string, take the first character, convert to integer
hS          # Return the minimum

```

# Answer
> 0 votes
# Pip, 5 bytes

Takes the list of input numbers as command-line arguments.

```
@@SSg

```

Try it online!

Alternately:

```
MN@Zg

```

Try it online!

### Explanations

In both programs, `g` is the list of command-line args.

```
@@SSg

```

`SS` sorts using string comparison, thus putting the numbers with smallest first digits first, regardless of their magnitudes. Unary `@` gives the first element of a list or scalar. We apply it twice to get the first digit of the first number after sorting.

```
    g  [24 72 491]
  SS   [24 491 72]
 @     24
@      2

```

Alternately:

```
MN@Zg

```

`Z` is zip; its unary version can be used to transpose a list. The first element of the transposed list is a list of the first digits of all the numbers. `@` gets that list of digits; `MN` takes its minimum.

```
    g  [24 72 491]
   Z   [[2 7 4] [4 2 9]]
  @    [2 7 4]
MN     2

```

# Answer
> 0 votes
# Python 3, 33 bytes

```
lambda l:min(str(x)[0]for x in l)

```

Try it online!

@DJMcMayhem and @totallyhuman have a better solutions but mine assumes numerical input instead of string.

# Answer
> 0 votes
# **Pyth, 3 bytes**

```
hhS

```

Input is list of string representations of numbers.

Try It Online

**Explanation:**

```
hhS
    # Q=input
  S # Sort Q
 h  # First Element of sorted list
h   # First element of string
    # Implicitly print result

```

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


# Question
Title: Shortest string expressions stable under deleting quotes
Forgetting quotes can lead to certain problems. For example, in Scala the two expressions:

```
"("+("+")+(")+(")+")"
 ("+("+")+(")+(")+")

```

differ only in starting and ending quotes, but they respectively yield the result:

```
(+)+()
+()+()+

```

But this expression in scala almost has the desired property:

```
def m="+m+"
""+m+""

```

Your task is to **write the shortest expression surrounded with quotes**, such that if we remove the outer quotes, the **expression still returns the same string**.

Key points:

* Your language must support "..." as string literals
* The program has to contain at least three characters
* You are not allowed to define a context outside of the quotes themselves (as I did for m)
* You are not allowed to use other delimiters for strings, e.g. no `"""`, no `'`.
* Both expressions should *return strings*.
* Shortest code wins (counting the quotes themselves)

# Answer
> 2 votes
# Befunge 98 - 3, 4, 6, 17

In these programs, I'll assume you just want to get a string, but you don't care if the program terminates. In other words, you want a code snippet that can be placed in the code somewhere. (Note: in Befunge, whatever is on the stack is a string. It is also a number)

This code snippet must be placed on the first part of the first line.

```
"g"

```

When the quotes are removed, `g` acts like `00g`, so it pushes a `g`. Either way, it pushes a `g`.

```
""""

```

Works in Befunge 93 as well; it always pushes nothing.

This one is more interesting

```
""z"z"

```

It will always push `z`. `z` is a no-op so although the IP executes the command, it does nothing (I could have used , but `z` is more interesting).

This one only has one set of `"`, and is quine-like:

```
">:0g\1+:f`1+jb<"

```

It always pushes the contents of the string, but when the quotes are removed, it does it in a quine-like way. This must be placed on the first part of the first line, but adjustments can be made to put it elsewhere

# Answer
> 14 votes
# C (4 chars)

The expression

```
""""

```

satisfies the minimal requirement of three characters. It encodes the empty string, no matter even if you omit one level of quotes:

```
 ""

```

If you want the resulting string to be at least three characters, here is an expression of length 10 which results in three characters of string, namely three spaces:

```
""   "   "
 "   "

```

If you don't like spaces either, here are four printable characters in a length 12 expression:

```
""/**/"/**/"
 "/**/"/**/

```

Putting these expressions into a small program:

```
#include <stdio.h>
#define CASE(s) printf("'%s'\n", s)
int main() {
  CASE("""");
  CASE("");
  CASE(""   "   ");
  CASE("   "   );
  CASE(""/**/"/**/");
  CASE("/**/"/**/);
}

```

Output:

```
''
''
'   '
'   '
'/**/'
'/**/'

```

# Answer
> 4 votes
# Shell (3 chars)

```
"w"
w

```

Both execute the command `w`.

# Answer
> 4 votes
# JavaScript, ~~28~~ ~~27~~ ~~15~~ 12 (6 if result can be non-string (still works with output))

This one's pretty interesting.

```
"+"*1+"+"+""

```

The basic explanation is that `"string" * 1` is `NaN`, and `+"string"` is also `NaN`. Therefore, it results in the string `"NaN+"` with or without the outside quotes.

For further explanation, it gets parsed as `("+" * 1) + ("+") + ("")` with the outside quotes, and `(+ "*1+") + "+"` without.

The version that works if the output can be non-string:

```
"+"*""

```

Which does work when outputting (as JavaScript is weakly typed):

```
alert("+"*"") // NaN
alert(+"*")   // NaN

```

---

Old version:

```
"+".replace(/./,NaN)+"+"+""

```

With the quotes outside, it is parsed as

```
("+".replace(/./, NaN)) + ("+") + ("")
"NaN" + "+" + ""
"NaN+"

```

Without the quotes, it gets parsed as

```
(+".replace(/./,NaN)+") + ("+")
// +"any string" evaluates to NaN
NaN + "+"
"NaN+"

```

# Answer
> 3 votes
## Perl - 4 bytes

```
"$~"

```

Test program:

```
print"$~";
print$~;

```

Ouput:

```
STDOUT
STDOUT

```

# Answer
> 3 votes
## Update: Python (12 chars)

program

```
""+"+""+"+""
"+"+""+"+"

```

both giving

```
'++'

```

## Python (28 chars)

program

```
"".__str__()+".__str__()+"""
".__str__()+".__str__()+""

```

both giving

```
'.__str__()+'

```

## Python (38 chars)

program

```
"".replace("+","+")+".replace("+","")"
".replace("+","+")+".replace("+","")

```

both giving

```
'.replace(,)'

```

# Answer
> 3 votes
# JavaScript, 40

```
"(f=function (){return'(f='+f+')()'})()"

```

When you remove the quotes, it becomes an immediately invoked function expression, and this function happens to return `'(f='+f+')()'`, which is the entirety of the string. (Absuing `Function#toString`. `;)`)

# Answer
> 3 votes
## huh?, 7

```
"Ouch!"

```

It works because both `"Ouch!"` and `Ouch!` are both invalid files, so the interpreter will return `Ouch!`

# Answer
> 2 votes
## PowerShell, 4 chars

```
"$?"
$?

```

Output:

```
TRUE
TRUE

```

This uses the automatic variable $?, which is a Boolean containing the execution status of the last run command. The only effect of wrapping it in quotes is that it is converted to a string prior to being printed, which is a transparent operation.

# Answer
> 2 votes
## GolfScript: 16 chars

OK, since my 3-char solution `"1"` has been disqualified by a rules change, here's the straightforward solution in GolfScript:

```
"{`[46 126]+}.~"

```

With the quotes, this is just a double-quoted string literal. Without the quotes, it's a quine. The only slightly trickly part is that, to literally comply with the rule prohibiting alternative string delimiters, I have to encode the string `'.~'` as an array of ASCII codes `[46 126]` instead.

# Answer
> 1 votes
# Scala REPL (10 chars)

```
"0+"++"+0"
 0+"++"+0

```

are both returning:

```
0++0
0++0

```

**Explanation:** In the first case ++ treats the left string as a sequence of chars and concatenates the next sequence of chars and rebuilds a string. In the second case, + converts the first and last 0 to strings.

Note that everything is even a palindrom.

## Other interesting solution using blocks (55 chars)

```
"{val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}"
 {val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}

```

return both smileys:

```
 ;o}
 ;o}

```

**Explanation:** See the below decomposition

```
"{val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}"
--multiplied by 0=>"" --------- returns "" -----  result
 {val o="*{val o=0;o}+".substring(9,12);val i="*0+";o}
        -------- o equals ";o}"-------- -i ignored- o

```

# Answer
> 0 votes
# Python (8 characters)

```
""""""""

```

and

```
""""""

```

both return empty string
Is based on idea of MvG

# Answer
> 0 votes
# Tcl, 1, 3

```
1
"1"

```

Try it online!

Explanation: In Tcl, *"quoting is a tool, not a rule"*

# Answer
> 0 votes
## TI-BASIC, 6 bytes

```
""→Str1:"
"→Str1:

```

Both of these end up storing an empty string to `Ans` (and to `Str1`). The second works because storing to a variable also stores to `Ans`.

I also found another 6-byter:

```
"":":"
":":

```

Both of these will return `":"`.

I have checked every shorter chain matching `"[":]{0-3}"`, and none meet the specifications.

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


title: Sort an Option String

text:
# Question
Title: Sort an Option String
## Background

In C, there is a function to help parse command-line arguments: `getopt`.

Getopt takes the argument count (`argc`), the argument list (`argv`), and a string representing the options the program should take (**`optstring`**).

The option string (`optstring`) is a series of option characters each followed by one colon (for an option requiring an argument), two colons (for an option with an optional argument), or zero colons (for an option without an argument).

For example: one might use the following option string for their company's new widget.

```
"v::x:hy:S:G::dns:f::"

```

But that looks horrible! The options are all mixed together! This option string would look much better if it were sorted:

```
"f::G::v::S:s:x:y:dhn"

```

## Specifications

* The input will be a string matching the regular expression `([A-Za-z]:{0,2})+`
* You should take input as a string or list of characters.
* You should output the string sorted by the method detailed below.
* You do not need to handle empty input.
* You do not need to handle input with repeated options of the same type (`"aa"` is not valid, but `"aa:a::"` is valid).

### Sorting Method

In the sorted option string:

* The characters followed by two colons come first, sorted alphabetically, with uppercase letters before their respective lowercase letters (i.e. "aBb", not "Bab").
* Then are the characters with one colon, sorted alphabetically, with uppercase letters before their respective lowercase letters.
* Last are the characters with no colon, sorted alphabetically, with uppercase letters before their respective lowercase letters.

## Rules

## Scoring

This is , so shortest answer in bytes in each language wins.

## Examples

```
# "input" => "output"
"v::x:hy:S:G::dns:f::" => "f::G::v::S:s:x:y:dhn"
"aa:a::" => "a::a:a"
"B:" => "B:"
"Confusio:n::" => "n::o:Cfinosu"
"Confusio:n:" => "n:o:Cfinosu"
"m:qW:X:xc:vViI" => "c:m:W:X:IiqVvx"
"V:omo:V" => "o:V:moV"
"agg:ra:va::ting::" => "a::g::a:g:aginrtv"
"input" => "inptu"

```

Long test case (312 characters)

Invaid Inputs (you don't have to handle):

```
"gg" (duplicated option)
"" (empty string)
":w:" (first colon isn't after a character)
"x:y:0:fhn" ('0' is not alphabetic)
"A:::" (3 colons is invalid)

```

# Answer
> 10 votes
# Husk, 11 bytes

```
ΣÖom_↔Oġλ¬√

```

Try it online!

## Explanation

```
ΣÖom_↔Oġλ¬√  Implicit input, say "kH::r:R:Hk:"
       ġ     Split between characters for which this gives a falsy result:
        λ      Take two arguments, ignore the first.
          √    Is the second argument a letter?
         ¬     Negate.
             Now we have the options: ["k","H::","r:","R:","H","k:"]
      O      Sort: ["H","H::","R:","k","k:","r:"]
 Ö           Sort by
     ↔       reversing and
  om_        converting everything to lowercase: ["H::","k:","R:","r:","H","k"]
Σ            Concatenate: H::k:R:r:Hk

```

# Answer
> 3 votes
# Japt, ~~17~~ 16 bytes

```
f".:*" ñ_iZw vÃq

```

Test it online!

### How it works

Say the input string is `v:vg::G:G::o:`. The first part of the code, `f".:*"`, finds all matches of the regex `/.:*/g`, which matches a character followed by any number of colons. This splits the input into `[v:, v, g::, G:, G::, o:].`

The `ñ` method on an array sorts each the array as if certain changes were applied, without actually applying them (like `sorted(array, key=<whatever>)` in Python). So we need to sort:

* double-colons before everything else;
* single-colons after double-colons, but before no-colons;
* letters in their alphabetical order; and finally
* uppercase letters before lowercase.

`Z{ZiZéJ v}` is the shortest way I could find to do this:

```
  Zw     Reverse Z.
     v   Convert to lowercase.
Zi       Insert this at the beginning of Z.

```

This is easiest to understand with some examples:

```
         v:   v  g::    G:   G::    o:
  Zw     :v   v  ::g    :G   ::G    :o
     v   :v   v  ::g    :g   ::g    :o
Zi       :vv: vv ::gg:: :gG: ::gG:: :oo:

```

The original values are then sorted lexicographically by these keys. The result is that `::gG::` is sorted to the front, then `::gg::`, and so on, giving us `[G::, g::, G:, o:, v:, v]`, which is then joined with `q` and outputted.

# Answer
> 3 votes
## Retina, 47 bytes

```
.
$&$&
T01`L`l`..
O^`\w.:*
.(.)
$1
O$^`\w:*
$.&

```

Try it online!

The trickiest part was actually sorting the letters, because Retina's "sort-by" feature doesn't have a case-insensitive sort (so by default it sorts the upper case letters in front of *all* lower case letters). To work around this, I had to insert a lower-case copy of each character to do the sorting and then get rid of it again.

# Answer
> 3 votes
# Python 2, ~~100~~ 90 bytes

```
lambda s:''.join(sorted(re.findall('.:*',s),key=lambda s:(-len(s),s.lower(),s)))
import re

```

Try it online!

# Answer
> 2 votes
# Jelly, 14 bytes

```
n”:œṗ⁸ṢŒuÞṚLÞṚ

```

Try it online!

Full program.

# Answer
> 1 votes
# Perl 5, 69 + 1 (`-n`) = 70 bytes

```
say sort{$b=~y///c<=>length$a||($"=lc$a)cmp lc$b||1-2*($"ne$a)}/.:*/g

```

Try it online!

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

```
f=
s=>s.match(/\w:*/g).sort((a,b)=>b.length-a.length||parseInt(a,36)-parseInt(b,36)||a>b).join``
```

```
<input oninput=o.textContent=this.value&&f(this.value)><pre id=o>
```

# Answer
> 1 votes
# Bash, ~~232~~ 213 bytes

```
s(){ s=${1#?} c=${1%$s} o=${s%%[^:]*} s=${s#$o} o=$c$o;};
p()(s $1;l= g= p=$o d=$c;[[ $o ]]&&(while s $s;[[ $o ]];do
(((x=${#o}-${#p},y=36#$d-36#$c,x?x:y?y:62#$c-62#$d)>0))&&g+=$o||l+=$o;done;echo `p $g`$p`p $l`))

```

try it online

# Answer
> 1 votes
# Haskell, 124 bytes

```
import Data.List
import Data.Char
s(c:x)|(l,r)<-span(==':')x=(-length l,toLower c,c:l):s r;s _=[]
t(_,_,x)=x
f=(t=<<).sort.s

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 152 bytes

```
s=>{var o="";for(var d=":::";d!="";){d=d.Substring(1);for(var c='@';c!=90;o+=s.IndexOf(c+d)>=0?c+d:"",s=s.Replace(c+d,""),c^=' ')if(c<97)c++;}return o;}

```

Try it online!

Ungolfed:

```
s => {
    var o = "";
    for (var d = ":::"; d != "";) {
        d = d.Substring(1);
        for (
            var c = '@';
            c != 90;
            o += s.IndexOf(c + d) >= 0 ? c + d : "", s = s.Replace(c + d, ""), c ^= ' '
        ) if (c < 97) c++;
    }
    return o;
}

```

The basic idea is to iterate over all 156 possible options and check for their existence. If found, append to the output, and remove from the input.

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


title: Fibonacci Factorization

text:
# Question
Title: Fibonacci Factorization
# Fibonacci Numbers

Fibonacci Numbers start with `f(1) = 1` and `f(2) = 1` (some includes `f(0) = 0` but this is irrelevant to this challenge. Then, for `n > 2`, `f(n) = f(n-1) + f(n-2)`.

# The challenge

Your task is to find and output the `n`-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer.

Also, your answer must compute the 100th term in a reasonable time.

# Testcases

```
n   result corresponding product (for reference)
1   1      1
2   2      2
3   3      3
4   4      2*2
5   5      5
6   6      2*3
7   8      2*2*2 or 8
8   9      3*3
9   10     2*5
10  12     2*2*3
11  13     13
12  15     3*5
13  16     2*2*2*2 or 2*8
14  18     2*3*3
15  20     2*2*5
16  21     21
17  24     2*2*2*3 or 3*8
18  25     5*5
19  26     2*13
20  27     3*3*3
100 315    3*5*21

```

# References

# Answer
# Jelly, ~~26~~ ~~24~~ ~~23~~ 21 bytes

```
ÆDf÷ß€FðḊ¡
1ç#2+Ð¡1¤Ṫ

```

Try it online!

### How it works

```
1ç#2+Ð¡1¤Ṫ  Main link. Argument: n (integer)

        ¤   Combine the three links to the left into a niladic chain.
   2          Set the left argument and the return value to 2 (third positive
              Fibonacci number).
       1      Yield 1 (second positive Fibonacci number).
    +Ð¡       Compute the sum of the return value and right argument, replacing the
              return value with the sum and the right argument with the previous
              return value.
              Do this n times, collecting all return values in a list.
              This returns A, the first n Fibonacci numbers greater than 1.
1             Set the return value to 1.
 ç#           Call the helper link with left argument k = 1, 2, 3... and right
              argument A = [2, 3, 5...] until n of them return a truthy value.
              Collect the matches in a list.
           Ṫ  Tail; extract the last (n-th) match.

ÆDf÷ß€FðḊ¡    Helper link. Left argument: k. Right argument: A

        Ḋ     Dequeue; yield r := [2, ..., k].
       ð ¡    If r in non-empty, execute the chain to the left. Return k otherwise.
ÆD              Yield the positive divisors of k.
   ÷            Divide k by all Fibonacci numbers in A.
  f             Filter; keep divisors that belong to k÷A, i.e., all divisors
                d for which k÷d belongs to A.
    ß€          Recursively call the helper link for each kept divisor d, with left
                argument d and right argument A.
      F         Flatten the result, yielding a non-empty array iff any of the
                recursive calls yielded a non-empty array or a number.
                If the left argument is 1, the helper link returns 1, so the
                array will be non-empty if the consecutive divisions by Fibonacci
                numbers eventually produced a 1.

```
> 6 votes

# Answer
# Julia, 79 bytes

```
!k=any(i->√(5i^2+[4,-4])%1∋k%i<!(k÷i),2:k)^~-k
<|(n,k=1)=n>0?n-!k<|-~k:~-k

```

Try it online!

### Background

In Advanced Problems and Solutions, H-187: Fibonacci is a square, the proposer shows that

where **Ln** denotes the **n**th Lucas number, and that – conversely – if

then **n** is a Fibonacci number and **m** is a Lucas number.

### How it works

We define the binary operator `<|` for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser.

When called with only one argument (**n**), `<|` initializes **k** as **1**. While **n** is positive, it subtracts **!k** (**1** if **k** is a product of Fibonacci numbers, **0** if not) from **n** and recursively calls itself, increments **k** by **1**. Once **n** reaches **0**, the desired amount of products have been found, so `<|` returns the previous value of **k**, i.e., **~-k = k - 1**.

The unary operator `!`, redefined as a test for Fibonacci number products, achieves its task as follows.

* If **k = 1**, **k** is a product of Fibonacci numbers. In this case, we raise the return value of `any(...)` to the power **~-k = k - 1 = 0**, so the result will be **1**.
* If **k \> 1**, the result will be the value of `any(....)`, which will return **true** if and only if the predicate `√(5i^2+[4,-4])%1∋k%i<!(k÷i)` returns **true** for some integer **i** such that **2 ≤ i ≤ k**.

The chained conditions in the predicate hold if `k%i` belongs to `√(5i^2+[4,-4])%1` and `k%i` is less than `!(k÷i)`.

+ `√(5i^2+[4,-4])%1` takes the square root of **5i2 \+ 4** and **5i2 \- 4** and computes their residues modulo **1**. Each modulus is **0** if the corresponding number is a perfect square, and a positive number less than **1** otherwise.

    Since `k%i` returns an integer, it can only belong to the array of moduli if **k % i = 0** (i.e., **k** is divisible by **i**) and at least one among **5i2 \+ 4** and **5i2 \- 4** is a perfect square (i.e., **i** is a Fibonacci number).
    + `!(k÷i)` recursively calls **1** with argument **k ÷ i** (integer division), which will be greater than **0** if and only if **k ÷ i** is a product of Fibonacci numbers.

By induction, **!** has the desired property.
> 5 votes

# Answer
## Python, 90 bytes

```
f=lambda n,a=2,b=3:n<2or n%a<f(n/a)or n-a>0<f(n,b,a+b)
g=lambda k,n=1:k and-~g(k-f(n),n+1)

```

The main function `g` outputs the `k`th Fibonacci product, 1-indexed. It computes `g(100)` as `315` almost instantly. It goes so with a general recursive recipe of counting up numbers `n` looking for `k` instances that satisfy the function `f`. Each such instance lowers the required count `k` until it reaches `0`.

The auxiliary function `f` tests a number for being a Fibonacci product. It recursively generates the Fibonacci numbers in its optional arguments `a` and `b`. It outputs "yes" if any of the following is true:

* `n<2`. This implies `n==1`, the trivial product)
* `n%a<f(n/a)`. This requires `n%a==0` and `f(n/a)==True`, i.e. that `n` is a multiple of the Fibonacci number `a`, and removing this factor of `a` still yield a Fibonacci product.
* `n-a>0<f(n,b,a+b)`, equivalent to `n>a and f(n,b,a+b)`. Checks that the current Fibonacci number being tested isn't at least `n`, and some greater Fibonacci number works. Thanks to Dennis for 2 saving bytes using the inequality short-circuit instead of `and`.

The function `g` can be one byte shorter as

```
lambda k:filter(f,range(k*k+1))[k]

```

if `g(k)` is always at most `k*k`, which I'm not sure is asymptotically true. A bound of `2**k` suffices, but then `g(100)` takes too long. Maybe instead the recursive of `g` can be done in `f`.
> 5 votes

# Answer
# Perl 6,  ~~95~~  93 bytes

```
~~{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*!%%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}~~
{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}
```

( 0 based index )

### Test:

```
my &fib-prod = {(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}

say fib-prod 0 ..^ 20;
# (1 2 3 4 5 6 8 9 10 12 13 15 16 18 20 21 24 25 26 27)
say time-this { say fib-prod 100 -1; };
# 315
# 1.05135779

sub time-this (&code) {
  my $start = now;
  code();
  now - $start;
}

```

### Explanation:

```
{
  (1..*).grep(
    {
      $/ = $_; # copy the input ($_) to $/
      map { # map used just for side effect
        ->{
          $/ % $_    # if $/ is divisible by the current fib factor
        ||
          ($/ /= $_) # divide it out once
        ;
          # return the current value in $/
          $/
        }
        ... # repeat until that returns:
        * !%% $_ # something that is not divisible by the current fib factor
        ;0
      },
      # the possible fibonacci factors plus one, reversed
      # ( the extra is to save one byte )
      reverse 2,3,&[+] ... *>$_;

      # is the end result of factoring equal to 1
      # ( for the grep above )
      2 > $/
    }
  )[ $_ ] # get the value at 0-based index
}

```
> 2 votes

# Answer
# Python 3, ~~175~~ ~~170~~ 148 bytes

*Thanks to @Dennis for -22 bytes*

```
j=x=int(input())
y=1,1
exec('y+=y[-2]+y[-1],;'*x)
i=c=0
while c<x:
    if j>=x:j=0;i+=1;t=i
    if t%y[~j]<1:t/=y[~j];j-=1
    if t<2:c+=1;j=x
    j+=1
print(i)

```

Takes input from STDIN and prints to STDOUT. This is one-indexed. Computing the 100th term takes roughly a tenth of a second.

**How it works**

```
j=x=int(input())                Get term number x from STDIN and set Fibonacci number index
                                j to x to force initialisation of j later
y=1,1                           Initialise tuple y with start values for Fibonacci sequence
exec('y+=y[-2]+y[-1],;'*x)      Compute the Fibonacci sequence to x terms and store in y
i=c=0                           Initialise test number i and term counter c
while c<x:                      Loop until x th term is calculated
    if j>=x:j=0;i+=1;t=i        Initialise Fibonacci number index j, increment i and
                                initialise temp variable t for looping through all j for
                                some i. Executes during the first pass of the loop since
                                at this point, j=x
    if t%y[~j]<1:t/=y[~j];j-=1  Find t mod the j th largest Fibonacci number in y and if no
                                remainder, update t by dividing by this number.
                                Decrementing j means that after a later increment, no
                                change to j occurs, allowing for numbers that are
                                divisible by the same Fibonacci number more than once by
                                testing again with the same j
    if t<2:c+=1;j=x             If repeated division by ever-smaller Fibonacci numbers
                                leaves 1, i must be a Fibonacci product and c is
                                incremented. Setting j equal to x causes j to be reset
                                to 0 during the next loop execution
    j+=1                        Increment j
print(i)                        i must now be the x th Fibonacci product. Print i to STDOUT

```

Try it on Ideone
> 2 votes

# Answer
# Python 2, ~~120~~ 107 bytes

```
g=lambda k:1/k+any(k%i==0<g(k/i)for i in F)
F=2,3;k=0;n=input()
while n:F+=F[k]+F[-1],;k+=1;n-=g(k)
print k

```

Test it on Ideone.

### How it works

We initialize **F** as the tuple **(2, 3)** (the first two Fibonacci number greater than **1**), **k** as **0** and **n** as an integer read from STDIN.

While **n** is positive, we do the following:

* Append the next Fibonacci number, computed as **F\[k\] + F\[-1\]**, i.e., the sum of the last two elements of **F** to the tuple **F**.
* Increment **k**.
* Subtract **g(k)** from **n**.

**g** returns **1** if and only if **k** is a product of Fibonacci numbers, so once **n** reaches **0**, **k** is the **n**th Fibonacci number and we print it to STDOUT.

**g** achieves its purpose as follows.

* If **k** is **1**, it is a product of Fibonacci numbers, and `1/k` makes sure we return **1**.
* If **k** is greater than **1**, we call `g(k/i)` recursively for all Fibonacci numbers **i** in **F**.

`g(k/i)` recursively tests if **k / i** is a Fibonacci number product. If `g(k/i)` returns **1** and **i** divides **k** evenly, **k % i = 0** and the condition `k%i<g(k/i)` holds, so **g** will return **1** if and only if there is a Fibonacci number such that **k** is the product of that Fibonacci number and another product of Fibonacci numbers.
> 2 votes

# Answer
# JavaScript (ES6), 136

Quite slow golfed this way, computing term 100 in about 8 seconds in my PC.

```
(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')

```

*Less golfed* and faster too (avoiding `eval`)

```
n=>{
  F=i=> i>1 ? F(i-1)+F(i-2) : i+1; // recursive calc Fibonacci number
  K=(n,i=1,d,x)=>{ // recursive check divisibility
    for(; (d=F(i++))<=n && !(x=!(n%d)&&K(n/d)); );
    return x||n<2
  };
  for(a=0; n; )
    K(++a) && --n;
  return a
}

```

**Test**

```
X=(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')

function test() {
  var i=+I.value
  O.textContent=X(i)
}

test()
```

```
<input id=I value=100 >
<button onclick="test()">Go</button><pre id=O></pre>
```
> 1 votes

# Answer
## Haskell, 123 bytes

```
f=2:scanl(+)3f
m((a:b):c)=a:m(b?(a#c))
v#((a:b):c)|v==a=b?(v#c)
_#l=l
y?(z:e)|y>z=z:y?e
a?b=a:b
l=1:m[[a*b|b<-l]|a<-f]
(l!!)

```

Very lazy, much infinite!

Possibly not the shortes way, but I had to try this approach, a generalization of a quite well known method to compute the list of hamming numbers. `f` is the list of fibonacci numbers starting from 2. For brevity, let's say that a lol (list of lists) is an infinite list of ordered infinite lists, ordered by their first elements. `m` is a function to merge a lol, removing duplicates. It uses two infix helper functions. `?` inserts an infinite sorted list into a lol. `#` removes a value from a lol that may appear as head of the first lists, reinserting the remaining list with `?`.

Finally, `l` is the list of numbers which are products of fibonacci numbers, defined as 1 followed by the merge of all the lists obtained by multiplying `l` with a fibonacci number. The last line states the required function (as usual without binding it to a name, so don't copy it as is) using `!!` to index into the list, which makes the function 0-indexed.

There is no problem computing the 100th or 100,000th number.
> 1 votes

# Answer
# Husk, 13 bytes

Note that Husk is newer than this challenge. However it and the most useful function for this golf (`Ξ`) were not created with this challenge in mind.

```
S!!Ṡ¡ȯuΞIṪ*İf

```

Try it online!

**More efficient version for 14 bytes:**

Try it online!
> 1 votes

# Answer
# Python 2, ~~129~~ ~~128~~ ~~125~~ ~~123~~ 121 bytes

```
g=lambda k:1/k|any(abs(round(5**.5*i)**2-5*i*i)==4>k%i<g(k/i)for i in range(k+1))
f=lambda n,k=1:n and f(n-g(k),k+1)or~-k

```

Test it on Ideone.
> 0 votes

---
Tags: code-golf, number-theory, fibonacci
---


# Question
Title: Print three columns vertically separated by space(s)
# Task

* Take input string separated by space.
* Sort the words alphabetically.
* Print them out vertically in 3 columns separated by space(s).

# Challenge

* All three column's heights should be as evenly weighted as possible.
* All three column's should be left aligned.

This is , so shortest code wins!

# Example

If the input is:

```
"cat caterpillar pie frog elephant pizza",

```

The output should be:

```
cat         elephant pie
caterpillar frog     pizza

```

Please beware of cases, if input is:

```
"a b c d e f g"

```

Should be printed as:

```
a c e
b d f
    g

# or

a d f
b e g
c

# and not

a d g
b e
c f

```

# Answer
> 4 votes
# Husk, ~~24~~ 17 bytes

```
TmoTT' §CȯmLTC3Ow

```

Try it online!

## Explanation

This was a surprisingly tricky challenge, as Husk currently lacks a builtin for breaking a list into a given number of parts.

```
TmoTT' §CȯmLTC3Ow  Implicit input, say s="bbb a cc ddd e"
                w  Split at spaces: x=["bbb","a","cc","ddd","e"]
             C3    Cut into slices of length 3: [["bbb","a","cc"],["ddd","e"]]
            T      Transpose: [["bbb","ddd"],["a","e"],["cc"]]
         ȯmL       Map length: [2,2,1]
                   These are the correct lengths of the columns.
       §C      O   Sort x and split into these lengths: [["a","bbb"],["cc","ddd"],["e"]]
                   These are the columns of the correct output, without padding.
 mo                For each column,
    T'             transpose and pad with spaces: [["ab"," b"," b"],["cd","cd"," d"],["e"]]
   T               then transpose back: [["a  ","bbb"],["cc ","ddd"],["e"]]
T                  Transpose the whole list: [["a  ","cc ","e"],["bbb","ddd"]]
                   Implicitly join each row by spaces,
                   join the resulting strings by newlines and print.

```

# Answer
> 2 votes
# Jelly, 6 bytes

```
Ṣœs3ZG

```

Try it online!

# Answer
> 2 votes
# Python 3, 148 bytes

*-6 bytes thanks to ovs.*

```
l=sorted(input().split())
n=-~len(l)//3
f=lambda l:[i.ljust(max(map(len,l)))for i in l+['']]
for i in zip(f(l[:n]),f(l[n:n*2]),f(l[n*2:])):print(*i)

```

Try it online!

~~Workin' on it.~~ *Everything* I've tried makes the output lopsided...

# Answer
> 1 votes
# Mathematica, 115 bytes

```
Grid[Transpose@PadRight@TakeList[#,Last@IntegerPartitions[Tr[1^#],3]]&@Sort@StringSplit@#/. 0->"",Alignment->Left]&

```

try it on wolfram sandbox

paste the following code and press shift+enter

```
Grid[Transpose@PadRight@TakeList[#,Last@IntegerPartitions[Tr[1^#],3]]&@Sort@StringSplit@#/. 0->"",Alignment->Left]&["cat caterpillar pie frog elephant pizza"]

```

# Answer
> 1 votes
# Perl 5, 134 + 1 (`-a`) = 135 bytes

```
$.=(sort{$b=~y///c-length$a}(@F=sort@F))[0]=~y///c;@a=splice@F,0,@F/3;@b=splice@F,0,@F/2;printf"%-$.s "x3 .$/,shift@a,shift@b,$_ for@F

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
#{.B3äζ»

```

Try it online!

---

```
#        | Split on spaces.
 {       | Sort aphabetically.
  .B     | Pad to max string length.
    3ä   | Split into columns.
      ζ  | Transpose.
       » | Print with newlines.

```

# Answer
> 1 votes
# Javascript 181 175 bytes

```
f=a=>(a=a.split` `).sort().map(c=>(t[y]=[...t[y]||[],c],M[x]>(l=c.length)?0:M[x]=l,a[++y*3+x]?y:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`
`

console.log(f("cat caterpillar pie frog elephant pizza"))
console.log("-------------------")
console.log(f("cat caterpillar pie frog frog123123 pizza"))
console.log("-------------------")
console.log(f("a b c d e f g"))
console.log("-------------------")
console.log(f("a b c d e f"))
console.log("-------------------")
console.log(f("a b c d e"))
console.log("-------------------")
console.log(f("a b c d"))

/*
f=a=>(a=a.split` `).sort().map(c=>((t[y] =t[y]||[])[x]=c,M[x]>(l=c.length)?0:M[x]=l,++y*3+x<a.length?0:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`\n`

f=a=>(a=a.split` `).sort().map(c=>(t[y]=[...t[y]||[],c],M[x]>(l=c.length)?0:M[x]=l,++y*3+x<a.length?0:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`\n`

*/
```

# Answer
> 0 votes
# , 73 bytes

```
,.@(' ',"1[:>|:)@((](s,(s=.]{.1:),(1:{.~[-2*]))([:<.0.5+%&3))@#];.1])@/:~

```

I can explain this mess later if someone is interested.

Try it online!

# Answer
> 0 votes
# Charcoal, ~~65~~ 64 bytes

```
≔⪪θ ηＦη«⊞υ⌊η≔⟦⟧ηＦ⪪θ ¿¬№υκ⊞ηκ»ＦＥ³✂υ÷×ιＬυ³÷×⊕ιＬυ³Ｉ1«Ｐ⪫ι¶¿ιＭ⊕⌈ＥιＬκ→

```

Try it online! Link is to verbose version of code. Save 2 bytes if I don't have to handle the case of fewer than 3 words. There's probably a sorting "eval" I should be using... Explanation:

```
≔⪪θ η

```

Split the input on spaces.

```
Ｆη«⊞υ⌊η≔⟦⟧ηＦ⪪θ ¿¬№υκ⊞ηκ»

```

Sort the array.

```
ＦＥ³✂υ÷×ιＬυ³÷×⊕ιＬυ³Ｉ1«

```

Loop over three approximately equal slices of the array. (`Ｉ1` should really be `¦¹`.)

```
Ｐ⪫ι¶

```

Join the slice with newlines and print it without moving the cursor.

```
¿ιＭ⊕⌈ＥιＬκ→

```

If the slice is not empty then move right by one more than the length of the longest word in the slice.

# Answer
> 0 votes
# 358 bytes of minified JS:

```
function f(b){let d=[,,,],e=b.split(" ").sort(),g=[],h=[];for(var j in e){var k=Math.min(2,Math.floor(j/Math.floor(e.length/3)));d[k]||(d[k]=[],g[k]=e[j].length),d[k].push(e[j]),2==k&&h.push(""),g[k]=Math.max(e[j].length,g[k])}for(var o in g)for(var p=0;p<g[o]+1;p++)for(var q in h)h[q]+=q>=d[o].length||p>=d[o][q].length?" ":d[o][q][p];return h.join("\n")}

```

```
function f(b){let d=[,,,],e=b.split(" ").sort(),g=[],h=[];for(var j in e){var k=Math.min(2,Math.floor(j/Math.floor(e.length/3)));d[k]||(d[k]=[],g[k]=e[j].length),d[k].push(e[j]),2==k&&h.push(""),g[k]=Math.max(e[j].length,g[k])}for(var o in g)for(var p=0;p<g[o]+1;p++)for(var q in h)h[q]+=q>=d[o].length||p>=d[o][q].length?" ":d[o][q][p];return h.join("\n")}

console.log(f("cat caterpillar pie frog elephant pizza"));
console.log(f("a b c d e f g"));
```

# Answer
> 0 votes
# GNU sed, 92 + 1 = 93 bytes

+1 bytes for `-r` flag.

I haven’t golfed this at all, but it turned out to be a lot simpler than I expected.

```
s/$/ /
s/(\S+ ){1,3}/:&\n/g
:
s/:(\S)/\1:/g
/:\S/!bZ
s/: / &/g
t
:Z
s/: / :/g
t
s/ *:.*$//gm

```

Try it online!

# Answer
> -1 votes
# Bourne shell, 172 bytes

```
F=/tmp/t
<$1 tr \  \\n|sort>$F
N=$(wc -w $F|awk '{print $1/3}')
for i in 0 1 2
do
awk 'NR%N==C {print}' N=$N C=$i $F
done|awk '{printf "%s%s",$1,NR%3?" ":"\n"}'|column -t

```

It's more readable if formatted conventionally:

```
#! /bin/sh
F=/tmp/t
<$1 tr \  \\n | sort > $F
N=$(wc -w $F | awk '{print $1/3}')

for i in 0 1 2
do
    awk -v N=$N -v C=$i 'NR % N == C {print}' $F
done |
    awk '{printf "%s%s", $1, NR % 3 == 0? "\n" : " " }' | column -t

```

At the price of scanning the input once per column, it uses no arrays. A more complex awk program could open 3 files (one for every Nth word), processing the input in one pass. Then they could be concatenated and printed using the same last line.

The variable `N` isn't strictly needed, either; for the price of 4 bytes, we save scanning the input 3 more times.

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


# Question
Title: The Median of Practically Recreational Languages
According to TIO there are two types of programming languages:

* Practical (seen in many corporate environments as a development standard).
* Recreational (if seen in a corporate environment, you're probably fired).

## Your Task

Mix together one language from each of these realms to achieve the simple goal of calculating the median of a list. You will write a program (or function) in one language of each type. The list will be composed entirely of integers, and will be fed as input to your first program. The output of that program will then be fed as input to the second program. For a valid answer, the output of the second language must always be the median of the list. Both programs must be at least 1 byte in length, and both must have an output that differs from their input in at least one case (e.g., neither program may be a cat program). If the list has an even number of elements, your program may output any value between the two elements of the list closest to the median (inclusive). The list is guaranteed to contain at least one element, and consist entirely of integers.

# Test Cases

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

[1,2,3,4,5,6] = 3-4

[-1,4,3,-2,0] = 0

[0,1,2,7,8,9] -> 2-7

[1,2,3,7,8,9] -> 3-7

```

## Scoring:

This is , lowest sum of the byte-count of the two programs wins.

# Answer
# Python \+ Actually, 6 + 1 = 7 bytes

```
sorted

```

**Try it online!**

**Try it online!**

The twist is that the Actually built-in for median () doesn't sort the list, hence it is perfectly combined with Python's `sorted()` built-in.
> 7 votes

# Answer
# Jelly \+ Python,  ~~4 3~~  2 + 3 = 5 bytes

-1 thanks to Mr. Xcoder (`;0` -\> `W` \- I considered this but incorrectly disregarded it as an option)
-1 thanks to Luis Mendo (drop the `W` and change from `sum` to `int`)

Part 1, Jelly function:

```
Æṁ

```

A function which, given a list of integers will return their median.
e.g. `[-1,-9,-2,-8,0,-7]` yields `-4.5`.

**Try it online!**

Part 2, Python function:

```
int

```

A function which given an integer or a floating point number returns an integer (dropping any fractional part).
e.g. `-4.5` yields `-4`.

**Try it online!**
> 2 votes

# Answer
# Jelly \+ Bash, ~~5~~ 4 + 3 = 7 bytes

```
ÆṁṾṚ

```

Try it online!

*-1 byte* thanks to *Jonathan Allan*

A monadic chain that takes a list and returns (is that the right terminology?) the stdin for the bash program.

```
rev

```

Try it online!

## Explanation

```
ÆṁṾṚ
  Ṿ   String representation
Æṁ    of the median
   Ṛ  reversed

```
> 1 votes

# Answer
# MATL \+ , 1 + 19 = 20 bytes

```
S

```

Try it online!

`S` reads in input as a matrix `[a_1, a_2, ..., a_n]` and then sorts it. Then the program terminates, printing the values as `b_1 b_2 ... b_n`, which is then read by R's `scan()` as a vector. The R program then computes the median and prints it out.

```
cat(median(scan()))

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js) \+ Pyth, 11 + 10 = 21 bytes

```
n=>n.sort()

```

Try it online!

```
.O@R/lQ2_B

```

Try it online!

## How the Pyth code works

```
.O@R/lQ2_B ~ Full program.

        _B ~ Bifurcate with reverse; Yields [Input, Reverse(Input)]
    /lQ2   ~ The length of the input divided by two, and floored.
  @R       ~ For each in ^^, get the element at index ^.
.O         ~ Average (arithmetic mean).

```
> 1 votes

# Answer
# Actually and Python, 1 + 3 = 4 bytes

## Actually, 1 byte

Full program that computes the median, possibly with a decimal part. Try it online!

## Python, 3 bytes

```
int

```

Defines a function that rounds towards zero. Try it online!
> 1 votes

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


title: Regex: Match an egalitarian series

text:
# Question
Title: Regex: Match an egalitarian series
# Introduction

I don't see many regex challenges on here, so I would like to offer up this deceptively simple one which can be done in a number of ways using a number of regex flavours. I hope it provides regex enthusiasts with a bit of fun golfing time.

# Challenge

The challenge is to match what I've very loosely dubbed an "egalitarian" series: a series of equal numbers of different characters. This is best described with examples.

Match:

```
aaabbbccc
xyz
iillppddff
ggggggoooooollllllffffff
abc
banana

```

Don't match:

```
aabc
xxxyyzzz
iilllpppddff
ggggggoooooollllllfff
aaaaaabbbccc
aaabbbc
abbaa
aabbbc

```

To generalize, we want to match a subject of the form `(c<sub>1</sub>)<sup>n</sup>(c<sub>2</sub>)<sup>n</sup>(c<sub>3</sub>)<sup>n</sup>...(c<sub>k</sub>)<sup>n</sup>` for any list of characters `c<sub>1</sub>` to `c<sub>k</sub>`, where `c<sub>i</sub> != c<sub>i+1</sub>` for all `i, k > 1, and n > 0.`

**Clarifications:**

* Input will not be empty.
* A character may repeat itself later in the string (eg. "banana")
* `k > 1`, so there will always be at least 2 different characters in the string.
* You can assume only ASCII characters will be passed as input and no character will be a line terminator.

# Rules

(Thank you to Martin Ender for this excellently-stated block of rules)

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's `e` modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly, e.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex must match the entire string for valid egalitarian strings and yield no matches for invalid strings. You may use as many capturing groups as you wish.

You may assume that the input will always be a string of two or more ASCII characters not containing any line-terminators.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually `/.../`) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

# Criteria

This is good ol' fashioned golf, so forget efficiency and just try to get your regex as small as possible.

Please mention which regex flavour you have used and, if possible, include a link showing an online demo of your expression in action.

# Answer
## .NET flavour, 48 bytes

```
^(.)\1*((?<=(\5())*(.))(.)(?<-4>\6)*(?!\4|\6))+$

```

Try it online! (using Retina)

Well, turns out that *not* negating the logic is simpler after all. I'm making this a separate answer, because the two approaches are completely different.

### Explanation

```
^            # Anchor the match to the beginning of the string.
(.)\1*       # Match the first run of identical characters. In principle,
             # it's possible that this matches only half, a quarter, an
             # eighth etc of of the first run, but that won't affect the
             # result of the match (in other words, if the match fails with
             # matching this as the entire first run, then backtracking into
             # only matching half of it won't cause the rest of the regex to
             # match either).
(            # Match this part one or more times. Each instance matches one
             # run of identical letters.
  (?<=       #   We start with a lookbehind to record the length
             #   of the preceding run. Remember that the lookbehind
             #   should be read from the bottom up (and so should
             #   my comments).
    (\5())*  #     And then we match all of its adjacent copies, pushing an
             #     empty capture onto stack 4 each time. That means at the
             #     end of the lookbehind, we will have n-1 captures stack 4,
             #     where n is the length of the preceding run. Due to the
             #     atomic nature of lookbehinds, we don't have to worry
             #     about backtracking matching less than n-1 copies here.
    (.)      #     We capture the character that makes up the preceding
             #     run in group 5.
  )
  (.)        #   Capture the character that makes up the next run in group 6.
  (?<-4>\6)* #   Match copies of that character while depleting stack 4.
             #   If the runs are the same length that means we need to be
             #   able to get to the end of the run at the same time we
             #   empty stack 4 completely.
  (?!\4|\6)  #   This lookahead ensures that. If stack 4 is not empty yet,
             #   \4 will match, because the captures are all empty, so the
             #   the backreference can't fail. If the stack is empty though,
             #   then the backreference will always fail. Similarly, if we
             #   are not at the end of the run yet, then \6 will match
             #   another copy of the run. So we ensure that neither \4 nor
             #   \6 are possible at this position to assert that this run
             #   has the same length das the previous one.
)+
$            # Finally, we make sure that we can cover the entire string
             # by going through runs of identical lengths like this.

```
> 12 votes

# Answer
## .NET flavour, 54 bytes

```
^(?!.*(?<=(\2)*(.))(?!\2)(?>(.)(?<-1>\3)*)(?(1)|\3)).+

```

Try it online! (using Retina)

I'm pretty sure this is suboptimal, but it's the best I'm coming up with for balancing groups right now. I've got one alternative at the same byte count, which is mostly the same:

```
^(?!.*(?<=(\3())*(.))(?!\3)(?>(.)(?<-2>\4)*)(\2|\4)).+

```

### Explanation

The main idea is to invert the problem, match non-egalitarian strings and put the whole thing in a negative lookahead to negate the result. The benefit is that we don't have to keep track of **n** throughout the entire string (because due to the nature of balancing groups, you usually consume **n** when checking it), to check that all runs are of equal length. Instead, we just look for a single pair of adjacent runs that *don't* have the same length. That way, I only need to use **n** once.

Here is a breakdown of the regex.

```
^(?!.*         # This negative lookahead means that we will match
               # all strings where the pattern inside the lookahead
               # would fail if it were used as a regex on its own.
               # Due to the .* that inner regex can match from any
               # position inside the string. The particular position
               # we're looking for is between two runs (and this
               # will be ensured later).

  (?<=         #   We start with a lookbehind to record the length
               #   of the preceding run. Remember that the lookbehind
               #   should be read from the bottom up (and so should
               #   my comments).
    (\2)*      #     And then we match all of its adjacent copies, capturing
               #     them separately in group 1. That means at the
               #     end of the lookbehind, we will have n-1 captures
               #     on stack 1, where n is the length of the preceding
               #     run. Due to the atomic nature of lookbehinds, we
               #     don't have to worry about backtracking matching
               #     less than n-1 copies here.
    (.)        #     We capture the character that makes up the preceding
               #     run in group 2.
  )
  (?!\2)       #   Make sure the next character isn't the same as the one
               #   we used for the preceding run. This ensures we're at a
               #   boundary between runs.
  (?>          #   Match the next stuff with an atomic group to avoid
               #   backtracking.
    (.)        #     Capture the character that makes up the next run
               #     in group 3.
    (?<-1>\3)* #     Match as many of these characters as possible while
               #     depleting the captures on stack 1.
  )
               #   Due to the atomic group, there are three two possible
               #   situations that cause the previous quantifier to stopp
               #   matching.
               #   Either the run has ended, or stack 1 has been depleted.
               #   If both of those are true, the runs are the same length,
               #   and we don't actually want a match here. But if the runs
               #   are of different lengths than either the run ended but
               #   the stack isn't empty yet, or the stack was depleted but
               #   the run hasn't ended yet.
  (?(1)|\3)    #   This conditional matches these last two cases. If there's
               #   still a capture on stack 1, we don't match anything,
               #   because we know this run was shorter than the previous
               #   one. But if stack 1, we want to match another copy of
               #   the character in this run to ensure that this run is
               #   longer than the previous one.
)
.+             # Finally we just match the entire string to comply with the
               # challenge spec.

```
> 9 votes

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


title: Minecraft Inventory Management

text:
# Question
Title: Minecraft Inventory Management
Minecraft inventory management is hard. You have 17 diamonds, but you need 7 to craft an enchantment table, a pickaxe, and a sword. Do you pick them up and right click 7 times? Or do you right click once and right click twice and take the 7 left? It's so confusing!

for those of you who are now confused, don't worry, I'll explain it all in a sec

# Challenge

Given the size of a stack of items and a desired amount, determine the least number of clicks to get that amount. You only need to handle up to 64 for both inputs and you may assume you have infinite inventory slots. You cannot use the drag-to-distribute trick.

# Definitions

The **inventory** is a collection of slots where you can store items.

A **slot** is a storage space in your inventory where you can place up to one type of item.

A **stack** is a number of items placed in the same group. For the purposes of this challenge, a stack is simply a bunch of items in the same place (so ignore stack-size)

The **cursor** is your pointy thingy. That cursor. It can have items "on it"; in other terms, if you clicked on a slot and picked up items, the items you picked up are "on the cursor" until you put them down.

# Specifications

There are four possible situations. Either you have an item on your cursor or you don't, and either you left click or you right click.

If you don't have an item on your cursor and you left-click on a slot, you pick up the entire stack.

If you don't have an item on your cursor and you right-click on a slot, you pick up half the stack, rounded up.

If you have an item on your cursor and you left-click on a slot, you place all of the items into that slot. (For all you Minecraft players, you won't have \>64 items for this challenge and they're all 64-stackable, and you only have one type so the item swap does not apply here)

If you have an item on your cursor and you right-click on a slot, you place one item into that slot.

So, you start with all of the items given (first input, or second; you may choose the order) in a slot, and you want to finish with having the desired amount (other input) in your cursor.

Let's run through an example. Say you start with 17 items and you want 7. First, you right-click on the stack, which means you have picked up 9 and there are 8 in that slot. Then, if you right-click on the stack again, you place one item back into the slot, leaving you with 8 and the slot with 9. Finally, you right-click again and you have 7 and the slot has 10. Thus, you would return `3` (the number of clicks).

If you manage to out-click-golf me, please tell me and I will edit the example :P

# Test Cases

These are manually generated, so please tell me if there are any errors. I do inventory management through jitter-clicking right click so I don't have experience with optimal inventory management :P

```
Given, Desired -> Output
17, 7 -> 3
64, 8 -> 5
63, 8 -> 5
10, 10 -> 1
10, 0 -> 0 # note this case
25, 17 -> 7

```

# Explanations

This challenge might be tricky for non-Minecraft players, I have no idea. Here are some explanations.

`64, 8 -> 5` because you pick up 32 using right click, place it down, pick up 16, place it down, then pick up 8.

`63, 8 -> 5` for the same reason.

`25, 17 -> 7` because you pick up 13, place it down, pick up 6 from the leftover 12, place 2 back into the leftover stack, and then place the 4 in the cursor into the 13, and then pick those up.

# Rules

* Standard loopholes apply
* You may assume that `0 <= desired <= given <= 64`
* You may take input in either order and do I/O in any reasonable format

# Answer
> 2 votes
# C++, ~~498~~ ~~482~~ 457 bytes

If this function is just called once, it can be 455 bytes.

I found that almost every online GCC compilers (including TIO) forbids me to omit the type of the function `f`. However, the GCC on my computer allows that, and I don't know why.

This one can handle large inputs if a slot can contain that number of items (though needs a larger array and will probably run out of time).

```
#import<bits/stdc++.h>
#define t N.first
#define X n.erase(n.find
#define p(c){if(c==r)return l;if(L.emplace(w={n,c},l).second)Q[U++]=w;}
#define T(S,C)n.insert(S);p(C)X(S));
using m=std::multiset<int>;using s=std::pair<m,int>;s Q[99999];int x,l,B,U;int f(int a,int r){if(!r)return 0;std::map<s,int>L;s f({a},B=0),w,N;L[Q[U=1]=f];for(;;){l=L[N=Q[B++]]+1;x=N.second;t.insert(0);for(int i:t){m n=t;X(i));if(x){T(i+x,0)T(i+1,x-1)}if(!x&&i){p(i)T(i/2,i-i/2)}}}}

```

Ungolfed:

```
#include <map>
#include <set>
#include <queue>
#include <iostream>

using namespace std;

struct state {
    multiset<int> t; int q;
    bool operator<(const state& i) const { return make_pair(t, q) < make_pair(i.t, i.q); }
};

int f(int a, int target) {
    if (target == 0) return 0;

    map<state, int> len;
    queue<state> qu;
    state first = {{a}, 0};
    qu.push(first);
    len[first] = 0;

    #define push(c) { state a = {n, c}; auto t = len.insert({a, l + 1}); if (t.second) { \
        if (a.q == target) return l + 1; qu.push(a); \
    } } // push new state into queue and check for termination
    #define next(stk, cur) { n.insert(stk); push(cur); n.erase(n.find(stk)); }
    // insert new stack, push new state, erase the stack (for another use)

    while (qu.size()) { // BFS cycle
        state now = qu.front();
        qu.pop();

        int q = now.q;
        int l = len[now];

        multiset<int> n(now.t);
        for (int i : now.t) { // click on non-empty stack
            n.erase(n.find(i));
            if (!q) { // nothing on cursor
                push(i); // click left
                next(i / 2, (i + 1) / 2); // click right
            }
            else { // item on cursor
                next(i + q, 0); // click left
                next(i + 1, q - 1); // click right
            }
            n.insert(i);
        }
        if (q) { // click on empty stack
            next(q, 0); // click left
            next(1, q - 1); // click right
        }
    }
}

```

# Answer
> 1 votes
# Jelly, 74 bytes

```
Ẏċ⁴¬
HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€
‘1¦€ṭ€⁹’¤
+1¦€⁹ṭ€0;ç
⁹Ȧ‘Ḥ¤ŀ
Ṫ;0ṙJ$çḢ
Wṭ0WÇ€Ẏ$ÑÐ¿L’

```

A full program with first input (3rd argument) the current stack and the second input (4th argument) the wanted cursor.

**Try it online!** Due to the implementation this hits the 60 second TIO time out for the `25, 17` test case. This may be remedied by removing the redundancies left in for golfiness using this 84 byter (which filters out zero-sized stacks and sorts those remaining with `ḟ€Ṣ¥0¦€0` at the end of link 6 and only keeps unique states at each step with the use of `Q$` in the Main link).

### How?

The program implements the defined state-machine.
It creates the original state `[0, [argument 1]]`
then steps through to all the next possible states repeatedly
until one is found matching `[argument 2, [...]]`.

Note: the program entry is at the "Main link" which is the bottommost one (`Wṭ0WÇ€Ẏ$ÑÐ¿L’`)

```
Ẏċ⁴¬ - Link 1, test a list of states for not having the desired cursor
Ẏ    - tighten by one
  ⁴  - program's fourth argument (second input) - desired cursor
 ċ   - count occurrences (the stack list will never match, so just inspecting the cursors)
   ¬ - logical negation

HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€ - Link 2, next states given a 0 cursor: list, rotatedStacks; number currentCursor (unused)
     µ€1¦€         - for each rotation of rotatedStacks apply to the first element:
H                  -   halve
   $               -   last two links as a monad
 Ċ                 -     ceiling
  ,                -     pair
    Ḟ              -   floor (vectorises) -- i.e. n -> [floor(ceil(n/2)),floor(n/2)]
                                                     = [ceil(n/2),floor(n/2)]
          F€       - flatten each -- i.e. each [[c1,f1],s2, s3,...] -> [c1,f1,s2,s3,...]
             ⁸     - chain's left argument, rotatedStacks
            ;      - concatenate -- i.e. [[c1,f1,s2,s3,...],[c2,f2,s3,...,s1],...,[s1,s2,s3,...],[s2,s3,...,s1],...]
                $€ - last two links as a monad for each:
              Ḣ    -   head
               ,   -   pair -- i.e. [c1,f1,s2,s3,...] -> [c1,[f1,s2,s3,...]]

‘1¦€ṭ€⁹’¤ - Link 3, next states given a non-0 cursor and a right-click: list, rotatedStacks; number currentCursor
 1¦€      - for each rotation of rotatedStacks apply to the first element:
‘         -   increment -- i.e. place an item into the first stack of each rotation
        ¤ - nilad followed by link(s) as a nilad:
      ⁹   -   chain's right argument -- currentCursor
       ’  -   decrement
    ṭ€    - tack each -- i.e. [s1-1,s2,s2,...] -> [currentCursor-1,[s1-1,s2,s2,...]]

+1¦€⁹ṭ€0;ç - Link 4, next states given a non-0 cursor: list, rotatedStacks; number currentCursor
 1¦€       - for each rotation of rotatedStacks apply to the first element:
    ⁹      -   chain's right argument -- currentCursor
+          -   add
     ṭ€0   - tack each to zero -- i.e. [s1+currentCursor,s2,s3,...] -> [0,[s1+currentCursor,s2,s3,...]]
         ç - call the last link (3) as a dyad -- get the right-click states
        ;  - concatenate

⁹Ȧ‘Ḥ¤ŀ - Link 5, next states: list, rotatedStacks; number currentCursor
     ŀ - call link at the given index as a dyad...
    ¤  -   nilad followed by link(s) as a nilad:
⁹      -     chain's right argument -- currentCursor
 Ȧ     -     any & all -- for our purposes zero if zero, one if not
  ‘    -     increment
   Ḥ   -     double
       - -- i.e. call link 2 if currentCursor is zero else call link 4

Ṫ;0ṙJ$çḢ - Link 6, next states: currentState  e.g. [cc, [s1, s2, s3, ...]]
Ṫ        - tail -- get the stacks, [s1, s2, s3, ...]
 ;0      - concatenate a zero - add an empty stack to the options for use
     $   - last two links as a monad for each:
    J    -   range(length)
   ṙ     -   rotate left by -- i.e. [[s2,s3,0,...,s1],[s3,0,...,s1,s2],[0,...,s1,s2,s3],[...,s1,s2,s3,0],...[s1,s2,s3,0,...]]
       Ḣ - head -- get the currentCursor, cc
      ç  - call the last link (5) as a dyad

Wṭ0WÇ€Ẏ$ÑÐ¿L’ - Main link: initialStack, requiredCursor
W             - wrap -- [initialStack]
 ṭ0           - tack to zero -- [0, [initialStack]]
   W          - wrap -- [[0, [initialStack]]]
         Ð¿   - loop while, collecting the results:
        Ñ     - ...condition: call next link (1) as a monad -- cursor not found
       $      - ...do: last two links as a monad:
    Ç€        -   call the last link (6) as a monad for each
      Ẏ       -   flatten the resulting list by one level
           L  - length
            ’ - decremented (the collect while loop keeps the input too)

```

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


title: Working Minesweeper

text:
# Question
Title: Working Minesweeper
Similar to generating minesweeper grids, although the challenge is to make a working minesweeper grid. **This will be longer code than normal (I think)**.

more information on minesweeper.

> Minesweeper is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.

**Required features:**

```
-Randomized mine generation
-8x8 field with 10 mines
-Mine and "unknown" flags
-Reveal nearby blank spaces when a blank space has been revealed.
-Input and output code: It must be playable.  (Input and output code counts in the total)

```

**Note on scoring**:

```
Anything that is needed to make the program work is counted.
If it can be deleted and not affect the program, get rid of it.
I will occasionally update the selected answer to shorter programs if needed.

```

I came across a more specific version of this problem in computer science class: make a working version with the shortest number of lines in visual basic (I got 57 lines), and I thought it will be an interesting challenge for code golf. If there are any suggestions for improving the question, please comment. Shortest code in bytes wins.

# Answer
> 4 votes
# Python 2.7 (487C)

```
"""
char meaning:
    '?': unknown flag
    '!': mine flag
    'x': default
how to play:
    Input 3 chars each time. The first char is the action
    and the rest form a position. For example, '013' means
    uncover grid (1,3), '110' means flag the grid (1,0).

    The top-left corner is (0, 0), bottom-left (7,0), etc.

    Player will lose after uncover a mine, the program will
    output "Bom". If the Player uncovers all grid that do
    not contain a mine, he wins and the program will output
    "Win".
"""
import random as Z
S=sum
M=map
T=range
P=[(i,j)for i in T(8)for j in T(8)]
C=dict(zip(T(-3,9),'?!x012345678'))
m={p:-1 for p in P}
h=Z.sample(P,10)
def U(p):
 if m[p]>=0:return 0
 n=filter(lambda(c,d):0<max(abs(p[0]-c),abs(p[1]-d))<2,P)
 m[p]=s=S((x in h)for x in n)
 return(1 if s else S(M(U,n))+1,-1)[p in h]
s=u=0
while(s<54)&(u>-1):
 f,i,j=M(int,raw_input(''.join((C[m[x]]+'\n '[x[1]<7])for x in P)))
 p=i,j;c=m[p]
 if f*(c<0):m[p]=-1-(-c)%3
 else:u=U(p);s+=u
print'WBionm'[s<54::2]

```

Full game experience:

```
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x
000
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
x 1 0 1 x x x x
070
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 x x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
123
0 0 1 x x x x x
0 0 2 x x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
113
0 0 1 x x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
003
0 0 1 1 x x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
004
0 0 1 1 1 x x x
0 0 2 ! x x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
014
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 x x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
154
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 x x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
044
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 x x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
034
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 x x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
035
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 x x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
045
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! x x x
x 1 0 2 x x x x
1 1 0 1 x x x x
055
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! x x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
124
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 x x x x
1 1 0 1 x x x x
164
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 x x x x
174
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 ! x x x
074
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! x x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
125
0 0 1 1 1 x x x
0 0 2 ! 4 x x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
005
0 0 1 1 1 1 x x
0 0 2 ! 4 x x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
015
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! x x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
126
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 x x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
036
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 3 x
0 0 0 1 1 1 x x
1 1 0 2 ! 2 x x
x 1 0 2 ! x x x
1 1 0 1 1 x x x
046
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! x
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
127
0 0 1 1 1 1 x x
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
007
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x x
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
017
0 0 1 1 1 1 x 1
0 0 2 ! 4 4 x 3
0 0 2 ! ! ! ! !
0 0 1 2 3 3 3 2
0 0 0 1 1 1 0 0
1 1 0 2 ! 2 0 0
x 1 0 2 ! 2 0 0
1 1 0 1 1 1 0 0
016
Win

```

The last step is dangerous, though.

# Answer
> 8 votes
## Javascript, 978 bytes (824 without CSS)

http://jsbin.com/otayez/6/

Checklist:

```
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine flags - Yes
"unknown" flags - no
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes

```

JS:

```
(function(){
    f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0;

    for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];
    for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);
    for(i=64;i--;z.id='b'+(63-i),c.appendChild(z))z=document.createElement('button');
    for(d=b;d--;)
      for(r=b;r--;)
        s.map(function(y){
          s.map(function(x){
            if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++;
          });
        });

    c.onclick=function(e){
        var t=e.target,
            i=t.id.slice(1),
            x=i%b,
            y=f(i/b),
            n=t.className=='b';

      if(t.innerHTML||(n&&!e.ctrlKey))return;
      if(e.ctrlKey)return t.className=(n?'':'b')

      if(q(x,y))alert('boom')
      if(l==54)alert('win')
    };
  function q(x,y){
    if(x<0||x>7||y<0||y>7)return;

    var p=y*b+x,
        v=g[y][x],
        t=document.all['b'+p];

    if(v!=m&&!t.innerHTML){
      t.innerHTML=g[y][x];
      t.className='f';
      l++;
      if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}
    }
    return v==m
  }
})();

```

MiniJS **812 bytes**:

```
f=Math.floor;r=Math.random;b=8,s=[-1,0,1],o='',m='*',l=0,h='b';for(g=[i=b];i;)g[--i]=[0,0,0,0,0,0,0,0];for(i=10,a=f(r()*64);i--;g[f(a/b)][a%b]=m)while(g[f(a/b)][a%b])a=f(r()*64);for(i=64;i--;z.id=h+(63-i),c.appendChild(z))z=document.createElement('button');for(d=b;d--;)for(r=b;r--;)s.map(function(y){s.map(function(x){if(g[d][r]!=m&&g[d+y]&&g[d+y][r+x]==m)g[d][r]++})});c.onclick=function(e){var t=e.target,i=t.id.slice(1),n=t.className==h;if(t.innerHTML||(n&&!e.ctrlKey))return;if(e.ctrlKey)return t.className=(n?'':h);if(q(i%b,f(i/b)))alert('boom');if(l==54)alert('win')};function q(x,y){if(x<0||x>7||y<0||y>7)return;var p=y*b+x,v=g[y][x],t=document.all[h+p];if(v!=m&&!t.innerHTML){t.innerHTML=g[y][x];t.className='f';l++;if(!v){t.className='z';s.map(function(d){s.map(function(r){q(x+r,y+d)})})}}return v==m}

```

HTML **12 bytes**

```
<div id="c">

```

The CSS isn't necessary from a functionality standpoint, but is from a usability standpoint:

```
#c{
  width:300px;
  height:300px;
}
button{
  width:12.5%;
  height:12.5%;
  line-height:30px;
}
.f,.z{
  background:#fff;
  border:solid 1px #fff;
}
.z{
  color:#fff;
}
.b{background:#f00}

```

Mini CSS **154 bytes**:

```
#c{width:300px;height:300px}button{width:12.5%;height:12.5%;line-height:30px}.f,.z{background:#fff;border:solid 1px #fff}.z{color:#fff}.b{background:#f00}

```

# Answer
> 4 votes
## C, 568, 557, 537

```
Checklist:
  Randomized mine generation - yes
  8x8 field with 10 mines - yes
  Mine and "unknown" flags - yes
  Reveal nearby blank spaces when a blank space has been revealed. - yes
  Input and output code: It must be playable. - yes

Further to playable:
  Win detection (found all mines, or revealed all empties)
  Bang detection (hit a mine)
  Game terminates.

Output format:
  # - unrevealed
  ! - a flagged mine
  * - a mine
  (number) - number of neighbouring mines
  ? - unknown flag

Input format:
  x y f
  - where x is 0..7, y is 0..7 (origin upper-left)
  - f is 0 to open up, 1 to flag a mine, and 2 to flag a unknown

```

example game:

```
./a.out
5 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 # #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
6 1 1
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 #
# # # 1 2 1 # #
# # # # # # # #
7 5 0
# 1 0 0 0 2 # #
# 1 0 0 0 2 ! #
# 1 0 0 0 1 1 1
# 1 0 0 0 0 0 0
# # 1 0 0 0 1 1
# # 1 0 0 0 1 *
# # # 1 2 1 # 1
# # # # # # # #
bang!

```

code:

```
// 8x8 grid but with padding before first row, after last row, and after last column, i.e. its 9x10
m[99]; // 0=empty,1=mine
u[99]; // 0=revealed,1=unrevealed,2=flag,3=unknown

// count neighbouring mines (8way)
c(i){return m[i-8]+m[i-9]+m[i-10]+m[i+8]+m[i+9]+m[i+10]+m[i-1]+m[i+1];}

// reveal (4way)
r(i){
    if(u[i]){
        u[i]=0;
        if(!c(i))r(i-9),r(i+9),r(i+1),r(i-1);
    }
}

i,x,y,f,e;
main(){
    // place 10 mines
    for(srand(time(0));i<10;){
        x=rand()%64;
        x+=9+x/8;
        if(!m[x]){
            m[x]=1;
            i++;
        }
    }
    for(;y<64;y++)u[y+9+y/8]=1; // mark visible grid as being unrevealed

    while(!e){
        // read input 0..7 0..7 0..2
        scanf("%d%d%d",&x,&y,&f);
        i=x+9+y*9;
        if(f)u[i]=f==1?2:u[i]==3?1:3;else r(i); // flag, toggle unknown/unrevealed, open

        // show grid and calc score
        for(y=f=x=0;x<64;x++){
            i=x+9+x/8;
            putchar(u[i]?" #!?"[u[i]]:m[i]?42:48+c(i)); // 42='*', 48='0'
            putchar(x%8==7?10:32);
            if(!u[i])y+=m[i]?-99:1;   // y = number of correctly open
            if(u[i]==2)f+=m[i]?1:-99; // f = number of correct mines
        }
        if(y<0||y==54||f==10)e=puts(y<0?"bang!":"win!"); // 54 = 64-10
    }
}

```

# Answer
> 4 votes
# Mathematica 566 548 1056

**Edit**: This is a complete rewrite. I gave up trying to obtain the shortest code and decided instead to build in the features that made most sense.

`r` indicates the number of rows in the grid. `c` indicates the number of columns in the grid. `m`: number of mines.

The game is played by mouse-clicking on the buttons. If the player clicks on a mine, the cell turns black and the program prints "You Lose!"

The checkbox "u" allows the player to peek at the complete solution at any time. The flags, "?" and "!" can be placed in any cell as desired.

```
DynamicModule[{s, x, f, l},
Manipulate[
Column[{
Grid[s],
If[u, Grid@f, Null]
}],
Grid[{{Control@{{r, 8}, 4, 16, 1, PopupMenu},
 Control@{{c, 8}, 4, 16, 1, PopupMenu},
 Control@{{m, 10}, 1, 50, 1, PopupMenu}},
{Button["New", i],
 Control@{{e, 0}, {0 -> "play", 1 -> "?", 2 -> "!"}, SetterBar},
 Control@{{u, False}, {True, False}}}}],
 Deployed -> True,

 Initialization :>
 (p = ReplacePart;
  q = ConstantArray;
  z = Yellow;
  w = White;
  b := Array[Button["  ", v[{#, #2}], Background -> z] &, {r, c}];
  a := RandomSample[l = Flatten[Array[List, {r, c}], 1], m];
  d[m1_] :=
   p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
    0], (# -> "*") & /@ (x)];
  n[y_] := Complement[Select[l, ChessboardDistance[y, #] == 1 &], x];
  d[m1_] :=
  p[ListConvolve[BoxMatrix@1, p[q[0, {r, c}], (# -> 1) & /@ m1], 2,
    0], (# -> "*") & /@ (x)];

  v[{r_, c_}] :=
   Switch[e,
    1, If[s[[r, c, 3, 2]] == z,
     s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "?", "  ", "?"]}],
     Null],

    2, If[s[[r, c, 3, 2]] == z,
    s = p[s, {{r, c, 1} -> If[s[[r, c, 1]] == "!", "  ", "!"]}],
    Null],
    3, Null,

    0, Switch[f[[r, c]],
     "*", (Print["You lose!"]; (s = p[s, {r, c, 3, 2} -> Black])),
     0, (s = p[s, {{r, c, 1} -> "  ", {r, c, 3, 2} -> w}];
      f = p[f, {{r, c} -> ""}]; v /@ n[{r, c}]),
     "  ", Null,
     _, (s = p[s, {{r, c, 1} -> f[[r, c]], {r, c, 3, 2} -> w}])]];

   i :=
   (x = a;s = b;f = d[x]);i) ] ]

```

**Initial State**

**At a later point...**

# Answer
> 2 votes
## Python (~~502~~ 566)

Checklist:

```
Randomized mine generation - yes
8x8 field with 10 mines - yes
Mine and "unknown" flags - yes
Reveal nearby blank spaces when a blank space has been revealed. - yes
Input and output code: It must be playable. - yes

```

It has a win detector as well.

Input is given while the game is running, with `(f, x, y)`. `(x, y)` is the coordinates of the grid selection, `f` is whether you want to flag or not. `(0, 0, 0)` would open up `(0, 0)`, and `(1, 2, 3)` would flag (2, 3). Flagging works in a cycle: flagging a square twice gives a question mark.

(number) - number of mines
(space) - unexplored
. - 0 mines
! - flag
" - question

```
import random
A=[-1,0,1]
R=lambda x:[x+i for i in[-9,-8,-7,-1,1,7,8,9]if(0<x+i<64)&([i,x%8]not in([7,0],[-7,7],[-1,0],[1,7]))]
M=lambda p:sum(G[i]=='*'for i in R(p))
def V(p):
 m=M(p);G[p]=`m`if m else'.'
 if m>0:return
 for c in R(p):
  if' '!=G[c]:continue
  m=M(c);G[c]=`m`
  if m==0:G[c]='.';V(c)
G=[' ']*54+['*']*10
random.shuffle(G)
while' 'in`G`:
 for i in range(8):print[j.replace('*',' ')[0]for j in G[8*i:8*i+8]]
 i=input()[::-1];a=i[0]*8+i[1];b=G[a]
 if i[2]:G[a]=(chr(ord(b[0])+1)if'"'!=b[0]else' ')+b[1:];continue
 if'*'==b:print'L';break
 if'!'!=b:V(a)

```

Needs to be improved: function R \[get all squares around item p\] (101 chars), printing (69 chars), flagging (72 chars)

# Answer
> 2 votes
# Dyalog APL, 113 bytes

`{⎕←1 0⍕c+○○h⋄10=+/,h:1⋄m⌷⍨i←⎕:0⋄∇{~⍵⌷h:0⋄(⍵⌷h)←0⋄0=⍵⌷c:∇¨(,⍳⍴m)∩⍵∘+¨,2-⍳3 3⋄0}i}h←=⍨c←{⍉3+/0,⍵,0}⍣2⊢m←8 8⍴10≥?⍨64`

non-competing: no "mine" and "unknown" flags

prints `*` for unopened cells and digits for opened (including `0`)

repeatedly asks the user for the 1-based coordinates of a cell to open

ultimately outputs `0` on failure (mine opened) or `1` on success (only 10 unopened left)

looks like this:

```
********
********
********
********
********
********
********
********
⎕:
      1 1
00000000
11012321
*112****
********
********
********
********
********
⎕:
      3 8
00000000
11012321
*112***1
********
********
********
********
********
⎕:
      4 7
00000000
11012321
*112***1
******3*
********
********
********
********
⎕:

```

...

---
Tags: code-golf, minesweeper
---