title: Simulating Exploding Dice

text:
# Question
Title: Simulating Exploding Dice
Your task is to make a program that takes in an integer `n > 1`, and outputs the roll of a single `n`-sided die. However, this dice follows the rules for exploding dice.

When you roll the die, check what value you rolled. If you got the maximum for that kind of die (on a standard d4 that would be 4, or 6 on a d6, etc.), roll again and add the new roll to that total. Each roll continues adding to the total, until you don't roll the max number anymore. That final number is still added though.

Your program should take in a single integer `n`, and roll the exploding `n`-sided die. Here's an example distribution to show what it should look like for `n=4` Note that you should never output any multiples of `n`, since they will always explode.

You can assume the stack size for any recursion you do is infinite, and your random function must meet our standards for randomness (built-in random generator or time/date). Your random function should also be as uniform as possible, vs. something like a geometric distribution, since these are dice we're talking about.

# Answer
# x86 Machine Code (for Intel Ivy Bridge and later), 17 bytes

```
31 C9 0F C7 F0 31 D2 F7 F6 42 01 D1 39 F2 74 F2 C3

```

The above bytes of code define a function that simulates an exploding die. It takes a single input, passed in the `ESI` register, indicating the maximum number of the die. It returns a single value in the `ECX` register, which is the result of the rolls.

Internally, it uses the `RDRAND` instruction to generate a random number. This uses a random number generator (RNG) that is built into the hardware on Intel Ivy Bridge processors and later (some AMD CPUs also support this instruction).

The logic of the function is otherwise quite straightforward. The generated random number is scaled to lie within the desired range using the standard technique (`(rand % dieSize) + 1`), and then it is checked to see if it should cause an explosion. The final result is kept in an accumulator register.

Here is an annotated version showing the assembly language mnemonics:

```
           unsigned int RollExplodingDie(unsigned int dieSize)
31 C9        xor     ecx, ecx    ; zero-out ECX, which accumulates the final result
           Roll:
0F C7 F0     rdrand  eax         ; generate a random number in EAX
31 D2        xor     edx, edx    ; zero-out EDX (in preparation for unsigned division)
F7 F6        div     esi         ; divide EDX:EAX by ESI (the die size)
                                 ;   EAX receives the quotient; EDX receives the remainder
42           inc     edx         ; increment the remainder
01 D1        add     ecx, edx    ; add this roll result to the accumulator
39 F2        cmp     edx, esi    ; see if this roll result should cause an explosion
74 F2        jz      Roll        ; if so, re-roll; otherwise, fall through
C3           ret                 ; return, with result in ECX register

```

I am cheating *a bit*. All standard x86 calling conventions return a function's result in the `EAX` register. But, in true machine code, there are no calling conventions. You can use any registers you want for input/output. Using `ECX` for the output register saved me 1 byte. If you want to use `EAX`, insert a 1-byte `XCHG eax, ecx` instruction immediately before the `ret` instruction. This swaps the values of the `EAX` and `ECX` registers, effectively copying the result from `ECX` into `EAX`, and trashing `ECX` with the old value of `EAX`.

**Try it online!**

Here's the equivalent function transcribed in C, using the `__builtin_ia32_rdrand32_step` intrinsic supported by GCC, Clang, and ICC to generate the `RDRAND` instruction:

```
#include <immintrin.h>

unsigned int RollExplodingDie(unsigned int dieSize)
{
    unsigned int result = 0;
Roll:
    unsigned int roll;
    __builtin_ia32_rdrand32_step(&roll);
    roll    = ((roll % dieSize) + 1);
    result += roll;
    if (roll == dieSize)   goto Roll;
    return result;
}

```

Interestingly, GCC with the `-Os` flag transforms this into almost exactly the same machine code. It takes the input in `EDI` instead of `ESI`, which is completely arbitrary and changes nothing of substance about the code. It must return the result in `EAX`, as I mentioned earlier, and it uses the more efficient (but larger) `MOV` instruction to do this immediately before the `RET`. Otherwise, samezies. It's always fun when the process is fully reversible: write the code in assembly, transcribe it into C, run it through a C compiler, and get your original assembly back out!
> 38 votes

# Answer
# , 39 bytes

```
n=scan();n*rgeom(1,1-1/n)+sample(n-1,1)

```

Try it online!

Explanation: this solution avoids recursion/while loops by directly calculating the distribution of the number of explosions that will occur. Let \\$n\\$ be the number of sides on the die. If you denote success as rolling an \\$n\\$ and failure as rolling anything else, then you have probability \\$\frac1n\\$ of success. The total number of explosions is the number of successes before the first failure. This corresponds to a \\$\mathrm{Geometric}\left(1-\frac{1}{n}\right)\\$ distribution (see the wikipedia page, which defines success and failure the other way round). Each explosion brings \\$n\\$ to the total. The final roll follows a \\$\mathrm{Uniform}(1,2,\ldots,n-1)\\$ distribution which we add to the total.
> 12 votes

# Answer
# Python 2, ~~66~~ ~~64~~ 61 bytes

-3 bytes thanks to xnor

```
f=lambda n,c=0:c%n or c+f(n,randint(1,n))
from random import*

```

Try it online!

The previous roll is stored in `c`, allowing us to access it multiple times without having to store it to a variable, which can't be done in a Python lambda. Each recursion, we check if we rolled exploding dice.

`c` is initialised to zero, so `c%n` is falsey there. In the next iterations, it will only be falsey if exploding dice were rolled.

# Python 2, 55 bytes

```
f=lambda n:randint(1,n)%n or n+f(n)
from random import*

```

Try it online!

My other answer seems to be a bit overengineered, since this appears to work as well... I'll leave it anyway.
> 12 votes

# Answer
# Perl 6, 26 bytes

```
{sum {roll 1..$_:}...*-$_}

```

Try it online!

### Explanation

```
{                        } # Anonymous block
                  ...      # Sequence constructor
     {roll 1..$_:}         #   Next elem is random int between 1 and n
                           #   (Called as 0-ary function with the original
                           #   $_ for the 1st elem, then as 1-ary function
                           #   with $_ set to the previous elem which
                           #   equals n.)
                     *-$_  #   Until elem not equal to n (non-zero difference)
 sum                       # Sum all elements

```
> 10 votes

# Answer
# , ~~16~~ 11 bytes

```
(+$:)^:=1+?

```

Try it online!

## Explanation

**TL;DR** `1+?` performs the die roll, `(+$:)^:=` reiterates only when it equals the input.

---

The function is a train of 4 verbs:

```
             ┌─ +
         ┌───┴─ $:
  ┌─ ^: ─┴─ =
  │
──┤      ┌─ 1
  └──────┼─ +
         └─ ?

```

A train is when 2 or more verbs are concatenated. Here, the answer is of the form `f g h j`:

```
(+$:)^:=  1  +  ?
    f     g  h  j

```

A so-called "4-train" is parsed as a hook and a fork:

```
f g h j   ⇔   f (g h j)

```

Thus, the answer is equivalent to:

```
(+$:)^:= (1 + ?)

```

### Hooks: `(f g) x` and `x (f g) y`

A monadic (one-argument) hook of two verbs, given an argument `x`, the following equivalence holds:

```
(f g) x   ⇔   x f (g x)

```

For example, `(* -) 5` evaluates to `5 * (- 5)`, which evaluates to `_25`.

This means that our 4-train, a hook of `f` and `(g h j)`, is equivalent to:

```
(f (g h j)) x   ⇔   x f ((g h j) x)

```

But what does `f` do here? `(+$:)^:=` is a conjunction of two verbs using the **Power** conjunction `^:`: another hook (`(+$:)`) and a verb (`=`). Note here that `f` is *dyadic*—it has two arguments (`x` and `(g h j) x`). So we have to look at how `^:` behaves. The power conjunction `f^:o` takes a verb `f` and either a verb or a noun `o` (a noun is just a piece of data) and applies `f` `o` times. For example, take `o = 3`. The following equivalences holds:

```
(f^:3) x     ⇔   f (f (f x))
x (f^:3) y   ⇔   x f (x f (x f y))

```

If `o` is a verb, the power conjunction will simply evaluate `o` over the arguments and use the noun result as the repeat count.

For our verb, `o` is `=`, the equality verb. It evaluates to `0` for differing arguments and to `1` for equal arguments. We repeat the hook `(+$:)` once for equal arguments and no times for differing ones. For ease of notation for the explanation, let `y ⇔ ((g h j) x)`. Remember that our initial hook is equivalent to this:

```
x   (+$:)^:=   ((g h j) x)
x   (+$:)^:=   y

```

Expanding the conjunction, this becomes:

```
x ((+$:)^:(x = y)) y

```

If `x` and `y` are the same, this becomes:

```
x (+$:)^:1 y   ⇔   x (+$:) y

```

Otherwise, this becomes:

```
x (+$:)^:0 y   ⇔   y

```

Now, we've seen monadic forks. Here, we have a dyadic fork:

```
x (f g) y   ⇔   x f (g y)

```

So, when `x` and `y` are the same, we get:

```
x (+$:) y   ⇔   x + ($: y)

```

What is `$:`? It refers to the entire verb itself and allows for recursion. This means that, when `x` and y`are the same, we apply the verb to`y`and add`x\` to it.

### Forks: `(g h j) x`

Now, what does the inner fork do? This was `y` in our last example. For a monadic fork of three verbs, given an argument `x`, the following equivalence hold:

```
(g h j) x   ⇔   (g x) h (j x)

```

For this next example, suppose we have verbs named `SUM`, `DIVIDE`, and `LENGTH`, which do what you suppose they might. If we concatenate the three into a fork, we get:

```
(SUM DIVIDE LENGTH) x   ⇔   (SUM x) DIVIDE (LENGTH x)

```

This fork evaluates to the average of `x` (assuming `x` is a list of numbers). In J, we'd actually write this as example as `+/ % #`.

One last thing about forks. When the leftmost "tine" (in our symbolic case above, `g`) is a noun, it is treated as a constant function returning that value.

With all this in place, we can now understand the above fork:

```
(1 + ?) x   ⇔   (1 x) + (? x)
            ⇔   1 + (? x)

```

`?` here gives a random integer in the range \\$\[0,x)\\$, so we need to transform the range to represent dice; incrementing yields the range \\$\[1, x\]\\$.

### Putting it all together

Given all these things, our verb is equivalent to:

```
((+$:)^:=1+?) x   ⇔   ((+$:)^:= 1 + ?) x
                  ⇔   ((+$:)^:= (1 + ?)) x
                  ⇔   x ((+$:)^:=) (1 + ?) x
                  ⇔   x ((+$:)^:=) (1 + (? x))
                  ⇔   x (+$:)^:(x = (1 + (? x))
(let y = 1 + (? x))
if x = y          ⇒   x + $: y
otherwise         ⇒   y

```

This expresses the desired functionality.
> 9 votes

# Answer
# Jelly, 7 bytes

```
X+ß}¥=¡

```

Try it online!

Uses recursion. Runs the program again (`ß`) and adds (`+`) if (`¡`) the random number (`X`) is equal (`=`) to the program input. `}` makes `ß` act on the program input and `¥` combines `+ß}` into a single link for `¡` to consume.

Here a distribution of 1000 outputs for n=6 which I collected using this program. Plotted with python/matplotlib.

Here is a 5000 data points from n=3 on a semilog plot which shows the (approximately?) exponential distribution.
> 7 votes

# Answer
# Pyth - ~~12~~ 11 bytes

Uses functional while. I feel like there should be a smarter answer that just simulates the distribution.

```
-.W!%HQ+hOQ

-         (Q)         Subtract Q. This is because we start Z at Q to save a char
 .W                   While, functionally
  !                   Logical not. In this case, it checks for 0
   %HQ                Current val mod input
  +     (Z)           Add to current val
   h                  Plus 1
    OQ                Random val in [0, input)

```

Try it online.
> 6 votes

# Answer
# Japt, 12 bytes

It may be shorter than dana's solution, but it's a hell of a lot uglier. I'm only posting it 'cause it seems like forever since we had a Japt solution that started with an empty line.

```

ö
>°V©VªV+ß
```

Try it
> 5 votes

# Answer
# JavaScript (ES6),  ~~39~~  30 bytes

*Saved 9 bytes thanks to @tsh!*

```
f=n=>Math.random()*n|0||n+f(n)

```

Try it online! or See the distribution for n=4
> 4 votes

# Answer
# Python 3, 80 bytes

```
import random as r,math
lambda n:int(-math.log(r.random(),n))*n+r.randint(1,n-1)

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
[ILΩDIÊ#}O

```

Try it online or verify the lists.

**10 bytes alternative:**

```
[LΩDˆÊ#}¯O

```

Try it online or verify the lists.

Although I like the top one more because it got the 'word' `DIÊ` in it, which suits the challenge.

**Explanation:**

```
[         # Start an infinite loop:
 IL       #  Create a list in the range [1, input]
   Ω      #  Pop and push a random value from this list
    D     #  Duplicate it
     IÊ   #  If it's NOT equal to the input:
       #  #   Stop the infinite loop
}O        # After the loop: sum all values on the stack
          # (which is output implicitly as result)

[         # Start an infinite loop
 L        #  Create a list in the range [1, (implicit) input]
  Ω       #  Pop and push a random value from this list
   Dˆ     #  Add a copy to the global_array
     Ê    #  If it's NOT equal to the (implicit) input:
      #   #   Stop the infinite loop
}¯        # After the loop: push the global_array
  O       # Pop and push its sum
          # (which is output implicitly as result)

```
> 4 votes

# Answer
# , ~~47~~ 42 bytes

```
function(n){while(!F%%n)F=F+sample(n,1)
F}

```

Try it online!

Credit to ArBo's approach.

Still a byte longer than Robin Ryder's, go upvote his!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 50 bytes

```
R@#//.x_/;x~Mod~#==0:>x+R@#&
R=RandomChoice@*Range

```

Try it online!
> 3 votes

# Answer
# Ruby, 35 bytes

```
->n,s=0{s+=x=1+rand(n);x<n||redo;s}

```

Try it online!
> 3 votes

# Answer
# Haskell, 77 76 bytes

```
import System.Random
f x=randomRIO(1,x)>>=(x!)
x!y|y<x=pure y|0<1=(y+)<$>f x

```

Try it online!

Thanks to killmous for one byte.

If `<|>` were in the prelude, we could do better with `MonadComprehensions`:

# Haskell, non-competing, 66 bytes

```
import System.Random
f x=do y<-randomRIO(1,x);[y|y<x]<|>(y+)<$>f x

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~94~~ ~~81~~ 78 bytes

```
import System.Random
f n=do i<-randomRIO(1,n);last$((i+)<$>f n):[return i|i<n]

```

Try it online!

---

Original

Quite similar to @dfeuer's, but using `do` notation.

* -13 bytes by removing whitespace, thanks to @dfeuer
* -3 bytes thanks to this
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~15~~ 14 bytes

```
{×r←?⍵:r⋄⍵+∇⍵}

```

Try it online!
> 3 votes

# Answer
# Python 2, 53 bytes

```
f=lambda n:random()*n//1or n+f(n)
from random import*

```

Try it online!

Uses the `or` short-circuiting idea from ArBo's answer. The expression `random()*n//1` generates a number from `0` to `n-1`, with `0` taking the place of a roll of `n`. The `or` takes the that number, except if it's zero (Falsey) it continues on to `n+f(n)`.
> 3 votes

# Answer
# Japt, 13 bytes

```
ö)g@¶°X?X+ß:X

```

Try it

Port of Arnauld's answer. Figured out how to make a recursive call ;)

Transpiled JS:

```
// U: Implicit input
// ö: generate a random number [0,U)
(U.ö())
  // g: run the result through a function
  .g(function(X, Y, Z) {
    // increment the result and compare to input
    return U === (++X)
      // if they are the same, roll again and add to current roll
      ? (X + rp())
      // if they are different, use current roll
      : X
   })

```
> 3 votes

# Answer
# Python 3, ~~81~~ 72 bytes

```
from random import*
def f(x,a=0):
 while a%x<1:a+=randint(1,x)
 return a

```

Try it online!

-9 bytes thanks to ArBo

## Explanation

```
import random             #load the random module
def explodeDice(num):     #main function
    ans = 0                     #set answer to 0
    while a % num != 0:         #while a isn't a multiple of the input
        ans += random.randint(1, num) #add the next dice roll to answer
    return ans                  #return the answer

```
> 2 votes

# Answer
# Forth (gforth), 72 bytes

```
include random.fs
: f >r 0 begin i random 1+ >r i + r> i < until rdrop ;

```

Try it online!

### Code Explanation

```
include random.fs      \ include library file for random
: f                    \ start a new word definition
  >r                   \ stick the input on the return stack (for easy access)
  0                    \ add a counter to hold the sum
  begin                \ start an indefinite loop
    i random 1+        \ generate a random number from 1 to n
    >r i + r>          \ add the result to the counter, use the return stack to save a few bytes
    i <                \ check if result was less than n
  until                \ end the loop if it was, otherwise go back to begin
  rdrop                \ remove n from the return stack
;                      \ end the word definition

```
> 2 votes

# Answer
# TI-BASIC, ~~28~~ 23 bytes

*-5 bytes thanks to this meta post!*

```
Ans→N:0:Repeat fPart(Ans/N:Ans+randInt(1,N:End:Ans

```

Input is in `Ans`.
Output is in `Ans` and is implicitly printed.

**Examples:**

```
4
              4
prgmCDGF11
              5
6
              6
prgmCDGF11
              3

```

**Explanation:**

```
Ans→N:0:Repeat fPart(Ans/N:Ans+randInt(1,N:End:Ans   ;full logic

Ans→N                                                ;store the input in "N"
      0                                              ;leave 0 in "Ans"
        Repeat fPart(Ans/N                 End       ;loop until the sum
                                                     ; is not a multiple of
                                                     ; the input
                               randInt(1,N           ;generate a random
                                                     ; integer in [1,N]
                           Ans+                      ;then add it to "Ans"
                                               Ans   ;leave the sum in "Ans"
                                                     ;implicitly print "Ans"

```

---

**Notes:**

* TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
> 2 votes

# Answer
# Excel VBA, 46 bytes

Thanks to @TaylorRaine

```
Do:v=-Int(-[A1]*Rnd):t=t+v:Loop While[A1]=v:?t

```

Executed in the command window.

As a user-defined function.

# Excel VBA, ~~108~~ 67 bytes

```
Function z(i)
Do
v=Int((i*Rnd)+1)
z=z+v
Loop While v=i
End Function

```
> 2 votes

# Answer
# PowerShell, 49 bytes

```
for($a=$l="$args";$a-eq$l){$o+=$l=1..$a|Random}$o

```

Try it online!

Iterative method. Sets the input `$args` to `$a` and the `$l`ast roll (done so we enter the loop at least once). Then, so long as the last roll is `-eq`ual to the input, we keep rolling. Inside the loop we accumulate into `$o` the last roll, which is updated by creating a range from `1` to input `$a` and picking a `Random` element thereof. *(Honestly, I'm a little surprised that `$o+=$l=` works.)* Once we're out of the loop, we leave `$o` on the pipeline and output is implicit.
> 2 votes

# Answer
## Batch, 70 bytes

```
@set t=0
:g
@set/at+=d=%random%%%%1+1
@if %d%==%1 goto g
@echo %t%

```

Takes input `n` as a command-line parameter `%1`. `d` is the current roll, `t` the cumulative total. Simply keeps rolling until `d` is not equal to `n`.
> 2 votes

# Answer
# Jelly, 9 bytes

```
x⁹X€Ä%ƇµḢ

```

Try it online!

A monadic link that takes n as its argument and returns a number generated by an exploding n-sided die. This generates 256 numbers from 1 to n and returns the first cumulative sum that is not a multiple of n. In theory this could return 256n, but even for a 2-sided die this would happen only one every \\$2^{256}\\$ times.

An alternative that doesn’t have this limitation is:

# Jelly, 10 bytes

```
X³X¤+¥³ḍ¥¿

```

Try it online!

Note both TIO links generate 400 numbers to show the distribution.
> 2 votes

# Answer
# SmileBASIC 3, 49 bytes

Function `D N OUT R` implements exploding dice rolls recursively.

```
DEF D N OUT R
R=RND(N)+1IF R==N THEN R=R+D(N)
END

```

## Ungolfed

```
DEF D N OUT R  'N is sides and R is output param (shorter than using RETURN in this case)
 R=RND(N)+1  'random number in [1, N]
 IF R==N THEN R=R+D(N)  'if roll is same as N then roll again and add
END

```

Note that in SmileBASIC, functions can have multiple return values. If a function has one return value then `fun in OUT var` and `var = fun(in)` are exactly the same, which is why we can define the function in `OUT` form and also call it in an expression in the function body itself. If I had defined the function as `DEF D(N)` I would have to explicitly state `RETURN R` in the function body; mixing both syntaxes saved me bytes.
> 2 votes

# Answer
# PowerShell, 43 bytes (Iterative method)

```
param($n)do{$x+=1..$n|random}until($x%$n)$x

```

Try it online!

---

# PowerShell, 48 bytes (recursive method)

```
filter f{if($_-eq($x=1..$_|random)){$x+=$_|f}$x}

```

Try it online!
> 2 votes

# Answer
# Jelly, 7 bytes

```
X=Ð¿⁸S_

```

A monadic Link accepting an integer, `n`, which yields an integer.

**Try it online!** Or see the counts of \\$10^5\\$ runs

### How?

```
X=Ð¿⁸S_ - Link: integer, n
  Ð¿    - Collect up while...
 =  ⁸   - ...condition: equal to chain's left argument, n
X       - ...next value: random number in [1..n]
     S  - sum
      _ - subtract n (since the collection starts with [n])

```
> 2 votes

# Answer
# SmileBASIC, 41 bytes

```
INPUT N@L
S=S+RND(N)+1ON S MOD N GOTO@L?S

```

After reading:

> Note that you should never output any multiples of n, since they will always explode.

I realized that rather than checking if a dice roll was `n`, you can just repeat while the sum is a multiple of `n`.
> 2 votes

# Answer
# AnyDice, 36 bytes

Almost a built-in in the language:

```
function:f I:n{result: [explode dI]}

```

For this to be correct I have to abuse the infinite recursion depth assumption. AnyDice limits the recursion depth with a global property maximum function depth. the explode builtin however uses it's own; explode depth - which defaults to 2.

```
set "explode depth" to 99

```

Would add another 25 bytes; and would not really match the requirements since it's theoretically possible for a dice to explode more than 99 times.

The output of the function is a die, ie. an AnyDice built-in type that is a paring of results and probabilities for the result.
> 2 votes

# Answer
# CJam, 19 bytes

```
qi{__mr)_T+:T;=}g;T

```

Explanation:

```
T is pre-set to 0

qi{__mr)_T+:T;=}g;T - whole code
qi                  - read input as integer (n) | Stack: n
  {            }    - block
   __               - Duplicate twice | Stack: n n n
     mr)            - Choose a random number from 1 to n (r). Since 'mr' picks a
                      number from 0 to n-1, the number has to be incremented with ')'
                      Stack: n n r
        _           - Duplicate |  Stack: n n r r
         T          - push T | Stack: n n r r T
          +         - add the random number to T (t) | Stack: n n r t
           :T;      - pop the value and store in T | Stack: n n r
              =     - are the top two stack values the same (c) | Stack: n c
               }
                g   - do while loop that pops the condition from the stack after each
                      iteration | Stack: n
                 ;  - pop the top stack element and discard | Stack: T
                  T - push T | Stack: T
                    - implicit output

```

Or in pseudocode:

```
input n
var sum = 0
do {
    var random_number = pick random number from 1 to n
    sum = sum + random_number
} while (random_number == n)
output n

```

As a flowchart:

Try it online!
> 2 votes

# Answer
# Excel (pure), 43 bytes

```
=A1*INT(-LOG(RAND(),A1))-INT(RAND()*(1-A1))

```

Takes input from A1, outputs in the cell you put this formula.

# Explanation

This uses the observation from Robin Ryder's R solution that the requested distribution is the sum of `n` times a `Geom(1-1/n)` and an independent `Uniform(1..n-1)` distribution. The clever bit is that

```
INT(-LOG(RAND(),A1))

```

uses a logarithm to scale a `Uniform(0,1)` distribution exactly to the desired geometric distribution: for instance, with A1=6, the `LOG` maps the interval `(1/6,1)` to the interval `(-1,0)`, the interval `(1/36,1/6)` to the interval `(-2, -1)`, and so on. I also save a `+1` on the uniform distribution by scaling a random number "backwards" to `(1-A1, 0)`, then subtracting the floor of this negative number.
> 2 votes

# Answer
# Octave/MATLAB with Statistics Package/Toolbox, 30 bytes

```
@(n)geornd(1-1/n)*n+randi(n-1)

```

**Try it online!**

### How it works

This is an anonymous function which takes `n` as input and produces a number obtained as follows. The function generates a geometric random variable with parameter `1-1/n` (this models the number of rolls that produce `n`), multiplies by `n`, and adds a random variable uniformly distributed from `1` to `n-1` (this models the last roll).
> 2 votes

# Answer
# Vyxal, ~~25~~ 10 bytes

```
λ?:ɾ℅~=[x+

```

Try it Online!

-15 thanks to Aaron Miller. This is a fully functional program as lambdas are automatically called at the end.
> 2 votes

# Answer
# \>\<\>, 90 bytes

```
0&  v
v:::<             <
v/1>{1-:?!v}
>x0^v10~  <
 ^
5=?v>:@}}*{+{2*l
&n;>,*:1%-1+:&+&=?^

```

Try it online!

The whitespace on the second line is bugging me. I'll work on golfing that out.

---

`><>` doesn't have a nice method for producing uniform random integers. This approach generates, for input \\$N\\$, a random number produced by generating \\$N\\$ random bits, then taking the resulting binary integer and dividing it by \\$2^N\\$. This process is repeated until \\$N\\$ is not generated by this process.
> 1 votes

# Answer
# C (gcc), ~~36~~ 32 bytes

*-4 bytes thanks to Ben Voigt*

```
f(n,x){x=rand()%n;x=x?x:n+f(n);}

```

Try it online!

Here a Test with 100k d4
> 1 votes

# Answer
# Attache, 30 bytes

```
f:=${If[x=y,f@x+y,y]}#1&Random

```

Try it online!

Direct implementation of the process.

## Alternatives

**36 bytes:** `${NestWhile[{_+Random[1,x]},x&`|,0]}`

**37 bytes:** `${NestWhile[{_+Random[1,x]},{x|_},0]}`
> 1 votes

# Answer
# Perl 6, 26 bytes

```
{[+] {^$_ .roll+1}...$_>*}

```

Try it online!
> 1 votes

# Answer
# Python 3, 80 bytes

This is pretty much just a tail-call recursive version of @Artemis Fowl's answer, but I liked doing it without unrolling into a while loop.

Uses an accumulator parameter to return the total rolled value once the exploding stops.

```
from random import*
def r(n,a=0):v=randint(1,n);a+=v;return r(n,a)if v==n else a

```
> 1 votes

# Answer
# Charcoal, 17 bytes

```
ＮθＷ⁼Ｌυ№υθ⊞υ⊕‽θＩΣυ

```

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

```
Ｎθ

```

Input `n`.

```
Ｗ⁼Ｌυ№υθ

```

Repeat while the predefined empty list only contains `n`s (i.e. its length equals its count of `n`s)...

```
⊞υ⊕‽θ

```

... push a random integer from `1` to `n` to the list.

```
ＩΣυ

```

Print the total.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 60 bytes

```
int f(int n,int k=1)=>(k=new Random().Next(n)+1)<n?k:k+f(n);

```

Saved 4 bytes thanks to @ExpiredData!

Try it online!
> 1 votes

# Answer
# Perl 6, 25 bytes

```
{sum {.rand+|0+1}...$_>*}

```

Try it online!
> 1 votes

# Answer
## F#, 83 bytes

```
let r=System.Random()
let e d=
 let mutable t=0
 while t%d=0 do t<-t+r.Next(d)+1
 t

```

Try it online! The first argument in the TIO program is the number of sides on the die, the second is the amount of tests to make. The output is printed to the console and shows each total and the number of times it has been rolled.

The random number generator `r` is initialised outside of the function. Initialising it within the function, combined with calling this function many times in succession, will cause it to return the same random numbers over and over again (try it for yourself!)

For the life of me I could not figure out how to write this without using `mutable`, especially since the last roll must be counted (`Seq.takeWhile` would not include the terminating element). I thought about using `Seq.mapFold` but it seems like it evaluates the input sequence first, which was a no-go for me.
> 1 votes

# Answer
# Ruby, 28 bytes

```
f=->n{(a=rand n)>0?a:n+f[n]}

```

Try it online!
> 1 votes

# Answer
# Java (JDK), 61 bytes

```
int f(int n){int r=1;r+=Math.random()*n;return r<n?r:r+f(n);}

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), ~~155 153 145~~ 144 bytes

```
using C=System.Console;class A{static void Main(){int i=int.Parse(C.ReadLine()),j=0;while((j+=new System.Random().Next(i)+1)%i<1){}C.Write(j);}}

```

Try it online!

This code instantiates a new RNG every time, but that uses time as a seed anyway so it *should* still satisfy randomness requirements.

I wonder if console input is cheaper in the long run.
> 1 votes

# Answer
# Funky, 38 bytes

```
f=n=>ifn==x=math.random(n)f(n)+x elsex

```

Try it online!
> 1 votes

# Answer
# Clojure, 63 bytes

```
#(loop[n 0](let[r(+ n(rand-int %)1)](if(<(- r n)%)r(recur r))))

```

A naive solution to the problem.

Expanded:

```
(defn exploding-die [sides]
  (loop [total 0]
    (let [new-total (+ total (rand-int sides) 1)]
      (if (< (- new-total total) sides) new-total
        (recur new-total)))))

```
> 1 votes

# Answer
## VTL-2, ~~54~~ ~~53~~ 51 bytes

```
1 A=?
2 C=C+B
3 B='/A*0+%+1
4 #=B=A*2
5 ?=C+B

```

Line 1 takes input into variable A, this will be our die's sidedness. Line 2 does what it appears to, though it's important to note that in VTL-2, referencing a variable that hasn't been initialized assumes 0, so for the first pass, this is `C=0+0`. Line 3 divides a random number by our dice sides (`'` is the system variable for a random number) and then turns this into a roll - `%` is the remainder of the last division operation; add 1 and put this in B. Line 4 is a little cryptic: `B=A` is evaluated first. It evaluates to 1 if the two are equal (if our die roll is the same as its number of sides), otherwise it evaluates to 0. This result is multiplied by two (`*2`), and then the final value here is handed to `#=`, which is equivalent to a GOTO. If this is given a zero, it ignores it; otherwise we GOTO 2, adding the roll to the total and rolling again. Line 6 prints the total of C+B.

Had an epiphany right after posting this, and golfed off one byte. I was doing `3 B='/A` and `4 B=%+1` because `%` is a system variable with the remainder of the last division operation; you need to do a division operation to get that value. But it occurred to me that I could do the division and then multiply that by zero since I don't need it. But since I've done it, the remainder is now in `%` and so I can add that to the zero I just made, and add 1 to get the die roll. This is long, but still shorter than two lines - line numbers always take two bytes in VTL-2, plus a space to separate the line number, plus a CR.

Second edit, did my math wildly wrong on byte count both times. Eesh. Third, golfed off two leftover parens.
> 1 votes

# Answer
# MMIX, 40 bytes (10 instrs)

Assumes `TRAP 82,78,71`¹ gets a randomly-generated `uint64_t`, by some method the OS knows about, but we don't have to.

(jxd -T)

```
00000000: e3010000 f7010000 00524e47 1effff00  ẉ¢¡¡ẋ¢¡¡¡RNGœ””¡
00000010: feff0006 220101ff 22010100 43fffffb  “”¡©"¢¢”"¢¢¡C””»
00000020: 26000100 f8010000                    &¡¢¡ẏ¢¡¡

```

Disassembled:

```
expl    SETL $1,0
        PUT  rD,0
0H      TRAP 82,78,71       // loop: tmp = sysrand()
        DIVU $255,$255,0
        GET  $255,rR        // tmp = tmp % n
        ADDU $1,$1,$255
        ADDU $1,$1,$0       // t += tmp + n
        BZ   $255,0B        // if(!tmp) goto loop
        SUBU $0,$1,$0
        POP  1,0            // return t - n

```

The main hack here is to treat every roll as being in the range \\$\[n,2n-1\]\\$, then subtracting \\$n\\$ once after everything is over.

¹ Yes, those numbers were carefully picked.
> 0 votes

# Answer
# Ly, 16 bytes

```
00ns[p+1l?l=]p+u

```

Try it online!

This one is pretty much a direct translations of the rules of the challenge.

```
00n              # Push "0", "0" and the input number on the stack
   s             # Save the input number in the backup cell
    [       ]    # Loop, quits when the random number doesn't match the die size
     p+          # Delete loop iterator check, add the remain two entries
                 # (The stack holds the accumulated value and the last roll)
       1l?       # Generate a random number between 1 and die size, inclusive
          l=     # Compare the random roll to the saved die size
             p+u # Add the last role and print as a number

```
> 0 votes

# Answer
# Thunno 2 `s`, 6 bytes

```
($=;$ɼ

```

Attempt This Online!

#### Explanation

```
($=;$ɼ  # Implicit input
(       # (while)
 $=     #   equals input
   ;    # (do)
    $ɼ  #   random item from [1..input]
        # Implicit output of summed stack

```
> 0 votes

# Answer
# Perl 5 `-Minteger -p`, 25 bytes

```
1until($\+=1+rand$_)%$_}{

```

Try it online!
> 0 votes

---
Tags: code-golf, random
---


# Question
Title: Bl lu ur rr ry yv vi is si io on - Blur the text
# Task

Given a string as input, generate a "blurred" version of that string.

# Input

Your input will be a single-line string of ASCII characters, containing a minimum of 2 alphanumeric characters

# Output

A string that is the "blurred" version of the input string.

A blurred string is one where every alphanumeric character from the original string has been paired with the ones adjacent to it, and each pair is separated by a space.

Any non-alphanumeric characters (whitespace, puncuation) in the input string must be ignored when determining adjacency of alphanumeric characters, and they must not included in the blurred string.

There must be no leading or trailing whitespace in the output string.

# Examples

`Ab` -\> `Ab`
`Abc` -\> `Ab bc`
`Abcd` -\> `Ab bc cd`
`E?h?` -\> `Eh`
`Blurry vision` -\> `Bl lu ur rr ry yv vi is si io on`
`We're #1!` -\> `We er re e1`
`I'm an example!` -\> `Im ma an ne ex xa am mp pl le`
`This is _not_ legible` -\> `Th hi is si is sn no ot tl le eg gi ib bl le`
`(a*b*c)+5^-x` -\> `ab bc c5 5x`
`??a_%,1!=z#@` -\> `a1 1z`

---

This is , so fewest bytes wins!

# Answer
> 25 votes
# Python 3, ~~57~~ 55 bytes

```
lambda s:"".join((c+" "+c)*c.isalnum()for c in s)[2:-2]

```

Try it online!

**How**:

* For each alpha-numeric character `c` in the string, replace it with `c+" "+c`.
E.g: `"abcd" -> "a ab bc cd d"`
* Remove the redundant first and last 2 characters:
E.g: `"a ab bc cd d" -> "ab bc cd"`

# Answer
> 13 votes
# Husk, 5 bytes

```
wX2f□

```

Try it online!

# Explanation

```
   f   Keep all items that
    □  Is an alphanumeric character.
 X     Pick all sublists
  2    With a length of 2.
w      Join the output list by spaces.

```

# Answer
> 8 votes
# K (ngn/k), ~~27 24 22~~ 21 bytes

```
" "/2':(2!"/9@Z`z"')_

```

Try it online!

`"/9@Z`z"'` binary search in the given string

`2!` mod 2

`(2!"/9@Z`z"')_` drop non-alphanumeric chars

`2':` make a list of pairs of adjacent chars

`" "/` join with spaces

# Answer
> 8 votes
# \[sed\] -E (C locale), ~~46~~ ~~33~~ 23 bytes

```
s/\W|_//g;s/\B.\B/& &/g

```

Try it online!

*Thanks to pizzapants184 for a 13-byte improvement.*

*10 more bytes off thanks to Dom Hastings.*

---

Input on stdin, and output on stdout.

If your locale isn't set to C, you can set it with: `export LC_ALL=C`

# Answer
> 7 votes
# Pyth, 14 bytes

```
jd.::Q"\W|_"k2

```

Try it online!

* `:Q"\W|_"k` replaces each non-alphanumeric character of the input with the empty string by matching each character against the regex `\W|_`
* `.: --- 2` finds all substrings of length 2
* `jd` joins the substrings using spaces

# Answer
> 7 votes
# 05AB1E, ~~8~~ ~~7~~ 8 bytes

*-1 byte thanks to @CommandMaster*

*+1 byte again thanks to @KevinCruijssen finding an issue*

```
žKÃüJðý?

```

Try it online!

# Answer
> 7 votes
# Jelly, 6 bytes

```
fØB;ƝK

```

A monadic Link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

```
fØB;ƝK - Link: list of characters, S
 ØB    - base-62 characters = "01...89AB...YZab...yz"
f      - (S) filter keep if in (that)
    Ɲ  - for neighbours:
   ;   -   concatenate
     K - join with spaces

```

# Answer
> 5 votes
# MATL, ~~17~~ 16 bytes

```
t8Y2m)2YC!Z{0&Zc

```

Try it online! Or verify all test cases.

### Explanation

Consider input `'Blurry vision'`.

```
t      % Implicit input. Duplicate
       % STACK: 'Blurry vision', 'Blurry vision'
8Y2    % Push '012...9ABC...Zabc...z' (predefined literal)
       % STACK: 'Blurry vision', 'Blurry vision', '012...9ABC...Zabc...z'
m      % Ismember: true for chars of the first string that are in the second
       % STACK: 'Blurry vision', [1 1 1 1 1 1 0 1 1 1 1 1 1]
)      % Use as logical index. This keeps only letters and numbers in the input
       % STACK: 'Blurryvision'
2YC    % Character matrix with sliding blocks of length 2 as columns
       % STACK: ['Blurryvisio';
                 'lurryvision']
!      % Transpose
       % STACK: ['Bl';
                 'lu';
                 ...
                 'on']
Z{     % Cell array of matrix rows
       % STACK: {'Bl' 'lu ... 'on'}
0&Zc   % Join with character 0 (which will be displayed as space)
       % STACK: 'Bl lu ur rr ry yv vi is si io on'
       % Implicit display

```

# Answer
> 5 votes
# TEX (INITEX), 372 bytes

```
\catcode`~13\let~\catcode~`{1~`}2~`#6~`\ 12~`|13\let|\expandafter\def\z{}\def\f#1{#1}\def\i#1{}\def\b#1#2{\ifx#2\e|||\i|\i\else|\f\fi{\ifcat#1a|\f\else|||\b|||#2|\i\fi}{\ifcat#2a #1#2|\b|#2\else|\b|#1\fi}}\def\t{~`011~`111~`211~`311~`411~`511~`611~`711~`811~`911~`\|12~`\~12~`\#12~`\{12~`\}12~127=12~`\%12~`\\12\read16to\x\edef\r{|\b\x\e}\immediate\write16{|\i\r\z}\end}\t

```

For example, the program being saved in a file named "codegolf.tex", provided with input `??a_%,1!=\z#@`, `initex codegolf.tex` outputs:

```
This is TeX, Version 3.14159265 (TeX Live 2019/dev/Debian) (INITEX)
(./codegolf.tex
\x=??a_%,1!=\z#@
a1 1z
 )
No pages of output.
Transcript written on codegolf.log.

```

In the case of a degraded input, for example the strings `??`, `?a`, or `a?`, this implementation does not print any pair.

# Explanation

## Basis for a TEX program

```
\read16

```

Per this Meta answer, the input of a program written in TEX should come from standard input, which is the *in register* number 16.

```
\immediate\write16

```

The TEX Codegolf community prefers to output to DVI or PDF, because it is simpler than writing to the terminal. However, this requires a valid `\output` routine, which either requires a format (with more category codes to alter1) or is longer to define. So I write to the terminal. (`\message` could also have been used, but I don't like how the output is surrounded by TEX chat on the same line).

Because I output to the terminal, I also feel that no DVI file should get produced, so `\immediate` is required2.

```
\end

```

This is a complete program, so it must end with `\end` to run cleanly.

## Category codes

Running on alphanumerics and ignoring punctuation is a trivial matter for TEX. All I have to do is to customize the category codes of those characters.

For this subject, I will use category code 11 ("letter") for characters that need to be blurred, and category code 12 ("other") for characters that are to be dropped. That choice comes from the defaults of (ini)TEX, where letters are already set to 11 and most of the other characters to 12.

```
\catcode`~13\let~\catcode

```

To save bytes, I make `~` an active character and set its meaning to `\catcode`. In the rest of the explanation, that alias will be ungolfed.

```
\catcode`{=1 \catcode`}=2 \catcode`#=6 \catcode`\ =12

```

These are required for INITEX to interpret my program correctly: `{` is now the begin-group character, `}` the end-group, `#` the macro argument, and  is considered a normal character (so that the first spurious space of output can be removed). These choices are widely used in the TEX world and do not cost bytes3.

```
\catcode`|=13 \let|=\expandafter

```

This is an useful alias for later.

```
\def\t{\catcode`0=11 ... \end}
\t

```

This is a TEX design pattern that fools TEX's eyes. Everything that is written in the `\todo` macro definition will get a category code assigned, and this category code will not be reconsidered when TeX expands the macro. Most notably:

```
\catcode`\\=12

```

This makes the escape character `\` a normal character when read from the user input.

```
\read16to\x \edef\r{|\b\x\e} \immediate\write16{|\i\r\z} \end

```

When reading the macro definition, TEX has decided that these were control words, and TEX will not reconsider this choice after the macro has been expanded, even if `\` has lost its special meaning in the meantime.

```
\catcode127=12

```

The `DEL` character is contained in ASCII, so it should be valid input per the subject's rules. But in order to change its category code to 12, the DEL character has to be written, and the most efficient4 way to input it in TEX is to name it by its code point.

```
\catcode`0=11 ... \catcode`\\=12

```

Here are three groups of category code assignments: make the digits like letters, revert the changes made at the beginning of the program, and cancel other INITEX defaults (`DEL`, `%`, `\`, but not the new line because the subject emits the hypothesis:)

> Your input will be a single-line string

## The blurring command

Because I opted for terminal output, and because `\write` does not executes its argument (only expands it), I am forced to write the `\blur` macro as fully expandable.

```
\def\z{} \def\firstofone#1{#1} \def\ignore#1{}

```

As a prolog, I define three macros, which are commonly used in various fully-expandable design patterns. The first one is the empty macro, the second one is the identity macro, and the third one is the zero macro.

```
\def\blur#1#2{ ... }

```

The `\blur` macro is recursive5. It takes two characters at a time (because the rules say that the input is longer than two). Its definition is made of three parts.

```
\ifx#2\e \expandafter\expandafter \expandafter\ignore \expandafter\ignore
\else    \expandafter\firstofone
\fi

```

is the recursion condition: if the end-of-string marker (the undefined command `\e`6) is found, ignore the two other parts. (More precisely, drop the unused portion of the conditional `\else...\fi` at `\expandafter` level 0, then ignore the second part at `\expandafter` level 1, then ignore the third part at `\expandafter` level 2.) Otherwise, close the conditional and interpret the second part.

```
\ifcat#1a \expandafter\firstofone
\else \expandafter\expandafter \expandafter\blur
      \expandafter\expandafter \expandafter#2
      \expandafter             \ignore
\fi

```

handles the first character. If it is a letter or digit, go analysing a second character. Otherwise, skip the remaining of the conditional, ignore the third part, and call `\blur` recursively with #1 being dropped and #2 as the first character7 (an other one will get extracted from input).

```
\ifcat#2a ␣#1#2 \expandafter\blur \expandafter#2
\else \expandafter\blur \expandafter#1
\fi

```

handles the second character. If it is a letter or digit, output a space then the first part of the blur, then forget about #1 and call `\blur` recursively on #27. Otherwise, forget about it and call `\blur` recursively on #17.

## Calling the blurring command on real input

```
\read16 to \x

```

will store the input into an (expandable) macro `\x`.

```
\expandafter\blur \x \e

```

This is how the `\blur` macro is called. Because `\blur` acts on tokens, the input contained in `\x` must be expanded first. The end-of-string marker follows.

```
\edef\result{\expandafter\blur \x \e}

```

The result of the expansion, including the whitespace at front, is stored into the `\result` macro.

```
\expandafter\ignore \result \z

```

Inside the `\write16` command, the `\result` macro is first expanded. Then, `\ignore` eliminates the first token of output: the first space if the output is non-empty, or the `\z` macro call if the output is empty. In the first case, the `\z` macro will survive; but `\write16` will finally expand it, and its expansion is a no-op. This is the most efficient way of handling the “no trailing space” requirement, even if it requires 24 bytes (the definition and call of `\z` and `\return`); suppressing a space at the end of the output would have been nearly impossible.

## ☡ Footnotes

1. `$`, `&`, `^`, `_`, `NUL`, `SPC`, `TAB`, `~` for plain TEX; 5 bytes each = 40 bytes.
2. Without `\immediate`, `\write` adds its content to a whatsit box, thus generating a page of output.
3. Because there are only three category code changes, it is not worth putting them in a group to save the reverting.
4. Decimal: `127=` (4); Hexadecimal: `"7F=` (4, harder to read); Octal: `'199=` (5); Escape sequence: ```\^^?` (5, plus `\catcode`^7` and revert)
5. It is even *tail-recursive*, which in T<sub>E</sub>X has the meaning of "it does not add tokens after the recursive call", and by doing so is more memory-friendly.
6. Because all input other than my program does not get interpreted, the `\e` command cannot be defined later.
7. This would fail if #2 was a simple group of arguments, but fortunately the input cannot contain simple groups, because no character has category code 1 nor 2.

# Answer
> 4 votes
# Retina, 13 bytes

```
\W|_

Lw| `..

```

Try it online!

## Explanation

`\W|_` Replace each character NOT in the regex group \W (which is `A-Z,a-z,0-9,_`) or a `_` with nothing

`Lw| `..` Compute lists (`L`) for each set of two characters (`..`) starting at all positions in the string (`w`) and separate the lists with a space (`|` )

# Answer
> 4 votes
# Factor, ~~51~~ 37 bytes

-14 bytes thanks to chunes

```
[ [ alpha? ] filter 2 clump " "join ]

```

Try it online!

# Factor, 51 bytes

```
: b ( s -- s ) [ alpha? ] filter 2 clump " " join ;

```

Try it online!

Unbelievably Factor is competitive with Python and JavaScript :)

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 74 bytes

This ended up very similar to the Python answer. I was trying something noticeably more interesting with Aggregate, but the terrible no trailing whitespace requirement made it too long.

```
s=>s.SelectMany(c=>char.IsLetterOrDigit(c)?c+" "+c:"").Skip(2).SkipLast(2)

```

Try it online!

# Answer
> 4 votes
# Kotlin, ~~77~~ 76 bytes

```
{it.filter{it.isLetterOrDigit()}.zipWithNext{a,b->"$a$b"}.joinToString(" ")}

```

Old solution

```
{it.replace("\\W|_".toRegex(),"").zipWithNext{a,b->"$a$b"}.joinToString(" ")}

```

# Answer
> 4 votes
# AWK, 52 54 bytes

```
{gsub("\\W|_",a);for(b=$0;c=substr(b,++d,2);)$d=c}--NF

```

Try it online!

*Fixed underscore rule goof (+2 chars), thanks to Pedro Maimere*

Here's what's going on with this one...

```
gsub("\\W",a)

```

Removes all the non-alphabetic characters from the input string since `$0` is the default target for `gsub`. Using an unitialized variable `a` instead of `""` saves a byte.

Next the code loops through the string taking 2 character slices and assigns them to positional variables.

```
for(b=$0;

```

The setup has to save `$0` to another variable, since changing the positional variables impacts the collected input in `$0` as well.

```
c=substr(b,++d,2);

```

The "test" at the top of the loop does a couple of things in one statement:

* increments `d`, the "current character" pointer
* sets variable `c` to the next 2 character slices of the input
* the true/false test simple has the code looping until we run off the string and get a null

The body of the loop sets the next positional variable to the slice we just took.

```
$d=c

```

After all the positional variables have been set, there's one "garbage" entry on the end with one character. So the test:

```
--NF

```

effectively drops that last positional variable and triggers the default action, which prints all the positional variables separated by a space.

# Answer
> 3 votes
# 05AB1E, ~~23~~ ~~19~~ 18 bytes

```
žKÃ©g<F®Nè?®N>è?ð?

```

Try it online!

This probably could be really shorter, but I just wasn't able to find the right tools for the job. -4 bytes thanks to petStorm and a further byte thanks to Command Master.

## Old Answer Explained

```
žj'_ммм©g<F®Nè?®N>è?' ?
žj                      # Push [a-zA-Z0-9_]
  '_м                   # Remove the "_" from the above string
     м                  # Remove all alphanum characters from the input, leaving non-alphanum chars
      м                 # Remove those non-alphanum chars from the input, leaving alphanum chars
       ©                # Put this string into the register
        g<F             # For N in range(0, len(input) - 1):
           ®Nè?         #   Index the string at position N and print
               ®N>è?    #   Index the string at position N + 1 and print
                    ' ? #   Print a space

```

# Answer
> 3 votes
# Retina 0.8.2, ~~17~~ 16 bytes

```
\W|_

M&!`..
¶

```

Try it online! Link includes test cases. Explanation: Now basically a port of @Jarmex's Retina 1 solution, except that `M!` always joins with newlines, so I have explicitly change them to spaces. Previous 17-byte approach:

```
\W|_

\B.\B
$& $&

```

Try it online! Link includes test cases. Explanation:

```
\W|_

```

Delete any non-word character and any underscore (which is the only non-alphanumeric character that counts as a word character).

```
\B.\B
$& $&

```

Duplicate each inner character and space separate the results.

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

```
s=>s.replace(/\W|_|(.)/g,(_,c)=>c?c+' '+c:'').slice(2,-2)

```

Try it online!

# Answer
> 3 votes
# Q/KDB+, 38 bytes

**Solution:**

```
{" "sv -2_2#'next\[x inter .Q.an _52]}

```

**Examples:**

```
q){" "sv -2_2#'next\[x inter .Q.an _52]}"Ab"
"Ab"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"Abc"
"Ab bc"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"E?h?"
"Eh"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"This is _not_ legible"
"Th hi is si is sn no ot tl le eg gi ib bl le"

```

**Explanation:**

```
{" "sv -2_2#'next\[x inter .Q.an _52]} / solution
{                                    } / lambda taking implicit x
                           .Q.an       / "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789"
                                 _52   / drop element at index 52
                   x inter             / intersection of x and alphanumerics
             next\[                 ]  / scan along input
          2#'                          / take first 2 characters of each
       -2_                             / drop final two items
 " "sv                                 / join (sv) with " "

```

# Answer
> 3 votes
# APL (Dyalog Unicode), 32 bytes (SBCS)

Port of Surculose Sputum's Python answer.

```
{¯2↓2↓⊃,/{⍵' '⍵}¨⍵∩⎕A,819⌶⎕A,⎕D}

```

Try it online!

# Answer
> 3 votes
# QuadR, 18 bytes

```
1↓∊' ',¨2,/⍵
\W|_

```

Try it online!

Replaces all non-word characters and underscores (`\W|_`) with nothing , and then:

`2,/⍵` adjacent pairs

`' ',¨` prepend a space to each pair

**ϵ**nlist (flatten)

`1↓` drop the first space

# Answer
> 3 votes
# C (gcc), 80 bytes

```
p,b;f(char*s){for(p=b=0;*s;s++)isalnum(*s)?p&&printf(" %c%c"+!b--,p,*s),p=*s:0;}

```

Try it online!

# Answer
> 3 votes
# Javascript ES6, ~~55~~ 54 chars

```
s=>s.replace(/\W|_/g,"").replace(/.(?=(.).)/g,"$&$1 ")

```

Test:

```
f=s=>s.replace(/\W|_/g,"").replace(/.(?=(.).)/g,"$&$1 ")

console.log(`Ab -> Ab
Abc -> Ab bc
Abcd -> Ab bc cd
E?h? -> Eh
Blurry vision -> Bl lu ur rr ry yv vi is si io on
We're #1! -> We er re e1
I'm an example! -> Im ma an ne ex xa am mp pl le
This is _not_ legible -> Th hi is si is sn no ot tl le eg gi ib bl le
(a*b*c)+5^-x -> ab bc c5 5x
??a_%,1!=z#@ -> a1 1z`.split`
`.map(s=>s.split` -> `).map(([s,k])=>f(s)==k).every(x=>x))
```

# Answer
> 3 votes
# , 32 bytes

```
[:}:[:,/2,&' '\]-.-.&AlphaNum_j_

```

Try it online!

```
               -.-.&AlphaNum_j_   remove non-alphanumeric
       2,&' '\                    append space to each pair of adjacent chars
     ,/                           join
 }:                               remove trailing space

```

# Answer
> 3 votes
# , 98 bytes

```
function(x,y=grep("[a-z0-9]",el(strsplit(x,"")),T,,T))for(i in seq(y)[-1])cat(y[i-1:0],' ',sep='')

```

Try it online!

Unusually for , a `for` loop is significantly shorter than a matrix-based approach, mainly because it allows us to just use `cat` instead of the much-more-verbose `Reduce(paste` vectorized way to build a text string from a list of characters.

# Answer
> 3 votes
# , 76 bytes

```
function(s)cat(substring(S<-gsub("[^a-z0-9]","",s,T),N<-1:(nchar(S)-1),N+1))

```

Try it online!

Similar to Dominic van Essen's answer, uses `cat` to join by spaces; uses `substring` which recycles (as opposed to `substr` which doesn't).

# Answer
> 3 votes
# Perl 5 `-p`, 25 bytes

```
s/\W|_//g;s/\B.\B/$& $&/g

```

Try it online!

# Answer
> 2 votes
# Charcoal, 26 bytes

```
≔ΦＳ№⁺α⁺β⭆χλιθ⪫Ｅ⊖Ｌθ✂θι⁺²ι¹

```

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

```
≔ΦＳ№⁺α⁺β⭆χλιθ

```

Filter out any character that can't be found in the upper or lower case alphabet and isn't a digit.

```
⪫Ｅ⊖Ｌθ✂θι⁺²ι¹

```

Extract all substrings of length 2 and join them together on spaces.

# Answer
> 2 votes
# \[C#\], ~~163~~ ~~155~~ ~~133~~ ~~128~~ ~~127~~ ~~128~~ ~~114~~ ~~112~~ ~~133~~ 98 bytes

```
i=>{var b=i.Where(char.IsLetterOrDigit);return b.Select((n,i)=>i==0|i==b.Count()-1?n+"":n+" "+n);}

```

Run it

~~Have not used a Regex yet in a Codegolf, so very excite.~~ Regex uses way too many characters. No longer excite.

* 127 bytes: removed a "." in the regex string
* 126 bytes: replaced String.Join("" with String.Concat
* 114 bytes: changed || to |, removed the ( ) { return; } from inside the Select
* 112 bytes: Removed + from regex
* 128 bytes: Reverting back to older solution. Entry now legal (thanks to @Neil and @my pronoun is monicareinstate)
* 98 bytes: Realization that char is way more powerful than I thought (thanks to @my pronoun is monicareinstate's C# solution), removed the string -\> char -\> string conversions

# Answer
> 2 votes
# Icon, 92 bytes

```
procedure f(s)
t:=""
find(k:=!s,&letters++&digits--'_')&t||:=k||' '||k&\z
return t[3:-2]
end

```

Try it online!

# Answer
> 2 votes
# Haskell, 86 74 bytes

<sup>-12 bytes thanks to Khuldraeseth na'Barya</sup>

```
import Data.Char
unwords.map(\(x,y)->[x,y]).(zip<*>tail).filter isAlphaNum

```

Try it online!

# Answer
> 2 votes
# Japt v2.0a0 `-S`, 6 bytes

```
r\W ä+

```

Try it

```
r\W ä+     :Implicit input of string
r          :Replace
 \W        :  Regex /[^a-z0-9]/gi
    ä+     :Consecutive pairs reduced by concatenation
           :Implicit output, joined with spaces

```

# Answer
> 2 votes
# C (gcc), 159 bytes (-2 more bytes thanks to S.S. Anne and JustinCB)

```
main(a,b)char**b;{b++;for(a=0;a<strlen(*b);a++){if(isalnum((*b)[a])){a?putchar((*b)[a]):0;a&&a<strlen(*b)-1?putchar(32):0;a<strlen(*b)-1?putchar((*b)[a]):0;}}}

```

Try it online!

# Answer
> 2 votes
# Red, 130 bytes

```
func[s][a: charset[#"0"-#"9"#"A"-#"Z"#"a"-#"z"]parse s[any[p: change
a(rejoin[p/1" "p/1])| remove skip]]take/part/last s 2 at s 3]

```

Try it online!

# Answer
> 2 votes
# , 42 bytes

```
1}.[:,/2' '&,\]#~'/9@Z`z'(2|I."#.)&(3&u:)]

```

Try it online!

Inspired by ngn's ngn/k solution

## Explanation

```
                                   (3&u:)     convert to integer both
                                         ]    the input
                 '/9@Z`z'                     and the symbols surrounding the digits,
                                              uppercas and lowercase letters
                         (2|I."#.)&           and find in which interval lies each char
                                              then check if it's an odd one
              ]#~                             use the above to filter the input
       2' '&,\                                prepend each pair of adjacent chars
                                              with a space
   [:,/                                       flatten the result
1}.                                           and drop the leading space

```

# Answer
> 2 votes
# JavaScript (ES6), ~~54~~ 76 bytes

```
a=>[...a.replace(/[\W_-]/g,'')].map((a,b,c)=>a+c[b+1]).slice(0,-1).join(' ')

```

Try it online!

# Answer
> 2 votes
# C (gcc), <sup>~~123~~ \\$\cdots\\$ ~~117~~</sup> 116 bytes

```
i;f(char*s){char*t=s;for(i=0;t[i+=!!isalnum(*s++)]=*s;);for(putchar(*t++);t[1];)printf("%c %1$c",*t++);putchar(*t);}

```

Try it online!

# Answer
> 2 votes
# Stax, 6 bytes

```
£Q·H°·

```

Run and debug it at staxlang.xyz!

### Unpacked (7 bytes) and explanation:

```
VL|&2BJ
VL         Push string of all alphanumeric characters.
  |&       Remove from the input all letters not in this string.
    2B     All length-2 substrings
      J    Join with spaces

```

# Answer
> 2 votes
# Elixir, 120 bytes

```
b=fn w->import String;l=replace(w,~r/[\W_]/,"");for(i<-0..String.length(l)-2,do: at(l,i)<>at(l,i+1))|>Enum.join(" ") end

```

Try it online!

# Answer
> 2 votes
# Raku, 31 bytes

```
{@$_ Z~.skip}o{S:g/\W|_//.comb}

```

Try it online!

The extra requirement for stripping non-alphanumeric characters takes up more than half of the bytes.

# Answer
> 2 votes
# F#, 130 bytes

```
let f s=s|>Seq.filter Char.IsLetterOrDigit|>fun x->Seq.tail x|>Seq.zip x|>Seq.map(fun(a,b)->string a+string b)|>String.concat" "

```

# Answer
> 2 votes
# K (ngn/k), 47 bytes

```
{" "/2':x^"!@#$%^&*()~`_-+={}[]|\:;\"'<>?,./ "}

```

Try it online!

The window adverb finally got a use for once. Also, removing non-alphanumeric is such a huge pain to write.

Anyways, here's the explanation:

```
{" "/2':x^"!@#$%^&*()~`_-+={}[]|\:;\"'<>?,./ "}  Main function. Takes x as input
          "!@#$%^&*()~`_-+={}[]|\:;\"'<>?,./ "   Hard-coded non-alphanumeric string
        x^                                       Remove all of them in x
     2':                                         Window (Get chunks of x at length 2)
 " "/                                            Join the chunks with whitespace

```

# Answer
> 2 votes
# Lua, 57 bytes

```
io.write((...):gsub('%W',''):gsub('.','%1 %1'):sub(3,-3))

```

Try it online!

Performs three steps:

* Removes all non-alphanumerics

`Blurry vision` -\> `Blurryvision`
* Double all characters, with a space in between

`Blurryvision` -\> `B Bl lu ur rr ry yv vi is si io on n`
* Remove the excess characters

`B Bl lu ur rr ry yv vi is si io on n` -\> `Bl lu ur rr ry yv vi is si io on`

# Answer
> 1 votes
# Erlang (escript), 110 bytes

Port of the Python answer.

```
f(X)->R=lists:flatten([[I]++" "++[I]||I<-X,re:run([I],"[A-Za-z0-9]")/=nomatch]),string:slice(R,2,length(R)-4).

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 59 bytes

```
s->s.replaceAll("\\W|_","").replaceAll(".(?=(.).)","$0$1 ")

```

Try it online!

# Answer
> 1 votes
# Swift, 141 bytes

```
{let a=$0.unicodeScalars.filter{CharacterSet.alphanumerics.contains($0)};return zip(a,a.dropFirst()).map{"\($0)\($1)"}.joined(separator:" ")}

```

Ungolfed:

```
let ungolfed: (String) -> String = { input in
    let unicodeScalars = input.unicodeScalars.filter { char in CharacterSet.alphanumerics.contains(char) }
    return zip(unicodeScalars, unicodeScalars.dropFirst())
        .map { "\($0)\($1)" }
        .joined(separator: " ")
}

```

Test case runner:

<pre><code>import Foundation

let testCases: [(input: String, expectedOutput: String)] = [
    (input: "Ab", expectedOutput: "Ab"),
    (input: "Abc", expectedOutput: "Ab bc"),
    (input: "Abcd", expectedOutput: "Ab bc cd"),
    (input: "E?h?", expectedOutput: "Eh"),
    (input: "Blurry vision", expectedOutput: "Bl lu ur rr ry yv vi is si io on"),
    (input: "We're #1!", expectedOutput: "We er re e1"),
    (input: "I'm an example!", expectedOutput: "Im ma an ne ex xa am mp pl le"),
    (input: "This is _not_ legible", expectedOutput: "Th hi is si is sn no ot tl le eg gi ib bl le"),
    (input: "(a*b*c)+5^-x", expectedOutput: "ab bc c5 5x"),
    (input: "??a_%,1!=z#@", expectedOutput: "a1 1z"),
]

for (input, expectedOutput) in testCases {
    let actualOutput = f(input)
    assert(actualOutput == expectedOutput, """
    Wrong answer.
        input: '\(input)'
        actualOutput: '\(actualOutput)'
        expectedOutput: '\(expectedOutput)'

    """)
}
```

# Answer
> 1 votes
# Python 3, 82 chars

```
a=[c for c in input() if c.isalnum()]
print(' '.join(a+b for a,b in zip(a,a[1:])))

```

Try it: https://ideone.com/dxJU8e

# Answer
> 1 votes
# PowerShell Core, ~~48~~ 47 bytes

```
''+($args-match'[a-z\d]'|%{,"$p$_"*!!$p;$p=$_})

```

Try it online!

# Answer
> 1 votes
# APL (NARS2000 dialect) 24 bytes

```
{¯1↓1↓⍕2,/⍵/⍨⍵∊A←⎕a,⎕A,⎕D}

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
kr↔zṄ

```

Try it Online!

```
kr↔   # Remove non-alphanumeric
   z  # Get chunks of length 2
    Ṅ # Join with spaces

```

# Answer
> 1 votes
# Ruby `-pl`, ~~48~~ ~~39~~ 35 bytes

Similar to my own original solution, this is now basically a port of Xcali's Perl 5 solution; give them an upvote.

```
gsub /\W|_/,""
gsub /\B.\B/,'\& \&'

```

Attempt This Online!

# Answer
> 1 votes
# Rust, ~~144 129 127 126 123 120~~ 106 bytes

-3 bytes, thanks @mousetail
-14 bytes, thanks @corvus\_192

Playing with strings can be subtle, and as such it is easy to slam face first into the borrow checker when trying to golf string manipulation in rust. As a result I welcome any improvement to this code:

```
|s|{let a:String=s.filter(|c|c.is_alphanumeric()).flat_map(|c|[c,' ',c]).collect();a[2..a.len()-2].into()}

```

The solution is the same as for the Python one above.

Ungolfed:

```
// This first line is not part of the code snippet,
// but needs to be present in the driving code in order for type inference to work.
let blur: fn(std::vec::IntoIter<char>) -> String =
    |s| {                                    // Take in an iterator over
                                             // a vector of chars and
        let a: String = s                    // build a new string
            .filter(|c| c.is_alphanumeric()) // by taking all alphanumeric characters
            .flat_map(|c| [c, ' ', c])       // and replacing them with a copy
                                             // of themselves around a space
            .collect();                      // and collecting them into a String.
        a[2..a.len() - 2].into()             // Then make a string slice of every
                                             // character except the first and last
                                             // two and convert that slice
                                             // into a String.
                                             // `.into()` works because of the
                                             // function signature that is specified
                                             // on the first line.
};

println!(
    "{}",
    // We call this closure by passing it an iterator over a vector of characters
    // that we build by iterating over the characters in a string.
    blur("This is a string"
        .chars()
        .collect::<Vec<_>>()
        .into_iter())
);

```

Attempt this online

# Answer
> 1 votes
# PHP, 70 bytes / 69 bytes

```
while(~$c=($s=preg_replace('/\W/','',$argn))[++$i])echo$s[$i-1],"$c ";

```

run these 70 bytes as pipe with `-nr`, ignore the warnings

or run this port of Qwertiy´s JavaScript solution (69 bytes) as pipe with `-nR`:

```
<?=preg_replace('/.(?=(.).)/','$0$1 ',preg_replace('/\W/','',$argn));

```

Try them online

# Answer
> 1 votes
# Zsh, 65 bytes

```
b=(${(s::)@//[^0-9A-Za-z]});for i ({2..$#b})printf $b[i-1]$b[i]\

```

try it online!

There is a a space character after the backslash: `\`

# Answer
> 1 votes
# Pip, ~~17~~ 16 bytes

```
_.BMP(aXA,XD)J:s

```

Attempt This Online!

### Explanation

```
_.BMP(aXA,XD)J:s
       XA         ; Regex matching any letter character
          XD      ; Regex matching any digit
         ,        ; Combine them using alternation (match one OR the other)
     (a     )     ; Find all matches in command-line argument
   MP             ; Map this function to each pair of adjacent results:
_                 ;  The first
 .                ;  concatenated with
  B               ;  the second
             J:s  ; Join the resulting list on spaces

```

Using the `-s` flag would remove the need for the final three bytes.

# Answer
> 1 votes
# Scala 3, 75 bytes

```
_.map(c=>if(c.isLetterOrDigit)c+" "+c else"").mkString.drop(2).dropRight(2)

```

Attempt This Online!

# Answer
> 1 votes
# Uiua, 22 bytes

```
/$"_ _"◫2▽+⌵⊃±∊,+@0⇡10

```

Try it

-1 + fix thanks to chunes :)

Explanation:

```
+@0⇡10

```

Take each number 0 to 9 and convert to character by adding it to character literal `0`

```
⊃±∊,

```

Apply `sign ±` to each character of the input, and `member ∊` to the digit list and each character of the input. The former gives 0 for non-letters, 1 for uppercase letters, and -1 for lowercase letters. The latter gives 1 if the character is a digit and 0 otherwise.

```
+⌵

```

Take the absolute value of each result from `sign ±`, yielding a list of 1 and 0. Then, add this list to the results of `member ∊`. This results in a list with 1 at every position where there's a letter or a digit, and 0 everywhere else.

`keep ▽` takes two lists and, in the case of the top containing only 0's and 1's, acts as a filter, removing any items from the first list that correspond with a 0 in the second. Here, the first list is the input string, and the second list is the filter created above.

So far, everything has just been the task of removing non-alphanumeric characters. The main task itself is much shorter:

```
◫2

```

The size-2 `windows ◫` of the list. This gives the overlapping pairs of the string.

```
/$"_ _"

```

`reduce /` passes the first two items through a function, then that result and the next item through the same function, repeatedly until there are no more items left. `$"_ _"` is a format string, which becomes a function where each `_` becomes replaced with an item from the stack. This operation results in the list joined by spaces.

# Answer
> 0 votes
# PowerShell Core, 56 bytes

```
$n=$args|% t*y|%{$_+" "+$_}
-join$n[0..($n.length-2)+-1]

```

Try it online!

-20 bytes for @mazzy

# Answer
> 0 votes
# Java 8 (OpenJDK 8), 144 bytes

No regexp, using only a single inline Stream

```
s->s.chars().filter(e->e>47&e<58|e>64&e<91|e>96&e<123).mapToObj(e->""+(char)e).reduce("",(a,b)->a+(a.length()<2?b:" "+a.charAt(a.length()-1)+b))

```

Try it online!

# Answer
> 0 votes
# Nibbles, 9 bytes (18 nibbles)

```
*" "`'`:<<;|@\$n>>$

```

Attempt This Online!

### Explanation

```
*" "`'`:<<;|@\$n>>$
            @        Line of stdin
           |         Filter its characters on this function:
             \$n      Character is alphanumeric
          ;          Store the result as $
        <<           Remove last character
                >>$  Take another copy of $ and remove first character
      `:             Put both strings in a list
    `'               Transpose, giving a list of 2-character strings
*" "                 Join on spaces

```

# Answer
> 0 votes
# Thunno 2 , 5 bytes

```
œȦDḣZ

```

Attempt This Online!

#### Explanation

```
œȦDḣZ  # Implicit input
œ      # Filter the input by:
 Ȧ     #  Is alphanumeric?
  D    # Duplicate
   ḣ   # Remove the first item
    Z  # Zip them together
       # Join by spaces
       # Implicit output

```

# Answer
> 0 votes
# Vyxal 3 `S`, 4 bytes

```
/““o

```

Try it Online!

janky formatting allows for a 3 byter

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


# Question
Title: Reconstruct a list of strings from its prefixes
emanresu A posted a challenge to reconstruct an ordered list of integers from its unordered set of unordered prefixes. Many users (beginning with xnor's answer) noticed that summing each unordered prefix led to a very short solution. Well, let's cruelly take that possibility away by using data that isn't integers!

A few answers from the other challenge work for this version as well; that's no problem. I'm just hoping to stimulate other answers in other languages.

(The text below is a slightly modified but mostly copied version of emanresu A's original text.)

A list of strings \\$\[a\_1,a\_2,a\_3, \ldots, a\_n\]\\$ can be uniquely represented as an unordered list of its unordered prefixes \\$ \[\[a\_1\],\[a\_1, a\_2\], \[a\_1,a\_2,a\_3\], \ldots, \[a\_1,a\_2,a\_3, \ldots, a\_n\]\] \\$. Both the set of prefixes and the set of elements of each individual prefix can be in any order - for example,

```
["lorem","ipsum","dolor"]

```

could be represented by any of

```
[["lorem"],["lorem","ipsum"],["lorem","ipsum","dolor"]] or
[["dolor","ipsum","lorem"],["ipsum","lorem"],["lorem"]] or
[["ipsum","lorem"],["lorem"],["dolor","lorem","ipsum"]]

```

and these are all equivalent up to order and all represent `["lorem","ipsum","dolor"]`.

Your challenge is, given an unordered list of the unordered prefixes of a (non-empty) list of strings, to return the ordered list represented by them. The list may contain repeated items. You may stipulate that the input includes the empty prefix if desired. This is , so shortest code in each language wins!

## Testcases

Note that the order of the output *does* matter: for the third test case, for example, you must output `["consectetuer","sit","elit","adipiscing"]`, not `["adipiscing","sit","elit","consectetuer"]`.

```
[["lorem"],
 ["lorem","ipsum"],
 ["lorem","ipsum","dolor"]]
-> ["lorem","ipsum","dolor"]

[["ipsum","lorem"],
 ["lorem"],
 ["dolor","lorem","ipsum"]]
-> ["lorem","ipsum","dolor"]

[["consectetuer","sit","elit"],
 ["adipiscing","sit","elit","consectetuer"],
 ["consectetuer","sit"],
 ["consectetuer"]]
-> ["consectetuer","sit","elit","adipiscing"]

[["consectetuer","ipsum","dolor","lorem"],
 ["lorem","ipsum"],
 ["lorem"],
 ["consectetuer","lorem","ipsum"],
 ["ipsum","ipsum","dolor","lorem","consectetuer"]]
-> ["lorem","ipsum","consectetuer","dolor","ipsum"]

[["ipsum"],
 ["nunc","ipsum","justo","in"],
 ["justo","in","ipsum","molestie","nunc"],
 ["ipsum","nunc","justo"],
 ["justo","ipsum"]]
-> ["ipsum","justo","nunc","in","molestie"]

[["elit","sit"],
 ["sit","elit","elit","sit"],
 ["sit","sit","elit"],
 ["sit"]]
-> ["sit","elit","sit","elit"]

[["pede","non","phasellus","lectus"],
 ["lectus","non"],
 ["pede","non","nunc","phasellus","lectus","sit","ipsum"],
 ["non"],
 ["phasellus","lectus","non"],
 ["pede","non","ipsum","phasellus","lectus"],
 ["ipsum","pede","non","phasellus","sit","lectus"]]
-> ["non","lectus","phasellus","pede","ipsum","sit","nunc"]

[["pellentesque","ullamcorper","semper","vestibulum"],
 ["semper","pellentesque"],
 ["pellentesque","semper","vestibulum"],
 ["pellentesque"]]
-> ["pellentesque","semper","vestibulum","ullamcorper"]

```

# Answer
# Python 2, ~~73~~ 68 bytes

```
lambda L:reduce(lambda v,l:map(l.remove,v)and v+l,sorted(L,key=len))

```

Try it online!

An anonymous function that accepts a `L`ist of lists and returns a list as result.

Copying my answer from the original question.

* -5 bytes thank to @Mukundan314

**How does it work?**

With the input sorted by length (so `[["ipsum","lorem"],["dolor","lorem","ipsum"],["lorem"]]` becomes `[["lorem"],["ipsum","lorem"],["dolor","lorem","ipsum"]]`), for each sub`l`ist, remove the first occurrence of elements already `v`isited from `l` and mark the remaining element as `v`isited.

It works for duplicates.
> 5 votes

# Answer
# Haskell, 57 bytes

```
import Data.List
concat.(zipWith(\\)<*>([]:)).sortOn(0<$)

```

Try it online!

Hey, I knew my slightly different approach would come in handy! Only change is needing to sort by length instead of sum, 'cause uh... well you know.
> 4 votes

# Answer
# Nekomata, 8 bytes

```
↕ᵉtiᶻ{∕z

```

Attempt This Online!

The input includes the empty prefix.

```
↕ᵉtiᶻ{∕z
↕           Take a permutation of the input (non-deterministically)
 ᵉt         Take its tail (removing the first item)
   i        and its initial prefix (removing the last item)
    ᶻ{      Zip with:
      ∕         Set minus
       z        Check that the result is a singleton

```

---

# Nekomata, 9 bytes

```
ᵐ∑oç∆ᵐᶠZH

```

Attempt This Online!

The input does not include the empty prefix.

Using @xnor's trick in emanresu A's challenge.

```
ᵐ∑oç∆ᵐᶠZH
ᵐ∑          Take the sum of each item of the input
            Strings are automatically converted to code points and padded with zeros
  o         Sort
   ç        Prepend zero
    ∆       Take the differences
     ᵐᶠZ    Remove zeros
        H   Convert the code points to characters

```
> 4 votes

# Answer
# Jelly, 7 bytes

```
LÞœ^ƝṪ€

```

A monadic Link that accepts the prefixes as a list of lists of lists of characters (including an empty prefix) and yields a list of lists of characters.

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

### How?

```
LÞœ^ƝṪ€ - Link: Prefixes
 Þ      - sort by:
L       -   length
    Ɲ   - for neighbouring pairs:
  œ^    -   multiset symmetric difference
     Ṫ€ - tail of each

```
> 3 votes

# Answer
# Jcram, 18 bytes

```
Ⓜ⍅Ⓛ⍎⍗¹W⍜nχ0⍒⑨1βⓏ2⏛

```

# JavaScript (Node.js), 100 bytes

```
a=>a.sort((a,b)=>a.length-b.length).map(k=>a.map(a=>k.splice(k.indexOf(a),1))&&a.push(...k),a=[])&&a

```

Try it online! Uses a similar method to movatica's python answer.
> 3 votes

# Answer
# JavaScript (ES6), 77 bytes

```
f=a=>a.some(b=>(w=b[0])==b)?[w,...f(a,a.map(b=>b.splice(b.indexOf(w),1)))]:[]

```

Try it online!

Or:

```
f=a=>a.some(b=>(w=b[0])==b)?[w,...f(a.map(b=>b.filter(v=>v!=w||x++,x=0)))]:[]

```

Try it online!
> 3 votes

# Answer
# , 25 bytes

```
2(~.#~2|1#.=)@;\a:,]/:#&>

```

Attempt This Online! Setup borrowed from Jonah's answer.

Sort by length, join adjacent prefixes, take the element that appears an odd number of times.

---

# , 27 bytes

```
2(0{~:#])/\a:>@;/:~&.>/:#&>

```

Attempt This Online!

Sort each prefix, sort by length. For each pair adjacent prefixes: Take the first *different* value from the longer prefix.
> 3 votes

# Answer
# Python, ~~76~~ ~~75~~ 74 bytes

*-2 bytes thanx to Mukundan314*

```
lambda p,l=[]:[[*map(q.remove,l),l:=q+l][-1][0]for q in sorted(p,key=len)]

```

Attempt This Online!
> 2 votes

# Answer
# Perl 5, ~~83~~ 77 bytes

```
sub{map{$r{$z}--;%t=%r;++$t{$_}for@$_;($z)=grep$t{$_}==1,@$_}sort{@$a-@$b}@_}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
¯IévDysõ.;õK«

```

Try it online or verify all test cases.

**Explanation:**

```
¯              # Push an empty list; result-list starts with []
 I             # Push the input-list of lists
  é            # Sort it by length (shortest to longest)
   v           # Pop and loop over each inner list `y`:
    D          #  Duplicate the current result-list
     y         #  Push the current loop-list `y`
      s        #  Swap so the duplicated result-list is at the top
       õ.;     #  Replace every first occurrence in `y` with an empty string
          õK   #  Then remove those empty strings
            «  #  And merge the remaining single item to the result-list
               # (after the loop, the result-list is output implicitly)

```
> 2 votes

# Answer
# , 40 bytes

```
({.,1$:^:(0<#)@}.](1}.i.|.[)&.>{.)@/:#&>

```

Attempt This Online!

This approach is more or less a port of Arnauld's recursive approach.

# , 45 bytes

```
[:,@(2~.&>@-.~&>/\a:,]/:#&>)(a:-.~&,<\/.~)&.>

```

Try it online!

Kinda long, but possibly interesting approach to dealing with repeats:

* `(a:-.~&,<\/.~)&.>` A pre-processing step that goes through each set and replaces repeated items by actually repeating them. This allows our main code to assume uniqueness.
    + Eg, conceptually, if we have a list like `[a, b, a]`, it becomes `[a, b, [a, a]]`. We use nested J boxes for this.
* The remaining steps may now assume no repeats.
* `a:,]/:#&>` Sort the sets by their length, and add an empty set to start
* `2...-.~&>/\` Do consecutive set differences to recover the original list
* `~.&>@` Uniquify each to undo the effect of the first pre-processing step
* `,@` Flatten the result
> 2 votes

# Answer
# Python, 69 bytes

```
lambda p:[s for s,in sorted(p,key=len)if[r.remove(s)for r in p if r]]

```

Attempt This Online!

# Python, 73 bytes

```
lambda p:p and(m:=min(p,key=len))+f([q for q in p if q!=m!=q.remove(*m)])

```

Attempt This Online!
> 2 votes

# Answer
# Charcoal, 23 bytes

```
Ｗ⌊Φθ⁼Ｌκ⊕Ｌυ⊞υ⊟Φι›№ικ№υκυ

```

Try it online! Link is to verbose version of code. Accepts but does not require the empty prefix. Explanation:

```
Ｗ⌊Φθ⁼Ｌκ⊕Ｌυ

```

While there is a prefix with one more member than the number of terms collected so far, ...

```
⊞υ⊟Φι›№ικ№υκ

```

... find any terms that appear more times in that prefix than in the terms collected so far and push one to the (predefined empty) list of terms so far.

```
υ

```

Output the final list.

Differences between this solution and the numeric solution:

* Slightly different way of retrieving the next prefix, since I need to refer to it twice
* Different method of finding the next term, of course
* Resulting list is of strings so only takes 1 byte to output
> 1 votes

# Answer
# Python, 101 bytes

```
lambda l,p=0:[PyObj_FromPtr(-p+(p:=x))for x in sorted(sum(map(id,b))for b in l)]
from _ctypes import*

```

Attempt This Online!

-6 bytes thanks to Mukundan314.

Direct adaptation of xnor's answer for integers, converting the strings to and from integers using `id` and its inverse `_ctypes.PyObj_FromPtr`.
> 1 votes

# Answer
# APL+WIN, 58 bytes

Prompts for a nested vector of nested vectors of strings.

```
 i←↑r←m[⍋∊⍴¨m←⎕]⋄⍎∊(⍴r)⍴⊂'r←1↓1↓¨(¯1+r⍳¨r[1])⌽¨r⋄i←i,↑r⋄'⋄i

```

Try it online! Thanks to Dyalog Classic
> 0 votes

---
Tags: code-golf, array, set-theory
---


title: Are the two sets equal

text:
# Question
Title: Are the two sets equal
`{}`is the empty set. You may use `()` or `[]` if you choose.

We aren't going to rigorously define "set", but sets all satisfy the following properties:

Sets follow the usual mathematical structure. Here are some important points:

* Sets are not ordered.
* No set contains itself.
* Elements are either in a set or not, this is boolean. Therefore set elements cannot have multiplicities (i.e. an element cannot be in a set multiple times.)
* Elements of a set are also sets and `{}` is the only primitive element.

**Task**

Write a program/function that determines whether two sets are equal.

**Input**

Two valid sets via stdin or function argument. The input format is loose within reason.

Some valid inputs are:

```
{} {{}}
{{},{{}}} {{{{{},{{}}}}}}
{{},{{},{{}}}} {{{},{{}}},{{{{{},{{}}}}}}}

```

Invalid inputs:

```
{{} {}              Brackets will always be balanced.
{{},{}} {}          Set contains the same element twice

```

**Output**

A truthy value if the inputs are equal, falsy otherwise.

**Test cases**

Your submission should answer correctly for all valid inputs, not just for the test cases. These may be updated at any point.

Truthy:

```
{} {}
{{},{{}}} {{{}},{}}
{{},{{},{{{}},{}}}} {{{{},{{}}},{}},{}}

```

Falsy:

```
{} {{}}
{{},{{},{{{}},{}}}} {{{{}}},{},{{}}}
{{},{{}},{{{}}},{{},{{}}}} {}

```

**Scoring**

**Additional Rules**

An additional rule has been added banning unordered iterable types altogether. They are too common and trivialize this challenge far too much. Feel free to leave answers that violate this in place, please just make an indication that they were made before the rule change.

# Answer
# CJam, 11 bytes

```
q']/"]$"*~=

```

Try it here.

# CJam, 13 bytes

```
q~L{{j}%$}j:=

```

Try it here.
> 4 votes

# Answer
# Jelly, 6 bytes

```
ß€Ṣ
ÇE

```

Try it online! or verify all test cases.

### How it works

```
ÇE   Main link. Argument: [s, t] (pair of set arrays)

Ç    Apply the helper link to [s, t].
 E   Check if the elements of the resulting pair are equal.

ß€Ṣ  Helper link. Argument: u (set array)

ß€   Recursively map this link over u.
  Ṣ  Sort the result.

```
> 4 votes

# Answer
# APL (NARS2000), 4 bytes

```
≡⍦

```

is the multiset operator, which modifies functions to treat their arguments as sets instead of lists
is the equivalence function, which returns a Boolean indicating if the arguments are completely equivalent in value and shape

Regarding the additional rule: Note that this answer does not use any unordered set datatype, but just normal lists (which may contain multiple identical elements). It just *treats* them as sets.

The byte count is 4 because NARS2000 uses UCS-2 exclusively.
> 4 votes

# Answer
# Brachylog, 8 bytes

```
{p:1a.}.

```

This expects brackets in Input and Output.

For example:

```
?- run_from_atom('{p:1a.}.', [[]:[[]]], [[[]]:[]]).
true .

```

### Explanation

```
{     }.   True if the predicate inside brackets is true with input Input and output Output

 p          Unify an implicit variable with a permutation of Input
  :1a       Apply this same predicate to each element of that implicit variable
     .      True if Output can be unified with the resulting list

```
> 3 votes

# Answer
# Prolog (SWI), 37 bytes

```
X+Y:-permutation(X,Z),maplist(+,Z,Y).

```

Try it online!

Takes input as nested lists, i.e. with square brackets instead of braces. Originally, this was `X+Y:-sort(X,M),sort(Y,N),maplist(+,M,N).`, but then I tried translating Fatalize's Brachylog v1 answer and it turned out 3 bytes shorter.

```
X+Y :-                    X+Y succeeds when
    permutation(X, Z),    for some permutation Z of X
    maplist(+, Z, Y).     + succeeds for every pair in Z zipped with Y.
                          (where maplist will succeed without the recursive call to + for
                          two empty lists, and fail if the lists have different lengths)

```

It actually can handle curly braces instead, for 23 more bytes:

# Prolog (SWI), 60 bytes

```
{A}*C:-A=..[,|B],sort(B,C).
X+Y:-X=Y;X*M,Y*N,maplist(+,M,N).

```

Try it online!

`*` here converts a (nonempty, hence the `X=Y;`) brace term on its right side to a list of the term's elements then sorts it to its left side.

```
{A}*C :-            X*C succeeds when X is the brace term containing A
    A =.. [,|B],    where A is a comma-tuple and B is a list of its elements,
    sort(B, C).     and C is B sorted.

```

Since both arguments to `+` are going through `*` already, putting a `sort` in `*` saves 7 bytes over using `permutation` in `+`.

And finally, here's a version which handles the input lists possibly having duplicate elements, which is what inspired me to write a solution in Prolog to begin with:

# Prolog (SWI), 57 bytes

```
X+Y:-X/Y,Y/X.
X/Y:-maplist(-(Y),X).
Y-E:-member(F,Y),E+F.

```

Try it online!

```
X+Y :-                   X+Y succeeds when
    X/Y, Y/X.            X/Y and Y/X succeed.
X/Y :-                   X/Y succeeds when
    maplist(-(Y), X).    for every element E of X, Y-E succeeds
                         (or when X is empty).
Y-E :-                   Y-E succeeds when
    member(F, Y),        there exists some element F of Y
    E+F.                 such that E+F succeeds.

```

Essentially, `X/Y` declares that X is a subset of Y, by declaring that for every element of X, there's an equal element of Y, so `X/Y,Y/X` declares that X and Y are equal sets.
> 3 votes

# Answer
# Pyth, 9 bytes

```
LSyMbqyEy

```

Input format: use `[]` instead of `{}`.

Test suite
> 2 votes

# Answer
# Python 2, 49 bytes

```
f=lambda x:sorted(map(f,x))
lambda a,b:f(a)==f(b)

```

For example, calling the anonymous function `g`:

```
>>> g( [[],[[]]] , [[[]],[]] )
True

```
> 2 votes

# Answer
## Mathematica, 16 bytes

```
Equal@@Sort//@#&

```

An unnamed function which expects a list containing both sets, e.g.

```
Equal@@Sort//@#& @ {{{}, {{}}}, {{{}}, {}}}

```

We use `//@` (`MapAll`) to sort the sets at every level and then assert at the results are equal.
> 2 votes

# Answer
## JavaScript (ES6), 42 bytes

```
f=(a,b,g=a=>0+a.map(g).sort()+1)=>g(a)==g(b)

```

Accepts input using `[]`s e.g. `f([[],[[]]],[[[]],[]])`. Works by converting the arrays to strings and then sorting them from the inside out. `0` and `1` are used because they're shorter than `'['` and `']'`, so for example `g([[[]],[]])` is `001,00111` which represents `[[],[[]]]`.
> 2 votes

# Answer
# Julia, ~~36~~ ~~35~~ 32 bytes

```
u*v=(sort(u.*v)...)
s%t=s*s==t*t

```

Input is a nested array either either the (deprecated) `{}` syntax or `Any[]`.

Try it online!
> 1 votes

# Answer
# SETL, 1 byte

```
=

```

Takes sets as left and right arguments.

Note that this does NOT adhere the added rule which prohibits unordered set datatypes.
> 1 votes

# Answer
# Brachylog v2, 3 bytes

```
p↰ᵐ

```

Try it online!

Takes one set through the input variable and the other set through the output variable. Succeeds if the sets are equal and fails if they aren't.

Like my main Prolog answer, a translation of Fatalize's Brachylog v1 answer (which I think could be golfed down to `p:0a`?).

```
       The input
p      can be re-ordered so that
 ↰     when this predicate is applied again to
  ᵐ    all of its elements,
       it is the output.

```
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Outputs a non-nested empty list if truthy, anything else is falsey. In Vyxal, the empty list is falsey but a list containing only an empty list is truthy.
> 1 votes

# Answer
# , 7 chars / 9 bytes

```
ѨƾꞨî,Ꞩí

```

`Try it here (ES6 browsers only).`

# Explanation

```
         // implicit: î=input1,í=input2
  Ꞩî,Ꞩí // apply the Set method to both inputs
Ѩƾ      // check if the Sets are equal
        // implicit output

```
> 0 votes

# Answer
# Haskell, 77 bytes

```
import Data.List
data S=L[S]deriving(Eq,Ord)
f(L x)=L$sort$f<$>x
a!b=f a==f b

```
> 0 votes

# Answer
# Perl 6, 55 bytes

```
my&f=->\a,\b {a==b&&all map {f(|$_)},(a.sort Z,b.sort)}

```

Takes input with `[]`.

Try it online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 20 bytes

```
Sort//@#==Sort//@#2&

```

Try it online!

Pure function that takes each set as an argument.
> 0 votes

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


title: What and where is the max?

text:
# Question
Title: What and where is the max?
This small challenge derives from my annoyance at discovering that numpy doesn't have a built in function for it.

# Input

An n by m matrix of integers.

# Output

The maximum value in the matrix and the 2d coordinates of one of its occurrences. The coordinates should be in the order (row\_idx, col\_idx) if your code is no shorter than it would be with (col\_idx, row\_idx). Otherwise it can be (col\_idx, row\_idx) but if so, please explain it in your answer.

1-based indexing is allowed too

# Examples

```
Input [[1, 2], [3, 4]]. Output (4, (1, 1))
Input [[-1]]. Output (-1, (0, 0))
Input [[6], [5], [4], [3], [2], [1]]. Output (6, (0, 0))
Input [[1, 2, 3, 4], [0, 2, 5, 3], [-5, -2, 3, 5]]. Output (5, (1, 2))

```

# Note

numpy answers gratefully received too.

# Answer
> 10 votes
# Julia 1.0, 7 bytes

```
findmax

```

Try it online!

Outputs `(value, CartesianIndex(row_index, col_index))` (1-indexed)

# Answer
> 9 votes
# Python \+ Numpy, 48 bytes

```
lambda x:(x.max(),divmod(x.argmax(),x.shape[1]))

```

Attempt This Online!

# Answer
> 6 votes
# Uiua SBCS, 9 bytes

```
⊢⊚⊃=∘/↥♭.

```

Try it!

```
⊢⊚⊃=∘/↥♭.
        .  # duplicate
       ♭   # deshape
     /↥    # maximum
  ⊃=∘      # mask of where the max exists in input
 ⊚         # coordinates of the ones
⊢          # first

```

# Answer
> 5 votes
# Vyxal, 3 bytes

```
Þė↑

```

Try it Online!

And they said maximum by tail was useless! Now who's laughing! (me... It's me who's laughing)

Outputs `[[x, y], item]`.

## Explained

```
Þė↑
Þė   # Multidimensional enumeration
  ↑  # Maximum by tail

```

Created with the help of Luminespire.

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~12~~ 11 bytes

−1 byte thanks to Mukundan314

Requires `⎕IO←0` which is default on many systems. Returns `[max, row_idx, col_idx]`

```
M,⍴⊤,⍳M←⌈/,

```

Try it online!

`⌈/` the maximum (lit. maximum reduction) of the

`,` ravelled (flattened) argument

`M←` store that as `M` (for **M**aximum)

`,⍳`**i**ndex of first location of that in the ravelled (flattened) argument

`⍴⊤` the shape-radix representation of that

`M,` prepend the Maximum

# Answer
> 5 votes
# K (ngn/k), 12 bytes

```
(*+&=)\||//\

```

Try it online!

```
        |//           max
           \    (mat,    )
(    )\|        (max,        )
   &=                 indices
 *+                   first

```

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

Returns `[max, y, x]`.

```
m=>m.map((r,y)=>r.map((v,x)=>m=v<m[0]?m:[v,y,x]))&&m

```

Try it online!

# Answer
> 4 votes
# Jelly, 5 bytes

```
ŒĖṚ€Ṁ

```

A monadic Link that accepts a (multidimensional) array and yields a pair, `[maximum-value, [row, column, ...]]` using 1-indexing. (Identifying the last location of the maximum-value.)

**Try it online!**

### How?

While Jelly has both `ŒM` (get *all* multidimensional indices of maximal elements), `œị` (get element at multidimensional index y), and `œi` (get first multidimensional index of y), amongst some others I think this may be the tersest approach...

```
ŒĖṚ€Ṁ - Link: multidimensional array of comparables, A
ŒĖ    - multidimensional enumerate
  Ṛ€  - reverse each (from [coordinates, value] to [value, coordinates])
    Ṁ - maximum

```

# Answer
> 4 votes
# Python \+ numpy, 61 bytes

```
lambda x:max(zip(x.flat,ndindex(x.shape)))
from numpy import*

```

Attempt This Online!

Returns the last index of the maximal value. Different 63 bytes, maybe `key=` can shorten this a bit?

```
lambda x:max((b,a)for a,b in ndenumerate(x))
from numpy import*

```

Attempt This Online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 29 bytes

```
{s=Max@#,#&@@#~Position~s-1}&

```

Try it online!

-1 byte from @att

# Answer
> 4 votes
# , 35 bytes

Almost built-in, but `which.max` flattens the input.

```
\(x,m=max(x))c(m,which(x==m,T)[1,])

```

Attempt This Online!

Fixed indexing and returned result, thanks to Giuseppe.

# Answer
> 4 votes
# Brachylog, ~~12~~ 8 bytes

*-4 bytes thanks to Fatalize*

```
{iiʰ}ᶠot

```

Outputs as `[[max, col], row]`. Try it online!

**Explanation**

```
{iiʰ}ᶠot
{   }ᶠ    Find all ways of satisfying this predicate:
 i         Get some [element, index] pair (i.e. a row and its row index)
  iʰ       Apply the same operation to that row, turning it into an element and
           its column index
          We now have a list of [[element, col], row] for each element in the array
      o   Sort ascending
       t  Take the last one

```

## Nicer output format, 11 bytes

```
{iiʰ}ᶠotgᵗc

```

Outputs as `[max, col, row]`. Try it online!

**Explanation**

```
{iiʰ}ᶠotgᵗc
{iiʰ}ᶠot     Same as above, gives [[max, col], row]
        gᵗ   Wrap the last element in a singleton list: [[max, col], [row]]
          c  Concatenate: [max, col, row]

```

To output as `[max, row, col]` is **12 bytes**; the only change is to transpose the matrix first with `\`:

```
\{iiʰ}ᶠotgᵗc

```

To output as `[max, [row, col]]` as originally requested is... longer. Brachylog doesn't handle mixed-type lists very well.

# Answer
> 4 votes
# Rust + ndarray, 41 bytes

```
|a|a.indexed_iter().max_by_key(|(_,x)|*x)

```

A closure of type `fn(&Array2<u8>)->Option<((usize, usize), &u8)>`.

`ndarray_stats` has an `argmax`, but it's very verbose at 46 bytes:

```
{use ndarray_stats::*;|a|(a.max(),a.argmax())}

```

# Answer
> 3 votes
# Haskell, ~~56~~ 55 bytes

*Another one bytes the dust thanks to DLosc.*

```
f m=maximum[(c,(y,x))|(y,r)<-e m,(x,c)<-e r]
e=zip[0..]

```

Try it online!

Heh, this is technically a built-in solution. Outputs as `(max, (y, x))`.

## Weird output solution, ~~46~~ 39 bytes

*-7 bytes thanks to to DLosc.*

```
maximum.e.map(maximum.e)
e=(`zip`[0..])

```

Try it online!

This effectively does the same thing but outputs as `((max, x), y)`.

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
˜Z=kIнg‰,

```

0-based; outputs the maximum and coordinate on separated newlines.

Try it online or verify all test cases.

**Explanation:**

Unfortunately, 05AB1E lacks multidimensional builtins, so things are done manually. Otherwise this could have been 4-5 bytes probably.

```
˜          # Flatten the (implicit) input-matrix
 Z         # Push its maximum (without popping the list)
  =        # Print this max with trailing newline (without popping again)
   k       # Pop both now, and get the 0-based index of this max in the list
    Iнg    # Push the width of the input-matrix (push input; first item; length)
       ‰   # Divmod the index by this width
        ,  # Pop and print it with trailing newline as well

```

# Answer
> 3 votes
# Perl 5 `MList::Util=max -p` 58 bytes

```
$\=max/-?\d+/g;/\[[^[]*$\\b/;say$`=~y/[//-1;say$&=~y/,//}{

```

Try it online!

Output format is

```
row
column
max

```

# Answer
> 2 votes
# Charcoal, 12 bytes

```
Ｉ⌈ＥＡ⟦⌈ικ⌕ι⌈ι

```

Try it online! Link is to verbose version of code. Outputs the highest possible row with the maximum value but the lowest possible column in that row. Explanation:

```
   Ａ            Input array
  Ｅ             Map over rows
      ι         Current row
     ⌈          Maximum value
       κ        Current index
        ⌕       First index of
           ι    Current row
          ⌈     Maximum value
         ι      In current row
    ⟦           Make into list
 ⌈              Take the maximum
Ｉ               Cast to string
                Implicitly print

```

Getting the maximum column of the maximum row can be done for 14 bytes:

```
Ｉ⌈ＥＡ⟦⌈ικ⌈⌕Ａι⌈ι

```

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

```
Ｉ⌈ＥＡ⟦⌈ικ        As above
         ⌕Ａ     Find all indices of
             ι  Current row
            ⌈   Maximum value
           ι    In current row
        ⌈       Take the maximum

```

Getting the lowest possible row with the lowest possible column takes a massive 21 bytes:

```
ＩＥ⌈Ｅθ⟦⌈ι±κ⌕ι⌈ι⟧⎇⊖κι±ι

```

Try it online! Link is to verbose version of code. Explanation: Negates the row number, which gives you the highest possible negated row, but then has to negate it again for display.

# Answer
> 2 votes
# Google Sheets, 63 59 bytes

```
=+sort(tocol(A:N&","&row(A:N)&","&column(A:N)),tocol(A:N),)

```

Put the 2D array in cells `A1:N1000` and the formula in cell `P1`.

Singularizes the data and coordinates and sorts in descending order. Uses unary plus `+` to extract just the first result. Gives 1-indexed coordinates.

# Answer
> 2 votes
# Go, 147 bytes

```
import."slices"
func f(I[][]int)(m,x,y int){m=Max(I[0])
for _,r:=range I{m=max(m,Max(r))}
for a,r:=range I{x,y=a,Index(r,m)
if y>-1{break}}
return}

```

Attempt This Online!

Returns as `max, x, y`. Assumes that the matrix is non-empty.

### Explanation

```
import."slices"
func f(I[][]int)(m,x,y int){
 m=Max(I[0])                       // default value for max, to account for negatives
 for _,r:=range I{m=max(m,Max(r))} // find the max of the whole matrix
 for a,r:=range I{                 // find the location of the max
  x,y=a,Index(r,m)                 // the current row index, and the index of the max
  if y>-1{break}}                  // if the max is in this row, exit the loop
 return
}

```

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~66~~ 60 bytes

Vanilla Python approach, outgolfed by the `numpy` versions.

*-6 bytes as lambda expression instead of a function*

```
lambda m:(a:=max(l:=sum(m,[])),divmod(l.index(a),len(m[0])))

```

Try it online!

# Answer
> 2 votes
# Nekomata, 11 bytes

```
ᵉ#Ť#ᵒÐᶻᶻÐjṀ

```

Attempt this online!

This language is cool, though this isn't really using the cooler aspects of it. I also have a sneaking suspicion this can get better.

## Alternate solution, 11 bytes

```
ᵐ{xᶻ,Ṁ}xᶻ,Ṁ

```

Attempt this online!

This is more elegant, but it flips the indices.

# Answer
> 1 votes
# APL(NARS), 109 chars

```
r←f w;i;j;s;h;k;a;b
j←1⋄s←¯∞⋄h←k←⍬⋄(a b)←⍴w
i←1
→4×⍳∼w[i;j]>s⋄h←i⋄k←j⋄s←w[i;j]
→3×⍳a≥i+←1⋄→2×⍳b≥j+←1
r←s(h,k)

```

19+23+3+30+21+8+5=109

How to use&test:

```
      ⎕fmt f 2 3⍴ 1 4 3 2 ¯1 5
┌2───────┐
│  ┌2───┐│
│5 │ 2 3││
│~ └~───┘2
└∊───────┘
      ⎕fmt 2 3⍴ 1 4 3 2 ¯1 5
┌3──────┐
2 1  4 3│
│ 2 ¯1 5│
└~──────┘

```

it would return the max and the first coordinates it finds max

# Answer
> 1 votes
# Haskell \+ hgl, 22 bytes

```
xB cr<Asx<<(mM eu<+eu)

```

Attempt This Online!

Outputs as `((x,y),v)`

# Strange order, 21 bytes

```
xB(cr<cr)<(mM eu<+eu)

```

Attempt This Online!

Outputs as `(x,(y,v))`

# Different strange order, 21 bytes

```
mx<g<m(mx<g)

```

```
g=fzp nn

```

Attempt This Online!

Outputs as `((v,y),x)`

# Reflection

This answer is hampered by the fact I haven't yet implemented any array handling functions, so this has to work with lists.

That asside, I have a couple of thoughts:

* There should be a flipped version of `eu`. I approximate this with `fzp nn` in the final version.
* `cr<cr` is a useful enough function to have a short version.

# Answer
> 1 votes
# APL+WIN, 32 bytes

Prompts for matrix:

```
(⌈/,m),(,(⍳↑⍴m)∘.,⍳1↓⍴m)[↑⍒,m←⎕]

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# Racket, ~~114~~ 112 bytes

Output in the format `(value row_idx col_idx)`

```
(λ(x[y(apply append x)][m(flatten y)][i(index-of y m)][l(length(car x))])(list m(quotient i l)(remainder i l)))

```

Try it online!

```
(λ(x
   [y (flatten x)]                      ; flatten the matrix
   [m (apply max y)]                    ; find the max value
   [i (index-of y m)]                   ; index of the value
   [l (length (car x))])                ; length of a row
 (list m(quotient i l)(remainder i l))) ; format output

```

# Answer
> 1 votes
# Ruby, 55 bytes

```
->a{b=a.flatten
[m=b.max,b.index(m).divmod(a[0].size)]}

```

Attempt This Online!

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