title: Remove surrounding zeroes of a 2d array

text:
# Question
Title: Remove surrounding zeroes of a 2d array
This is a 2-dimensional version of this question.

Given a non-empty 2-dimensional array/matrix containing only non-negative integers:

$$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & 0 & 1 & 0 \\ {\color{Red}0} & {\color{Red}0} & 0 & 0 & 1 \\ {\color{Red}0} & {\color{Red}0} & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} $$

Output the array with surrounding zeroes removed, i.e. the largest contiguous subarray without surrounding zeroes:

$$ \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 1 \end{bmatrix} $$

## Examples:

$$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & 0 & 1 & 0 \\ {\color{Red}0} & {\color{Red}0} & 0 & 0 & 1 \\ {\color{Red}0} & {\color{Red}0} & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 1 \end{bmatrix} $$

```
Input:
[[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 0]]

Output:
[[0, 1, 0], [0, 0, 1], [1, 1, 1]]

```

$$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 0 & 0 & 3 \\ {\color{Red}0} & 0 & 0 & 0 \\ {\color{Red}0} & 5 & 0 & 0 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 0 & 0 & 3 \\ 0 & 0 & 0 \\ 5 & 0 & 0 \end{bmatrix} $$

```
Input:
[[0, 0, 0, 0], [0, 0, 0, 3], [0, 0, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]]

Output:
[[0, 0, 3], [0, 0, 0], [5, 0, 0]]

```

$$ \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \mapsto \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} $$

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

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

```

$$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} \end{bmatrix} $$

```
Input:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Output:
[]

```

$$ \begin{bmatrix} {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \\ 1 & 1 & 1 & 1 \\ {\color{Red}0} & {\color{Red}0} & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 1 & 1 & 1 & 1 \end{bmatrix} $$

```
Input:
[[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]]

Output:
[[1, 1, 1, 1]]

```

$$ \begin{bmatrix} {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \\ {\color{Red}0} & 1 & {\color{Red}0} & {\color{Red}0} \end{bmatrix} \mapsto \begin{bmatrix} 1 \\ 1 \\ 1 \end{bmatrix} $$

```
Input:
[[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]

Output:
[[1], [1], [1]]

```

$$ \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 2 & 3 & 1 \\ 1 & 1 & 1 & 1 \end{bmatrix} \mapsto \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & 2 & 3 & 1 \\ 1 & 1 & 1 & 1 \end{bmatrix} $$

```
Input:
[[1, 1, 1, 1], [1, 2, 3, 1], [1, 1, 1, 1]]

Output:
[[1, 1, 1, 1], [1, 2, 3, 1], [1, 1, 1, 1]]

```

# Answer
> 12 votes
# MATL, 3 bytes

```
JYa

```

Try it online! Or verify all test cases.

### Explanation

```
J      % Push 1j
Ya     % With complex 2nd input, this unpads the matrix in the
       % 1st input (implicit). The unpad value is 0 by default
       % Display (implicit)

```

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

```
#&@@CellularAutomaton[{,{},0{,}},{#,0},0]&

```

Try it online!

Cellular automata are indeed the answer to life, the universe, and everything.1

### How?

`CellularAutomaton` accepts an input array and an optional background value. Thus, `{#,0}` specifies that a cellular automaton rule should be applied to the input, assuming a background of `0`s.

A neat thing here is that `CellularAutomaton` crops the output so that no border of background cells is present (because otherwise the output lies on an infinite plane).

The code applies the rule `{Null, {}, {0, 0}}` -- applying the head `Null` to the 0-radius neighbor of each cell (i.e. only the center: the cell itself) -- exactly `0` times. The result of this is the original input, but with background removed (i.e. cropping out surrounding `0`s).

---

1. See the bytecount of my answer? ;)

# Answer
> 14 votes
# JavaScript (ES6), 98 bytes

```
(a,z)=>(g=A=>A.slice(A.map(m=M=(r,i)=>M=(z?a:r).some(n=>z?n[i]:n)?1/m?i:m=i:M)|m,M+1))(a).map(z=g)

```

Try it online!

### How?

To overcome the lack of a *zip* built-in, we define a function ***g()*** that is able to operate on either the rows or the columns of the input matrix ***a\[ \]***, depending on the value of the global flag ***z***.

***g()*** looks for the minimum index ***m*** and maximum index ***M*** of either non-empty rows (if ***z*** is undefined) or non-empty columns (if ***z*** is defined) and returns the corresponding *slice* of either the matrix itself or a given row of the matrix.

To summarize:

* we first remove rows by invoking ***g()*** on the matrix with ***z*** undefined
* we then remove columns by invoking ***g()*** on each row with ***z*** defined, which leads to this rather unusual `.map(z=g)`

### Commented

```
(a, z) => (               // a[] = input matrix; z is initially undefined
  g = A =>                // g() = function taking A = matrix or row
    A.slice(              //   eventually return A.slice(m, M + 1)
      A.map(m = M =       //     initialize m and M to non-numeric values
        (r, i) =>         //     for each row or cell r at position i in A:
        M = (z ? a : r)   //       iterate on either the matrix or the row
        .some(n =>        //       and test whether there's at least one
          z ? n[i] : n    //       non-zero cell in the corresponding column or row
        ) ?               //       if so:
          1 / m ? i       //         update the maximum index M (last matching index)
                : m = i   //         and minimum index m (first matching index)
        :                 //       otherwise:
          M               //         let M (and m) unchanged
      ) | m,              //     end of map(); use m as the first parameter of slice()
      M + 1               //     use M+1 as the second parameter of slice()
    )                     //   end of slice()
  )(a)                    // invoke g() on the matrix with z undefined
  .map(z = g)             // invoke g() on each row of the matrix with z defined

```

# Answer
> 7 votes
# Haskell, ~~62~~ 61 bytes

```
f.f.f.f
f=reverse.foldr(zipWith(:))e.snd.span(all(<1))
e=[]:e

```

Try it online!

`foldr(zipWith(:))e` with `e=[]:e` is a slightly shorter `transpose`, and `snd.span(all(<1))` drops leading lists of zeros from a list of list. As `transpose` followed by `reverse` on a 2D list equals an rotation by 90°, the code `f.f.f.f` is just four times *drop leading lists of zeros and rotate*.

# Answer
> 6 votes
# Pyth, 13 bytes

```
V2=.sCQ]m0Q;Q

```

Try it online!

# Answer
> 5 votes
# , ~~96 100~~ 97 bytes

```
function(m)m[~m,~t(m),drop=F]
"~"=function(x,z=seq(r<-rowSums(x)))z>=min(y<-which(r>0))&z<=max(y)

```

Try it online!

The `~` helper takes a non-negative vector and returns a vector with `FALSE` for the "exterior" `0`s of the vector and `TRUE` for positives and any "interior" `0`s. This function is applied to the row and column sums of the input matrix.

`~` and `!` use R's parser treatment of operators.

Corrected as per @DigEmAll's comment, but with some bytes golfed back from @J.Doe

# Answer
> 5 votes
# Jelly, 10 bytes

```
œr€0z0Uµ4¡

```

Try it online!

# Answer
> 5 votes
# Brachylog, ~~24~~ ~~22~~ ~~20~~ 19 bytes

```
{s.h+>0∧.t+>0∧}\↰₁\

```

Try it online!

Outputs the result matrix as an array of arrays, or false for empty output.

*(Thanks to @Fatalize for suggesting inline predicate and saving 1 byte.)*

### Explanation

**Predicate 0 (Main):**

```
{...}     Define and call predicate 1 to remove all-zero rows
  \       Transpose the result
   ↰₁     Call pred 1 again, now to remove all-zero columns
     \    Transpose the result to have correct output orientation

```

**Predicate 1:**

```
?s.h+>0∧.t+>0∧
  .           output is
 s              a subsequence of the rows of
?              the input (implicit)
   h          also, output's head element (first row)
    +>0        has a sum > 0 (i.e. has at least one non-zero value)
       ∧.t+>0  and similarly the output's tail element (last row)
∧              (don't implicitly unify that 0 with the output)

```

# Answer
> 5 votes
# , ~~89~~ 79 bytes

```
function(m,y=apply(which(m>0,T),2,range)){y[!1/y]=0;m[y:y[2],y[3]:y[4],drop=F]}

```

Try it online!

Thanks to @ngm for the test cases code, and @J.Doe for saving 10 bytes !

* I had to add `drop=F` parameter due to the default R behavior turning single row/col matrix into vectors...

# Answer
> 4 votes
# APL (Dyalog Classic), ~~17~~ 15 bytes

```
{⍉⌽⍵⌿⍨∨\∨/×⍵}⍣4

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 66 bytes

```
If[Max@#>0,ImageCrop@Image[#~ArrayPad~1,r="Real"]~ImageData~r,{}]&

```

Try it online!

Now works by padding the array with zeroes (thanks @JungHwanMin)!

A second thanks to @JungHwanMin for saving 4 bytes

# Answer
> 3 votes
# Python 2, 71 bytes

Returns by modifying the input. A list should be passed as input.

```
def f(a):exec'while a and 1>sum(a[-1]):a.pop()\na[:]=zip(*a)[::-1]\n'*4

```

Try it online!

---

# Python 2, 77 bytes

This also modifies the input, but it works....

```
def f(a):exec'while a and 1>sum(a[-1]):a.pop()\na=zip(*a)[::-1]\n'*4;return a

```

Try it online!

# Answer
> 3 votes
# , 24 bytes

```
(|.@|:@}.~0=+/@{.)^:4^:_

```

Try it online!

## Explanation

```
(|.@|:@}.~0=+/@{.)^:4^:_
            +/                sum
              @               of
               {.             the first row
          0=                  is zero? (1 = true, 0 = false)
       }.~                    chop off that many rows from the front
 |.@|:@                       rotate by 90 deg (transpose then reverse)
(                )^:4         repeat this process 4 times (rotating a total of 360 deg)
                     ^:_      fixpoint - repeat until no change

```

# Answer
> 2 votes
# Python 2, ~~118~~ 116 bytes

```
f=lambda a,n=4,s=sum:n and f(zip(*a[max(i for i in range(len(a))if s(s(a[:i],()))<1):][::-1]),n-1)or(s(s(a,()))>0)*a

```

Try it online!

---

Saved:

* -2 bytes, thanks to shooqie

# Answer
> 2 votes
# Jelly, 12 bytes

```
Ṗ§Ṫ¬ȧƲ¿UZµ4¡

```

Try it online!

As a function.

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

```
Nest[Reverse@Thread@#//.{{0..},a___}->{a}&,#,4]&

```

Try it online!

Doing it the normal way.

# Answer
> 2 votes
# K (ngn/k), ~~22~~ 19 bytes

```
4{+|(+/&\~+/x)_'x}/

```

Try it online!

# Answer
> 2 votes
# Husk, 11 bytes

```
!5¡(T0mo↔↓¬

```

Try it online!

I feel like some bytes could be shaved off by shortening the `!5¡` part.

### How it works

```
!5¡(

```

Repeatedly apply the function explained below, collecting the results in an infinite list. Then, retrive the \\$5^{\text{th}}\\$ element. In other words, apply the function to the input 4 times.

```
mo↔↓¬

```

Map over the current version of the input and: reverse each, after having dropped the longest prefix consiting of zeroes only (dropping this prefix is performed by using Husk's , which is a function that crops the longest run of consecutive elements from the beginning of the list that yield truthy results when ran through a function, namely `¬`, logical not).

```
T0

```

Transpose, replacing missing entries with **0**.

# Answer
> 2 votes
# Retina, 87 bytes

```
/.\[(?!0,)/^+`\[0,
[
/(?<! 0)]./^+`, 0]
]
\[(\[0(, 0)*], )+
[
(, \[0(, 0)*])+]|\[0]]
]

```

Try it online! Explanation:

```
/.\[(?!0,)/^+`

```

Until at least one row doesn't begin with zero...

```
\[0,
[

```

... remove the leading zero from each row.

```
/(?<! 0)]./^+`

```

Until at least one row doesn't end with zero...

```
, 0]
]

```

... remove the trailing zero from each row.

```
\[(\[0(, 0)*], )+
[

```

Remove leading rows of zeros.

```
(, \[0(, 0)*])+]|\[0]]
]

```

Remove trailing rows of zeros, or the last remaining zero.

# Answer
> 2 votes
# Charcoal, 48 bytes

```
Ｆ⁴«Ｗ∧θ¬Σ§θ±¹Σ⊟θ¿θ≔⮌Ｅ§θ⁰Ｅθ§§θνλθ»⪫[]⪫Ｅθ⪫[]⪫ι, ¦,

```

Try it online! Link is to verbose version of code. Includes 15 bytes for formatting. Explanation:

```
Ｆ⁴«

```

Repeat 4 times.

```
Ｗ∧θ¬Σ§θ±¹

```

Repeat while the array is not empty but its last row sums to zero...

```
Σ⊟θ

```

Remove the last row from the array and print a line of the length of its sum, i.e. nothing.

```
¿θ≔⮌Ｅ§θ⁰Ｅθ§§θνλθ»

```

If the array isn't empty then transpose it.

```
⪫[]⪫Ｅθ⪫[]⪫ι, ¦,

```

Format the array nicely for display. (Standard output would be `Ｉθ` instead.)

# Answer
> 2 votes
# JavaScript, 144 140 129 127 bytes

```
w=>(t=w=>(q=(s=w=>w.some((r,j)=>r.find(e=>e,i=j))?w.slice(i).reverse():[[]])(s(w)))[0].map((e,j)=>q.map((e,i)=>q[i][j])))(t(w))

```

140 -\> 129 bytes, thanks @Arnauld

### Algorithm

* Do twice:
    + Find first non-zero row
    + Slice off preceding rows
    + Reverse
    + Find first non-zero row
    + Slice off preceding rows
    + Reverse
    + Transpose

```
f = w=>(t=w=>(q=(s=w=>w.some((r,j)=>r.find(e=>e,i=j))?w.slice(i).reverse():[[]])(s(w)))[0].map((e,j)=>q.map((e,i)=>q[i][j])))(t(w));

w1 = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 0, 0, 0]];
w2 = [[0, 0, 0, 0], [0, 0, 0, 3], [0, 0, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]];
w3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
w4 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

console.log(f(w1).join("\n"));
console.log(f(w2).join("\n"));
console.log(f(w3).join("\n"));
console.log(f(w4));
```

# Answer
> 2 votes
# PHP (\>=5.4), ~~200~~ ~~194~~ ~~186~~ 184 bytes

(-6 bytes by returning `null` instead of empty array)

(-8 bytes thanks to Titus)

(-2 bytes with calling by reference thanks to Titus)

```
function R(&$a){$m=$n=1e9;foreach($a as$r=>$R)foreach($R as$c=>$C)if($C){$m>$r&&$m=$r;$M>$r||$M=$r;$n>$c&&$n=$c;$N>$c||$N=$c;}for(;$m<=$M;)$o[]=array_slice($a[$m++],$n,$N-$n+1);$a=$o;}

```

Try it online!

# How?

Finds min and max index for rows (`$m` & `$M`) and columns (`$n` & `$N`) and replaces the input with a sub array from `$m,$n` to `$M,$N` (this is a call by reference).

# Answer
> 2 votes
# Ruby, ~~73~~ 63 bytes

```
->a{4.times{_,*a=a while a[0]&.sum==0;a=a.reverse.transpose};a}

```

Try it online!

Edit: simplified, also the previous version crashed for all `0`s

### How it works:

* do 4 times:
    + remove the first line while there is a first line and it's full of `0`s
    + rotate the array clockwise by 90°
* return the array

# Answer
> 2 votes
# Octave, ~~48~~ 49 bytes

```
@(a)sparse(1-min([x y v]=find(a))+x,1-min(y)+y,v)

```

Try it online!

Find nonzero points and rearrange them in a new sparse matrix.

# Answer
> 1 votes
# Octave, ~~78~~ 74 bytes

```
function x=f(x)
for k=1:nnz(~x)*4,x=rot90(x);x=x(:,~~cumsum(any(x,1)));end

```

Try it online!

### Explanation

This rotates the matrix by `90` degrees (`x=rot90(x)`) a sufficient number of times (`for k=1:... end`). The number of rotations is a multiple of `4`, so the final matrix has the original orientation. Specifically, the number of rotations is `4` times the number of zeros in the matrix (`nnz(~x)*4`).

For each rotation, if there are one or more columns on the left consisting of only zeros they are removed (`x=x(:,~~cumsum(any(x,1)))`).

What remains of the matrix after this process is output by the function (`function x=f(x)`).

# Answer
> 1 votes
# Japt `-h`, ~~23~~ 11 bytes

```
4Æ=sUb_dÃ z

```

Try it

---

## Explanation

```
                :Implicit input of 2D-array U
4Æ              :Map the range [0,4)
   s            :  Slice U from
    Ub          :   The first index in U where
      _dÃ       :    Any element is truthy (not zero)
          z     :  Rotate 90 degrees
  =             :  Reassign to U for the next iteration
                :Implicitly output the last element

```

# Answer
> 1 votes
# Attache, 40 bytes

```
Fixpoint[{Flip!_[N[0=Sum!_@0]...#_]}//4]

```

Try it online! Same business as below, just a bit smarter, splitting the process into four steps instead of two.

## Alternatives

**47 bytes:** `Fixpoint[{Reverse=>Tr!_[N[0=Sum!_@0]...#_]}//4]`

**48 bytes:** `Fixpoint[{MatrixRotate!_[N[0=Sum!_@0]...#_]}//4]`

---

## Attache, 68 bytes

```
Fixpoint[{n.=Dim@_@-1Tr[{_@1!in~-n'0or Sum!_@0}\Enumerate@_<:0]}//2]

```

Try it online!

Twice: This removes any first or last row whose sum is `0`, then transposes the array. Then, this process is repeated until the result does not change.

# Answer
> 1 votes
# Stax, 14 bytes

```
Ç·W≈y§╗♦º{¬║8•

```

Run and debug it

### Alternative, also 14 bytes

```
Ç·W≈x≈ƒHq♣☻»íÅ

```

Run and debug it

# Answer
> 1 votes
# PHP, 188 bytes

```
function f(&$a){for($s=array_shift;!max($a[0]);)$s($a);for($p=array_pop;!max(end($a));)$p($a);for($w=array_walk;!max(($m=array_map)(reset,$a));)$w($a,$s);while(!max($m(end,$a)))$w($a,$p);}

```

call by reference.

**breakdown**

```
// call by reference
function f(&$a)
{
    // while first row is all zeroes, remove it
    while(!max($a[0]))array_shift($a);
    // while last row is all zeroes, remove it
    while(!max(end($a)))array_pop($a);
    // while first column is all zeroes, remove it
    while(!max(array_map(reset,$a)))array_walk($a,array_shift);
    // while last column is all zeroes, remove it
    while(!max(array_map(end,$a)))array_walk($a,array_pop);
}

```

# Answer
> 1 votes
# Clean, 73 bytes

```
import StdEnv,StdLib
$ =dropWhile(all((>)1))o reverse o transpose

```

#

```
$o$o$o$

```

Try it online!

Very similar to Laikoni's Haskell answer.

# Answer
> 1 votes
# 05AB1E (legacy), 13 bytes

```
2Fζ2FRDv¬O_i¦

```

Try it online or verify all test cases.

**Explanation:**

```
2F                    # Loop two times:
  ζ                   #  Zip/transpose; swapping rows/columns
                      #  (takes the input-matrix implicitly in the first iteration)
   2F                 #  Inner loop two times:
     R                #  Reverse the rows
      Dv              #  Inner loop over the rows:
        ¬             #   Get the first row (without popping the matrix)
         O_i          #   If the row consists only of 0s:
            ¦         #    Remove this first row from the matrix
                      # (output the result implicitly)

```

# Answer
> 1 votes
# Python 2, 86 bytes

```
lambda a,l=1:a if l>4else([a.pop()for b in a if sum(a[-1])<1],f(zip(*a[::-1]),l+1))[1]

```

Try it online!

Takes a list of lists, returns a list of tuples.

## Explanation

Abuses the heck out of list comprehension. This is the equivalent expanded code:

```
def f(a,l=1):
    # after 4 rotations, the list is back in its original orientation, return
    if l > 4:
        return a
    else:
        # helper variable to store return values
        ret = []
        # "trim" all rows from "bottom" of list that only contain 0s
        # since we are always checking le that item in the list, don't need range(len(a))
        # since we are only removing at most one item per iteration, will never try to remove more than len(a) items
        # brackets surrounding generator force it to be consumed make a list, and therefore actually pop() list items
        ret.append([a.pop() for b in a if sum(a[-1]) < 1])
        # rotate the array, increase the number of rotations, and recursively call this function on the new array/counter
        ret.append(f(zip(*a[::-1]), l + 1)))
        # we only put both items in a list in order to stay in the one-line lambda format
        # discard the popped items and return the value from the recursive call
        return ret[1]

```

# Answer
> 1 votes
# JavaScript (Node.js), 100 bytes

```
f=(a,i=4,b=a[0])=>b&&i?/[1-9]/.test(b)?f([...b].map((c,j)=>a.map(d=>d.pop())),i-1):f(a.slice(1),i):a

```

Try it online!

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


title: Calculate the inverse of a matrix

text:
# Question
Title: Calculate the inverse of a matrix
Somehow, we don't yet have a challenge for finding the inverse of an arbitrarily-sized square matrix, despite having ones for 3x3 and 4x4, as well as a more complex version.

Your task is, given a square \\$n\times n\\$ non-singular matrix \\$M\\$, output the matrix \\$M^{-1}\\$ that satisfies

$$MM^{-1} = I\_n$$

There are a number of methods and formulae for calculating \\$M^{-1}\\$, but one of the most well known is

$$M^{-1} = \frac1{\det(M)}\text{ adj}(M)$$

where \\$\det\\$ represents the determinant and \\$\newcommand{\adj}{\text{adj}}\adj\\$ the adjugate

Some definitions:

* \\$I\_n\\$: The \\$n\times n\\$ identity matrix i.e. an \\$n\times n\\$ matrix where the leading diagonal consists entirely of \\$1\\$s and the rest \\$0\\$s
* Non-singular: the determinant of \\$M\\$ is guaranteed to be non-zero
* Determinant: a specific number that can be calculated for any given square matrix. Exact methods can be found in the Wikipedia article
* Adjugate: Formally, the transpose of the cofactor matrix of \\$M\\$. Informally, this is a operation on \\$M\\$ which takes determinants of submatrices in a specific way to construct a related matrix. Again, exact details can be found in the linked article.

For sake of simplicity, you may assume:

* The elements of \\$M\\$ will all be integers within the native bounds of your language
* \\$n\\$, nor \\$n^2\\$, will never exceed the maximum value in your language, and will always be greater than or equal to \\$1\\$
* The elements of \\$M^{-1}\\$ will never exceed the maximum value in your language (or minimum for negative values)
* \\$M\\$ will never be singular

No builtins are banned and you may use whatever (valid) method you like for calculating \\$M^{-1}\\$. It is acceptable if your program fails for some inputs due to floating point issues, so long as the underlying algorithm or method works for arbitrary matrices.

This is, of course, entirely optional, but if your answer consists entirely of a builtin, consider including a non-builtin method, simply for the sake of general interest.

Standard rules apply. This means you may input or output in any convenient format, and that standard loopholes are forbidden. The shortest code in bytes wins.

This script will take an input \\$n\\$ and generate an \\$n\times n\\$ matrix with random integers between \\$-10\\$ and \\$10\\$, along with it's inverse. You can use this for test cases.

---

### Worked example

Lets take the \\$3\times3\\$ matrix \\$M\\$ as:

$$M = \left\[\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right\]$$

We'll use the above formula, \\$M^{-1} = \frac{\adj(M)}{\det(M)}\\$ for this example.

First, we'll calculate \\$\det(M)\\$ by expanding along the third column:

$$\begin{align} \det(M) & = \left|\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right| \\ & = 0\left|\begin{matrix} -4 & -7 \\ 5 & 7 \end{matrix}\right| \- 6\left|\begin{matrix} 4 & -3 \\ 5 & 7 \end{matrix}\right| \+ 6\left|\begin{matrix} 4 & -3 \\ -4 & -7 \end{matrix}\right| \\ & = 0 - 6(4\cdot7 - -3\cdot5) + 6(4\cdot-7 - -3\cdot-4) \\ & = -6(28 + 15) + 6(-28 - 12) \\ & = -6\cdot43 + 6\cdot-40 \\ & = -498 \\ \therefore det(M) & = -498 \end{align}$$

We then need to calculate \\$\adj(M)\\$. As \\$\adj(\cdot)\\$ of a matrix is the transpose of the cofactor matrix, this essentially boils down to calculating the cofactor matrix of \\$M\\$, \\$C\_M\\$:

$$\begin{align} \adj(M) & = C\_M^T \\ & = \left\[\begin{matrix} \left|\begin{matrix} -7 & 6 \\ 7 & 6 \end{matrix}\right| & \left|\begin{matrix} -4 & 6 \\ 5 & 6 \end{matrix}\right| & \left|\begin{matrix} -4 & -7 \\ 5 & 7 \end{matrix}\right| \\ \left|\begin{matrix} -3 & 0 \\ 7 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & 0 \\ 5 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & -3 \\ 5 & 7 \end{matrix}\right| \\ \left|\begin{matrix} -3 & 0 \\ -7 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & 0 \\ -4 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & -3 \\ -4 & -7 \end{matrix}\right| \end{matrix}\right\]^T \\ & = \left\[\begin{matrix} -84 & 54 & 7 \\ 18 & 24 & -43 \\ -18 & -24 & -40 \end{matrix}\right\]^T \\ & =\left\[\begin{matrix} -84 & 18 & -18 \\ 54 & 24 & -24 \\ 7 & -43 & -40 \end{matrix}\right\] \end{align}$$

Finally, having calculated both \\$\det(M)\\$ and \\$\adj(M)\\$, we divide each element of \\$\adj(M)\\$ by \\$\det(M)\\$ to compute the final output, \\$M^{-1}\\$:

$$\begin{align} M^{-1} & = \frac{\adj(M)}{\det(M)} \\ & = \left\[\begin{matrix} \frac{-84}{-498} & \frac{ 18}{-498} & \frac{-18}{-498} \\ \frac{ 54}{-498} & \frac{ 24}{-498} & \frac{-24}{-498} \\ \frac{ 7}{-498} & \frac{-43}{-498} & \frac{-40}{-498} \end{matrix}\right\] \\ & = \left\[\begin{matrix} \frac{ 14}{ 83} & \frac{-3}{ 83} & \frac{ 3}{ 83} \\ \frac{ -9}{ 83} & \frac{-4}{ 83} & \frac{ 4}{ 83} \\ \frac{ -7}{498} & \frac{43}{498} & \frac{20}{249} \end{matrix}\right\] \end{align}$$

Alternatively, as decimals, \\$M^{-1}\\$ is

```
[[ 0.1686746987951807,   -0.03614457831325301, 0.03614457831325303],
 [-0.10843373493975902,  -0.04819277108433735, 0.04819277108433734]
 [-0.014056224899598388,  0.08634538152610442, 0.08032128514056225]]

```

# Answer
# Octave, 57 bytes

```
A=input('');V=A'/trace(A*A');for i=1:1e4V=2*V-V*A*V;end
V

```

Try it online!

This is not particularly well golfed, but I wanted to advertise an approach that could be useful for other non-builtin answers.

This uses the Hotelling-Bodewig scheme:

$$ V\_{i+1} = V\_i\left(2I - AV\_i\right)$$

Which iteratively computes the inverse of a non singular matrix. This is guaranteed to converge for \\$\left\lVert I - AV\_0\right\rVert \< 1\\$ (under a suitable matrix norm). Choosing the \\$V\_0\\$ is difficult, but Soleymani, F. shows in "A New Method For Solving Ill-Conditioned Linear Systems" that the inital guess \\$V\_0 = \frac{A^T}{\text{tr}(AA^T)}\\$ will always satisfy this condition, so the system is numerically stable.

What makes this a particularly attractive approach to other potential answers is that we don't require any builtin determinant or inverse functions. The most complex part is just matrix multiplication, since the transpose and trace are trivial to compute.

I have chosen `1e4` iterations here to make the runtime somewhat reasonable, although you could of course push it to `1e9` with no loss of byte count.

---

-10 thanks to xnor for noting we don't need to construct an identity matrix.
> 24 votes

# Answer
# , 5 bytes

```
solve

```

Try it online!

Nothing new here... Basically, the code `solve(A, B)` solves \\$AX = B\\$, but when \\$B\\$ is not given, it is treated as identity matrix, thus giving us the inverse as the result.
> 15 votes

# Answer
# APL (Dyalog Unicode), 1 byteSBCS

Try it online!

The domino primitive is a very interesting APL "built-in". It already featured in another 1-byte answer of my own where it was used to solve a least-squares problem. When applied to a square matrix,  tries to find the matrix inverse of its argument.

Many golfing languages will also have a built-in for this... But mind you, APL is **not** a golfing language, although it is terse enough to be very competitive and, in cases like this, win.
> 14 votes

# Answer
# , ~~72~~ 61 bytes

```
function(A,V=t(A/sum(diag(A%*%t(A))))){for(i in 1:1e4)V=2*V-V%*%A%*%V;V}

```

Try it online!

Porting Sisyphus' answer is not futile at all...and thanks to Sisyphus for -11 bytes.

Observes that \\$Tr(AA^T)=\sum\limits\_{i,j}a\_{ij}^2\\$.

# , 94 bytes

```
function(M)outer(k<-1:dim(M),k,Vectorize(function(j,i)det(M[-i,-j,drop=F])*(-1)^(i+j)))/det(M)

```

Try it online!

Thanks to Robin Ryder for fixing a bug and making this actually work.

Calculates \\$A^{-1}\\$ using the adjugate/determinant method.
> 11 votes

# Answer
# Python 2, 228 bytes

```
from random import*
a=input()
exec"""$:j,J=i,I;J+=[j==i $]
while~-all(I[i]$):shuffle(a)
$:
 j,J=i,I
 $:
	if j-i:I[:]=[y-I[j]*x/J[j]for x,y in zip(J,I)]
$:print[x/I[i]for x in I][len(a):]""".replace("$","for i,I in enumerate(a)")

```

Try it online!

Augment the matrix with the identity matrix, then apply Gauss–Jordan elimination. I don't know if this is the shortest approach, but it's the one I wanted to try golfing down.

I use `while not all(a[i][i]for i in r):shuffle(a)` to move zeros off the diagonal. This loop will definitely terminate, because if there is *no* permutation of the rows of \\$A\\$ that makes the diagonal free of zeros, then \\$\det(A)=0\\$, which we are guaranteed is not the case. This can be seen from the Leibniz formula for \\$\det(A)\\$:

$$\det(A) = \sum\_{\sigma \in S\_n} \text{sgn}(\sigma) \prod\_{i=1}^n a\_{\sigma(i),i}$$

“There is no permutation \\$\sigma\\$ of the rows that makes the diagonal free of zeros” can be equivalently rephrased as “\\$\prod\_{i=1}^n a\_{\sigma(i),i}\\$ is always 0, for all \\$\sigma\\$” which causes this whole formula to be 0.
> 8 votes

# Answer
# APL (Dyalog Unicode), ~~27~~ 23 bytes

-4 bytes thanks to Adám!

This implements the method advertised by Sisyphus.

```
⊢(⊢+⊢-⊢+.×+.×)⍣≡⍉÷,+.×,

```

Try it online!

A function that takes the matrix as the right argument.

`+.×` computes the dot product (sum of element-wise product) of the flattened matrix `,` and the flattened matrix `,`. This is sum of the squared matrix entries, which is equal to \\$tr(AA^T)\\$.
`⍉÷` divides the transposed matrix by the trace.

`(⊢+⊢-⊢+.×+.×)⍣≡` is a function which is applied to the original matrix \\$A\\$ as a left argument () and \\$A^T\div tr(AA^T)\\$ as the right argument (`⍉÷,+.×,`):

`⊢+⊢-⊢+.×+.×` takes the current matrix \\$V\\$ on its right and the input matrix \\$A\\$ on its left and executes one iteration step:
`+.×` is the inner product of `+` and `×`. Given two matrices, this calculates their product. In this case \\$ A \times V \\$.
is the right argument \\$V\\$, `⊢+.×` the product \\$V \times (A \times V)\\$.
`⊢-` subtracts this from the right argument: \\$V-V \times A \times V\\$.
`⊢+` adds this to the right argument: \\$V+V-V \times A \times V\\$.

`⍣≡` applies the function on its left until the result doesn't change. Because of the way equality testing works in Dyalog APL, this actually terminates.
> 8 votes

# Answer
# Julia 1.0, 3 bytes

```
inv

```

Try it online!

Yet another short built-in solution.
> 7 votes

# Answer
# JavaScript (ES6), 169 bytes

This computes \\$M^{-1} = \dfrac{\operatorname{adj}(M)}{\det(M)}\\$

```
M=>M.map((r,y)=>r.map((_,x)=>D(h(M,x).map(r=>h(r,y)))*(x+y&1?-1:1)/D(M)),h=(a,n)=>a.filter(_=>n--),D=M=>+M||M.reduce((s,[v],i)=>s+(i&1?-v:v)*D(h(M,i).map(r=>h(r,0))),0))

```

Try it online!
> 7 votes

# Answer
# , 2 bytes

```
%.

```

Try it online!

Same as APL, but more powerful, as J can produce exact rational matrix when given a matrix of extended integers as input.
> 7 votes

# Answer
# Scala, ~~237~~ 232 bytes

Uses the method from Sisyphus's answer. Go upvote that!

```
m=>{val h=m.indices
Seq.iterate(m.transpose.map(_.map(_/m.flatten.map(x=>x*x).sum)),9999){v=>h.map(i=>h.map{j=>2*v(i)(j)-(h.map(k=>v(i).zip(m.transpose.apply(k))map(t=>t._1*t._2)sum),v.transpose.apply(j)).zipped.map(_*_).sum})}last}

```

Try it online!

`h` is just a range from 0 until n to reuse later (mostly because Scala doesn't have matrix multiplication builtins). The function makes a sequence of 9999 elements and takes the last element. The first element is the transpose of `m` divided by the trace of `m` times its transpose. Subsequent elements are calculated with `2*v-v*m*v`, where `v` was the previous element.

To calculate \\$V\_0\\$ (It turns out the trace of `m` times its transpose is just the sum of squares of all of `m`'s cells):

```
m.transpose.map(            //For every row in m's transpose
  _.map(                    //For every cell in that row
    _ /                     //Divide it by (trace(M * M's transpose))
      m.flatten             //Turn m into a 1D list
        .map(x=>x*x)        //Square each cell
        .sum))              //Add them up

```

To calculate subsequent elements, we use \\$2V - (VA)V\\$, but you have to map over `h` instead of over `v` itself:

```
h.map(i =>                 //For every i in [0, n)
  h.map{j =>               //For every j in [0, n)
    2*v(i)(j) -            //2V at these coordinates minus
    <(v * m * v)[i][j]> }) //v*m*v at these coordinates (see explanation below)

```

To calculate `(v*m)[i]`:

```
h.map(k =>                //k is the index of a row in [0, n)
  v(i).zip(               //Zip column i of v with
    m.transpose.apply(k)  //Row k of m (apply is used for indexing here)
  ) map(t=>t._1*t._2)     //Multiply v(i)(j) with m(k)(i)
  sum                     //Add then up
)

```

And getting the cross product of that with row `j` of `v` uses pretty much the same approach.

---

# Scala, ~~346~~ 342 bytes

Saved 4 bytes thanks to **@corvus\_192**!

```
type M=Seq[Seq[Double]]
def c(m:M)={val I=m.indices;I.map(i=>I.map(j=>m(i)(j)*math.pow(-1,i+j)))}
def d(m:M):(M,Double)=if(m.size<2)m->m(0)(0)else{val I=m.indices
val M=I.map(i=>I.map{j=>d(I.filter(i!=_)map(k=>I.filter(j!=_)map(m(k))))._2})
c(M)->c(m).head.zip(M.head).map(t=>t._1*t._2).sum}
def i(m:M)=d(m)._1.transpose.map(_.map(_/d(m)._2))

```

Try it in Scastie!

As you can see, I'm not very good at math.
> 6 votes

# Answer
# 05AB1E, ~~38~~ ~~22~~ ~~21~~ 20 bytes

```
˜nO/øтF©I2Føδ*O®}·s-

```

Port of *@Sisyphus*' Octave answer, so make sure to upvote him!!
-16 bytes thanks to *@ovs*.

**Try this online.**

**Code explanation:**

```
˜            # Flatten the (implicit) input-matrix to a single list
 n           # Square each value in this list
  O          # Take the sum (this is the trace of M*M')
   /         # Divide each value in the (implicit) input-matrix by this trace
    ø        # Zip/transpose this matrix; swapping rows/columns
тF           # Loop 100 times:
  ©          #  Store the current matrix in variable `®` (without popping)
   I         #  Push the input-matrix
    2F       #  Loop 2 times:
      ø      #   Zip/transpose the top matrix; swapping rows/columns
       δ     #   Apply double-vectorized with the top two matrices:
        *    #    Multiply
         O   #   Sum each inner row
          ®  #   Push the matrix from variable `®` again
     }·      #  After the inner loop: double all values in matrix `®`
       s     #  Swap so the calculated matrix VMV is at the top again
        -    #  Subtract this VMV from the 2V
             # (after the outer loop, the resulting matrix is output implicitly)

```

---

## Original answer (38 bytes) and detailed explanation:

```
εUεX*O]Å\OIøs/тFxs©εUIøεX*O}U®øεX*O}}-

```

**Try it online.**

05AB1E has barely any useful builtins for matrices, not even matrix manipulation. So almost everything has to be done manually..

Since I'm an absolute noob in math, I'm gonna explain everything in full detail to help others like me who want to do this challenge without any builtins, and also to keep this answer self-contained.

**Step 1)** Matrix manipulation of the input-matrix \\$M\\$ with it's transpose: \\$M\times M'\\$:

If we have a matrix \\$A\\$ and \\$B\\$ and want to do matrix-manipulation \\$AB\\$, we take the dot-product of every \\$i^{th}\\$ row of \\$A\\$ and \\$j^{th}\\$ column of B for every coordinate \\$i,j\\$ in the two matrices.

For example, if we use the matrix in the challenge description:

\\$M = \left\[\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right\]\\$

We can for example calculate the values in the top row of the resulting \\$M\times M'\\$ matrix with:

Top-left: \\$4\times4+-3\times-3+0\times0 = 25\\$
Top-center: \\$4\times-4+-3\times-7+0\times6=5\\$
Top-right: \\$4\times5+-3\times7+0\times6 = -1\\$

I've done matrix manipulation in 05AB1E before in this answer of mine, so I've used that code snippet here as well. Since we want to multiply the input-matrix by it's transpose, we actually won't need the transpose builtin here.

```
ε                  # Map over each row of the (implicit) input-matrix
 U                 #  Pop and store the current row in variable `X`
  ε                #  Map over each row of the (implicit) input-matrix again
   X*              #   Multiply the values of the current row by the values at the same
                   #   positions in row `X`
     O             #   And take the sum of this row
]                  # Close both maps

```

Try just this step online.

**Step 2)** Take the trace of this new matrix: \\$(M\times M')^T\\$

The trace of a square matrix is basically the sum of its main diagonal (the values of the top-left to the bottom-right).

```
Å\                 # Take the main diagonal of the matrix of step 1
  O                # And sum the values in this list together

```

Try the first two steps online.

**Step 3)** Divide all values in the transposed matrix by this trace we calculated:

```
I                  # Push the input-matrix
 ø                 # Zip/transpose it; swapping rows/columns
  s                # Swap so the trace we calculated it at the top of the stack
   /               # And divide each value in the transposed matrix by this trace

```

Try the first three steps online.

**Step 4)** Repeat the following steps (5 through 8) enough times for the answer to not change anymore:

Since this program isn't very fast in 05AB1E, I've decided to loop just 100 times, but this can be increased to improve the accuracy of the decimal results (I've verified with *@Sisyphus*' Octave answer that changing the `1e4` to `1e2` still holds the same result for most matrices).

```
тF                 # Loop 100 times:

```

I'm not sure if the values will eventually not change anymore if we loop enough times. If this is the case we could (in theory) save a byte by changing this `тF` to `Δ` (loop until the result no longer changes).

(Let's call the intermediate matrix inside this loop \\$V\\$ for the explanations of the following steps.)

**Step 5)** Double each value in the current matrix: \\$2V\\$:

```
  x                #  Double each value in the current matrix V (without popping)

```

Try the first five steps online, excluding the loop of step 4.

**Step 6)** Do matrix manipulation again for \\$VM\\$ (where \\$M\\$ is the input-matrix):

```
   s               #  Swap to take the non-doubled matrix V at the top again
    ©              #  Store this matrix V in variable `®` (without popping)
     ε             #  Map over each row of matrix V:
      U            #   Pop the current row, and store it in variable `X`
       I           #   Push the input-matrix M
        ø          #   Zip/transpose; swapping rows/columns
         ε         #   Map over each row of this transposed matrix M':
          X*       #    Multiply the values in the current row by row `X`
            O      #    And take the sum

```

Try the first six steps online, excluding the loop of step 4.

**Step 7)** And do matrix manipulation yet again right after: \\$VMV\\$:

```
         }         #   Close the inner map
          U        #   Pop and store this as new `X`
           ®       #   Push the matrix V from variable `®`
            ø      #   Zip/transpose; swapping rows/columns
             ε     #   Map over each row of this transposed matrix V':
              X*   #    Multiply the values in the current row by row `X`
                O  #    And take the sum
     }}            #  Close both the inner and outer maps

```

Try the first seven steps online, excluding the loop of step 4.

**Step 8)** Subtract the values at the same positions of these two matrices from one another: \\$2V-VMV\\$:

```
       -           #  Subtract matrix VMV from 2V

```

Try the first eight steps online, excluding the loop of step 4.

And after the loop is done, the resulting matrix is output implicitly.
> 6 votes

# Answer
# Python 2, 188 bytes

```
lambda a:[[c(a,j,i)/d(a)for j,_ in e(a)]for i,_ in e(a)]
c=lambda a,i,j:(-1)**(i+j)*d([b[:j]+b[j+1:]for I,b in e(a)if i-I])
d=lambda a:a==[]or sum(b[0]*c(a,i,0)for i,b in e(a))
e=enumerate

```

Try it online!

The top lambda computes \\$A^{-1} = \frac{1}{\det(A)}\text{adj}(A)\\$.

`d(a)` computes the determinant and `c(a,i,j)` computes cofactors.
> 6 votes

# Answer
# Wolfram Language (Mathematica), 7 bytes

```
Inverse

```

Try it online!
> 5 votes

# Answer
# Jelly, 3 bytes

```
æ*-

```

Try it online.

**Explanation:**

```
     # Full program taking a single integer-matrix as argument
æ*   #  Matrix exponentiation
  -  #  with -1
     #  (after which the result is output implicitly)

```
> 5 votes

# Answer
# Excel, 29 bytes

```
=MINVERSE(OFFSET(A2,,,A1,A1))

```

Straightforward application of the MINVERSE() function. It's boring but I got excited about Excel having a built-in for something. Input \\$n\\$ in `A1`, the matrix starting in `A2`, and the formula anywhere the spill won't interfere.
> 5 votes

# Answer
# Charcoal, 48 bytes

```
≔Ｅθ∕Ｅθ§λκΣＥＸθ²ΣληＦφＵＭηＥκ⁻⊗μΣＥθ×ΣＥθ×§κς§ρπ§§ηπνＩη

```

Try it online! Link is to verbose version of code. Explanation: Another port of @Sisyphus's answer.

```
≔Ｅθ∕Ｅθ§λκΣＥＸθ²Σλη

```

Transpose the input and divide it by the sum of squares of all the elements. Sadly neither sum nor divide fully vectorise, so I have to divide a row at a time and calculate the sum via a nested loop.

```
Ｆφ

```

Repeat 1000 times, which should be enough for floating-point precision.

```
ＵＭηＥκ⁻⊗μΣＥθ×ΣＥθ×§κς§ρπ§§ηπν

```

Calculate the matrix multiplication and subtraction in-place. Charcoal doesn't have any vector or matrix operations, so we have to loop over the rows and columns manually, but there are a couple of places where we can share variables which saves us a couple of bytes each.

```
Ｉη

```

Output the array. (Note that each element is output on its own line and each row is double-spaced from the previous.)
> 4 votes

# Answer
# Matlab ~~6~~ 3 bytes

```
inv

```

Computes and prints the inverse of a square matrix. Pretty boring in-built solution. Thanks to @Bubbler for the clarification and -3 bytes.
> 4 votes

# Answer
# MATL, 4 bytes

```
-1Y^

```

Try it online!

## Explanation

```
-1Y^
-1   : Push -1 onto the stack
  Y^ : Raise implicit input to -1 power

```
> 3 votes

# Answer
# PARI/GP 8 bytes

```
f(A)=1/A

```

Built-in function; particularly efficient for matrices with integer matrix elements.

Most likely, the method used is similar to the one described in this refererence: H. Haramotu, M. Matsumotu, A p-adic algorithm for computing the inverse of integer matrices, Journal of Computational and Applied Mathematics, Volume 225, Issue 1, 1 March 2009, Pages 320-322.
> 3 votes

# Answer
# SageMath, ~~14~~ ~~13~~ 11 bytes

Saved a byte thanks to FryAmTheEggman!!!
Saved 2 bytes thanks to Sisyphus!!!

```
lambda M:~M

```

Try it online!

Inputs any square `matrix` and returns its inverse.
> 2 votes

# Answer
# Ruby `-rmatrix`, ~~23~~ 19 bytes

```
->a{Matrix[*a].inv}

```

Try it online!

Returns the result as a Ruby matrix object.

-4 bytes from Dingus.
> 2 votes

# Answer
# , 3 bytes

```
inv

```

# k, 1 byte

```
!

```

Does exactly as requested. Input must be a float matrix
> 1 votes

# Answer
# Fortran (GFortran), 350 ~~376~~ bytes

```
real,allocatable,dimension(:,:)::A,B,U;read*,n;allocate(A(n,n));B=A;U=A;read*,((A(i,j),j=1,n),i=1,n)
do i=1,n;do j=1,n;U(i,j)=merge(1,0,i==j);B(i,j)=merge(1.,1/A(i,j),A(i,j)==0);enddo;enddo
do 4 l=1,99;do 4 i=1,n;do 4 j=1,n;s=U(i,j);do k=1,n;m=i;if(k/=m)s=s-A(i,k)*B(k,j);enddo;B(m,j)=s/A(i,m)
4 continue;print'(3(x,f9.6))',((B(i,j),j=1,n),i=1,n)
end

```

Try it Online! ~~376 bytes~~

Adapted from here. Saved 26 bytes using `merge` instead of `if`.
> 1 votes

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


# Question
Title: CGAC2022 Day 1: Let's build a chocolate pyramid!
Following last year's event, we're doing **Code Golf Advent Calendar 2022**!

On each day from today (Dec 1) until Christmas (Dec 25), a Christmas-themed challenge will be posted, just like an Advent calendar. It is a free-for-all and just-have-fun-by-participation event, no leaderboards and no prizes for solving them fast or solving them in the shortest code. More details can be found in the link above.

---

I've got an infinite supply of two kinds of weirdly shaped chocolate:

* White chocolate, a square pyramid of side lengths 1
* Dark chocolate, a regular tetrahedon of side lengths 1

To celebrate the upcoming Christmas, I want to assemble them into a giant chocolate pyramid. When the base of the pyramid is a rectangle of size \\$R \times C\\$, the process to build such a pyramid is as follows:

1. Fill the floor with \\$RC\\$ copies of White chocolate.
2. Fill the gaps between White chocolate with Dark chocolate.
3. Fill the holes between Dark chocolate with White chocolate. Now the top face is a rectangle of size \\$(R-1) \times (C-1)\\$.
4. Repeat 1-3 until the top face has the area of 0.

The diagram below shows the process for \\$2 \times 3\\$. It takes 8 White and 7 Dark chocolate to complete the first floor, and 10 White and 8 Dark for the entire pyramid.

Given the width and height of the base rectangle, how many White and Dark chocolate do I need to form the chocolate pyramid?

You may assume the width and height are positive integers. You may output two numbers in any order.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
(width, height) -> (white, dark)
(2, 3) -> (10, 8)
(10, 10) -> (670, 660)
(10, 1) -> (10, 9)

```

# Answer
> 8 votes
# Vyxal, 14 bytes

```
gʁ$vεƛΠε∑;:›"Ṡ

```

Try it Online!

The main observation here is that the amount of white chocolate \\$w\\$ and dark chocolate \\$d\\$ in a layer of size (a, b) is: $$ w = ab +(a-1)(b-1) = 2ab - a - b + 1\\ d = (a-1)b+(b-1)a = 2ab - a - b $$

In other words, the difference between white chocolate and dark chocolate for a layer is 1

```
 ʁ             # Range from 0 to...
g              # Minimum dimension of input
  $vε          # Subtract each from the input, creating a list of pairs of bases
     ƛ   ;     # Over each base pair [a, b]
      Π        # Product ab
       ε       # Take the absolute difference - [ab - a, ab - b]
        ∑      # Sum
          :›"  # Create an incremented pair for white
             Ṡ # Sum each into the final amounts

```

# Answer
> 7 votes
# Desmos, ~~47~~ ~~46~~ 37 bytes

*-1 byte thanks to emanresu A*

*-9 bytes (!!!) thanks to alephalpha*

```
N=min(h,w)
f(w,h)=Nhw-N(NN+2)/3+[N,0]

```

\\$f(w,h)\\$ takes in the width \\$w\\$ and the height \\$h\\$ and returns a two-element list, with the number of white chocolates in the first element and the number of dark ones in the second element.

Try It On Desmos!

Made my own closed form formula because I figured it would be fun :)

For those who are really curious, here’s some of the scratch work for how I came up with this formula (warning: it’s completely unreadable :P): Scratch work

# Answer
> 4 votes
# PARI/GP, 41 bytes

```
f(r,c)=if(r*c,[t=r*c+r--*c--,t-1]+f(r,c))

```

Attempt This Online!

---

# PARI/GP, 41 bytes

```
f(r,c)=m=min(r,c);[t=1+3*r*c-m^2,t-3]*m/3

```

Attempt This Online!

```
f(r,c)=m=min(r,c);[t=r*c*m+m/3-m^3/3,t-m]

```

Attempt This Online!

Using the closed form formula.

# Answer
> 4 votes
# , ~~42~~ 39 bytes

*Edit: -3 bytes thanks to @Giuseppe.*

```
\(r,c)-c(0,m<-min(r,c))+r*c*m+m/3-m^3/3

```

Attempt This Online!

Port of alephalpha's answer.

# Answer
> 3 votes
# Charcoal, ~~20~~ 19 bytes

```
Ｉ⁺ΣＥ⌊θΣ⁻Π⁻θι⁻θι⟦⌊θ⁰

```

Try it online! Link is to verbose version of code. Takes input as a tuple or list of (rows, columns). Explanation:

```
     θ              Input tuple
    ⌊               Minimum
   Ｅ                Map over implicit range
          θ         Input tuple
         ⁻          Vectorised minus
           ι        Current value
        Π           Take the product
       ⁻            Minus
             θ      Input tuple
            ⁻       Vectorised minus
              ι     Current value
      Σ             Take the sum
  Σ                 Take the sum
 ⁺                  Vectorised add
               ⟦    List of
                 θ  Input tuple
                ⌊   Minimum
                  ⁰ Literal integer `0`
Ｉ                   Cast to string
                    Implicitly print

```

Edit: Saved 1 byte by porting @Ausername's formula. The best closed form formula I could find was 22 bytes, but adapting one of @alephalpha's versions saves 1 byte:

```
Ｉ⁻⁻×Πθ⌊θ÷⁻Ｘ⌊θ³⌊θ³⟦⁰⌊θ

```

Try it online! Link is to verbose version of code. Takes input as a tuple or list of (rows, columns). Explanation:

```
     θ                  Input tuple
    Π                   Product
   ×                    Multiplied by
       θ                Input tuple
      ⌊                 Minimum
  ⁻                     Subtract
            θ           Input tuple
           ⌊            Minimum
          Ｘ             Raised to power
             ³          Literal integer `3`
         ⁻              Subtract
               θ        Input tuple
              ⌊         Minimum
        ÷               (Integer) Divide by
                 ³      Literal integer `3`
 ⁻                      Vectorised subtract
                 ⟦      List of
                  ⁰     Literal integer `0`
                    θ   Input tuple
                   ⌊    Minimum
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 3 votes
# Ruby, ~~41~~ 40 bytes

-1 byte thanks to Sisyphus

Based on alephalpha’s PARI/GP answer.

```
->a{r,c=a.sort
[t=r/3+c*r*r-r**3/3,t-r]}

```

Attempt This Online!

# Answer
> 3 votes
# C (GCC), ~~76~~ ~~72~~ 70 bytes

* -4 bytes thanks to Conor O'Brien
* -2 bytes thanks to Keven Cruijssen

```
#define C(n,c)n(a,b){a=a*b?c*--b+n(a,b):0;}
C(f,a*b+--a)C(g,~-a*b+a--)

```

Attempt This Online!

`f(a,b)` returns the number of black chocolates while `g(a,b)` the number of white chocolates.

# Answer
> 2 votes
# Jelly, 14 bytes

```
_ⱮṂ‘PḤ_SƲ€S;ṂÄ

```

A monadic Link that accepts a list of two integers, the base dimensions, and yields a pair of integers, `[dark, white]`.

**Try it online!**

---

## 16 bytes

 ~~Probably~~  beatable with a constructive method, but I like it.

```
Ṃð‘c3×4+²×IAʋ;⁸Ä

```

A monadic Link that accepts a list of two integers, the base dimensions, and yields a pair of integers, `[dark, white]`.

**Try it online!**

### How?

```
Ṃð‘c3×4+²×IAʋ;⁸Ä - Link: Dimensions
Ṃ                - minimum (Dimensions)
 ð               - start a new dyadic chain - f(M=that, Dimensions)
  ‘              - increment (M)
   c3            - choose three -> (M-1)th triangular pyramidal number
     ×4          - times four (call this Q)
            ʋ    - last four links as a dyad - f(M, Dimensions):
        ²        -   square (M)
          I      -   forward differences (Dimensions) -> [Height-Width]
         ×       -   multiply -> [M*M*(Height-Width)]
           A     -   absolute value -> [M*M*|Height-Width|]
       +         - (Q) add (that) -> [dark piece count]
              ⁸  - chain's left argument -> M
             ;   - (dark piece count) concatenate (M) -> [dark piece count, M]
               Ä - cumulative sums -> [dark piece count, white piece count]

```

# Answer
> 2 votes
# 05AB1E, 13 bytes

```
WÝ¨€-DPαOD>‚O

```

Port of *@emanresuA*'s Vyxal answer, so make sure to upvote him/her as well!

Input as a pair \\$\[width,height\]\\$; output as a pair \\$\[dark,white\]\\$.

Try it online or verify all test cases.

**Explanation:**

```
W             # Get the minimum of the (implicit) input-pair
 Ý            # Pop and push a list in the range [0,min]
  ¨           # Remove the last item to make the range [0,min)
   €-         # Subtract each from the (implicit) input-pair
     D        # Duplicate this list of pairs
      P       # Get the product of each inner pairs
       α      # Get the absolute difference with the values in the pairs
        O     # Sum each inner pair
         D    # Duplicate this list
          >   # Increase each inner value by 1
           ‚  # Pair the two lists together
            O # Sum each inner list
              # (after which this pair is output implicitly as result [dark,white])

```

# Answer
> 2 votes
# Pyth, 20 bytes

```
_-h=SQ
sm+*FQ*F=tMQh

```

Try it online!

Takes (width, height), outputs (white, dark)

### Explanation

```
   =SQ            sort the input, set to Q
_-h               output dark - min(Q)

s                 sum of
 m          hQ    run min(Q) times:
  +                add
   *FQ             product of elements of Q
        =tMQ       decrement each element of Q
      *F           product of elements of Q

```

# Answer
> 1 votes
# Python 3, 83 bytes:

```
f=lambda r,c,w=0,d=0:f(r-1,c-1,w+r*c+(r-1)*(c-1),d+r*(c-1)+c*(r-1))if r*c else(w,d)

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES7), 40 bytes

Uses the closed form formula from alephalpha's answer.

Expects `(w)(h)`.

```
w=>h=>[n=w*h*(w<h?w:w=h)+(w-w**3)/3,n-w]

```

Try it online!

# Answer
> 1 votes
# Python, 50 bytes

```
lambda p,q:(y:=(x:=min(p,q))*(3*p*q+1-x*x)//3,y-x)

```

Attempt This Online!

Same closed formula (@alephalpha's) everybody is using.

# Answer
> 1 votes
# Lil, 59 bytes

```
on f x do
r:min x
t:(r/3)+(r*r*max x)-(r^3)/3
t,t-r
end

```

Try it online!

Same as alephalpha.

# Answer
> 1 votes
# Pip `-p`, 26 bytes

```
Y Ngy*a*b-y*(y*y+2)/3+[y0]

```

Try It Online!

Port of my Desmos answer.

# Answer
> 1 votes
# APL(Dyalog Unicode), 15 bytes SBCS

```
⌊××+3÷⍨1 ¯2-⌊×⌊

```

Try it on APLgolf!

Closed form formula from alephalpha's PARI/GP answer.

# Answer
> 0 votes
# Raku, 49 bytes

```
{my (\r,\c)=.sort;my \t=-r**3/3+r/3+c*r*r;t,-r+t}

```

Try it online!

# Answer
> 0 votes
# Perl 5, 68 + 3 (`-pla` option) = 71 bytes

```
($i,$j)=@F;{$d+=$k=$i*$j*2-$i---$j--;$w+=$k+1;$i*$j&&redo}$_="$w $d"

```

Try it online!

# Answer
> 0 votes
# x86-64 machine code, 26 bytes

```
92 39 F0 73 01 96 6A 03 59 F7 E1 29 F0 F7 E6 F7 E6 01 F0 F7 F1 AB 29 F0 AB C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which two 32-bit integers will be consecutively placed, for the white number and the dark number, in that order; and takes the width and height in ESI and EDX.

In assembly:

```
f:  xchg edx, eax    # Switch one argument into EAX.
    cmp eax, esi     # Compare the two arguments.
    jae s            # Jump if EAX holds the higher value.
    xchg esi, eax    # Otherwise, exchange the values.
s:                   # (Now, EAX holds the higher value (which we will call m)
                     #   and ESI holds the lower value (which we will call n).)
    push 3; pop rcx  # Set ECX to 3.
    mul ecx          # Multiply EAX by ECX (3), producing 3m.
                     # (Also, the high half of the product goes in EDX.)
    sub eax, esi     # Subtract ESI (n) from EAX, producing -n+3m.
    mul esi          # Multiply EAX by ESI (n), producing -n²+3mn.
    mul esi          # Multiply EAX by ESI (n), producing -n³+3mn².
    add eax, esi     # Add ESI (n) to EAX, producing -n³+3mn²+n.
    div ecx          # Divide EDX:EAX by 3, producing (-n³+3mn²+n)/3.
    stosd            # Write that value to the address EDI, advancing the pointer.
    sub eax, esi     # Subtract ESI (n) from EAX, producing (-n³+3mn²-2n)/3.
    stosd            # Write that value to the address EDI, advancing the pointer.
    ret              # Return.

```

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


title: Iterated Dice Rolling

text:
# Question
Title: Iterated Dice Rolling
Given an input `n` where `3 <= n <= 25`, perform the following steps, starting with a single `n`-sided die (faces in the range `[1, n]`, inclusive):

1. Print the result of rolling the current `n`-sided dice in play, in the form `kdn: X` (where `X` is the result and `k` is the number of dice in play).
2. If `X` is greater than or equal to `n/2` times the number of dice in play, add a die. Else, remove a die.
3. If the number of dice in play is equal to `0` or `n`, stop. Else, go to step 1.

Example runs (note that the output in parentheses is for explanation and is not required):

6-sided:

```
1d6: 4 (avg: 3.0, add)
2d6: 6 (avg: 6.0, add)
3d6: 9 (avg: 9.0, add)
4d6: 16 (avg: 12.0, add)
5d6: 13 (avg: 15.0, remove)
4d6: 9 (avg: 12.0, remove)
3d6: 5 (avg: 9.0, remove)
2d6: 7 (avg: 6.0, add)
3d6: 11 (avg: 9.0, add)
4d6: 14 (avg: 12.0, add)
5d6: 17 (avg: 15.0, add)

```

9-sided:

```
1d9: 7 (avg: 4.5, add)
2d9: 14 (avg: 9.0, add)
3d9: 18 (avg: 13.5, add)
4d9: 18 (avg: 18.0, add)
5d9: 28 (avg: 22.5, add)
6d9: 26 (avg: 27.0, remove)
5d9: 28 (avg: 22.5, add)
6d9: 34 (avg: 27.0, add)
7d9: 33 (avg: 31.5, add)
8d9: 30 (avg: 36.0, remove)
7d9: 29 (avg: 31.5, remove)
6d9: 35 (avg: 27.0, add)
7d9: 32 (avg: 31.5, add)
8d9: 42 (avg: 36.0, add)

```

## Rules

* Outputs must be exactly in the format `kdn: X`, with newlines separating each roll
* You must actually simulate rolling multiple dice; simply returning a random integer in the range `[1, n]` (inclusive) multiplied by the number of dice currently in play is not allowed, as that does not accurately simulate rolling multiple dice.
* Standard loopholes are forbidden
* This is , so the shortest answer in bytes wins

# Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 65904; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 3 votes
# Pyth, 37 bytes

```
J1W%JQs[J\dQ\:dKsmhOQJ)=J+WgK*JcQ2tJ2

```

Try it online.

# Answer
> 3 votes
## Mathematica, ~~95~~ ~~89~~ 80 characters

```
For[k=1,0<k<#,If[Print[k,d,#,": ",x=Tr[{1,#}~RandomInteger~k]];x<k/2#,k--,k++]]&

```

**Ungolfed**

```
For[
  k = 1,
  0 < k < #,
  If[
    Print[k, d, #, ": ", x = Tr[{1, #}~RandomInteger~k]];
    x < k/2 #,
    k--,
    k++
  ]
] &

```

# Answer
> 3 votes
# PHP, ~~164~~ ~~121~~ ~~112~~ ~~113~~ 109 bytes

Final version, I promise. Improved using Titus' suggestion:

```
function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x: $r\n";$y+=$r/$y>$x/2?:-1;$y<$x&&$y?d($x,$y):0;}

```

---

EDIT: Added an extra byte for formatting. Forgot there's an IF in there that, thanks to dropping the "add/sub" text, could have been a ternary operator:

```
function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x: $r\n";$r/$y>$x/2?$y++:$y--;if($y<$x&&$y)d($x,$y);}

```

Output now looks like:

```
1d6: 5
2d6: 11
3d6: 8
2d6: 11
3d6: 7
2d6: 4
1d6: 5

```

---

EDIT: Thanks to @Manatwork, saved me a lot! New and imrpoved version:

```
function d($x,$y){for($i=$y;$i--;)$r+=rand(1,$x);echo$y."d$x=$r\n";if($r/$y>$x/2)$y++;else$y--;if($y<$x&&$y){d($x,$y);}}

```

---

Previous entry:

```
function d($x,$y){for($i=0;$i<$y;$i++)($r+=rand(1,$x));$s=$y."d$x=$r, ";if($r/$y>$x/2){$y++;$s.="add";}else{$y--;$s.="sub";}echo $s."\n";if($y<$x&&$y>0){d($x,$y);}}`

```

Rolls separate dies, outputs this:

```
1d6=6, add
2d6=7, add
3d6=11, add
4d6=14, add
5d6=15, sub
4d6=15, add
5d6=18, add

```

And it's called thusly: `d(6, 1);`

Is displaying the `Add` and `Sub` suffix mandatory? This is unclear from your question.

# Answer
> 2 votes
## JavaScript (ES6), 97 ~~102~~ ~~106~~ ~~112~~ bytes

Thanks @user81655 and @Jupotter for saving me a few bytes.

```
f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=k;i--;)x+=Math.random()*n|0}

// 102 bytes:
f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=0;++i<=k;)x+=1+Math.random()*n|0}

// Previous attempt, 112 bytes
f=n=>{k=1;while(k&&k!=n){for(x=i=0;i++<=k;)x+=1+~~(Math.random()*n);console.log(k+`d${n}: `+x);k+=x<k*n/2?-1:1}}

```

### Demo

This only works in ES6 compliant browsers (at the moment that includes Firefox and Edge, possibly with Chrome and Opera with experimental JavaScript features enabled):

```
f=n=>{for(k=1;k%n;console.log(k+`d${n}: `+x),k+=x<k*n/2?-1:1)for(x=i=k;i--;)x+=Math.random()*n|0}

// Snippet stuff
console.log = x => {
  document.getElementById('O').innerHTML += x + `<br>`;
}

document.getElementById('F').addEventListener('submit', e => {
  document.getElementById('O').innerHTML = ``
  f(document.getElementById('I').valueAsNumber)
})
```

```
<form id=F action=# method=get>
  <label>
    Number of faces:
    <input type=number min=3 max=25 value=9 required id=I>
  </label>
  <button>Play</button>

  <div>
    <output id=O></output>
  </div>
</form>
```

# Answer
> 2 votes
# Python 3, 125

Saved 3 bytes thanks to DSM.

```
def x(d):
 import random;c=1
 while 0<c<d:r=sum(map(random.randint,[1]*c,[d]*c));print('%id%i: %i'%(c,d,r));c+=2*(r>=d*c/2)-1

```

Pretty simple, rolls a bunch of dice and checks the average. Nothing too fancy here yet.
It needs to be called with an int. So, `x(6)` will produce something like this:

```
1d6: 5
2d6: 10
3d6: 8
2d6: 7
3d6: 11
4d6: 8
3d6: 13
4d6: 19
5d6: 13
4d6: 15
5d6: 22

```

.

# Answer
> 1 votes
## CoffeeScript, ~~106~~ 99 bytes

```
f=(n,k=1)->(x=k;x+=Math.random()*n|0for[k..0];console.log k+"d#{n}: "+x;k+=x<k*n/2&&-1||1)while k%n

# Previous attempt, 106 bytes
f=(n,k=1)->(x=i=0;x+=1+Math.random()*n//1while++i<=k;console.log k+"d#{n}: "+x;k+=x<k*n/2&&-1||1)while k%n

```

### Ungolfed

```
f = (n, k = 1) ->
 (x = k
 x += 1 + Math.random() * n | 0 for [k..0]
 console.log k + "d#{n}: " + x
 k += x < k * n / 2 && -1 || 1
 ) while k % n

```

# Answer
> 1 votes
# Ruby, ~~93~~ ~~90~~ 82 characters

```
->n{d=s=2
puts"#{d}d#{n}: #{s=eval'+rand(n)+1'*d}"while(d+=s<d*n/2.0?-1:1)>0&&d<n}

```

Sample run:

```
2.1.5 :001 > -->n{d=s=2;puts"#{d}d#{n}: #{s=eval'+rand(n)+1'*d}"while(d+=s<d*n/2.0?-1:1)>0&&d<n}[6]
1d6: 5
2d6: 10
3d6: 6
2d6: 5
1d6: 5
2d6: 8
3d6: 15
4d6: 18
5d6: 22

```

# Answer
> 1 votes
# CJam, 45 bytes

```
ri:M;{X__{Mmr+}*[X'dM':S5$N]o_+XM*<_+(-:XM%}g

```

Try it online.

Implements the spec pretty literally (including the mathematically incorrect "mean roll" formula). As expected, porting the original GolfScript program below to CJam saved a bunch of bytes due to shorter built-in command names (`mr`, `o` and `g` instead of `rand`, `puts` and `do`).

# GolfScript, 51 bytes

```
~:&;{1..{&rand+}*[1"d"&": "4$]puts.+1&*<.+(-:1&%}do

```

Here's my original GolfScript entry. Notable golfing tricks include using the number `1` as a conveniently pre-initialized variable to store the current number of dice to to be rolled. (The CJam version instead uses `X`, which CJam initializes to the value 1.)

---

**Ps.** Seeing the title, I originally wanted to answer this in AnyDice. But it turns out to be a *horrible* choice for this challenge, and I don't think it's even technically possible to use it to implement this spec as given.

The problem is that AnyDice is a domain-specific language for writing *deterministic* programs to calculate dice rolling statistics. While inspecting the possible outcomes of a roll and doing conditional rolls based on them *is* possible via recursion, there's no way to generate any actual randomness. So while you could simulate this sequence of dice rolls in AnyDice, all you can get as output is statistics on things like, say, the number of rolls until the process ends, or the distribution of results at a given step.

All that said, here's the closest I could get in AnyDice:

```
N: 6
K: 1
function: clip X:n { result: X * (X < N) }
function: adjust X:n { result: [clip X + ((XdN)*2 >= X*N)*2-1] * (X > 0) }
loop I over {1..20} {
  output K named "dice in roll [I]"
  output KdN named "outcome of roll [I]"
  K: [adjust K]
}

```

This isn't particularly golfed code, since that seemed like an exercise in futility. Standard brace language golfing tricks, like shortening function names and eliminating unnecessary whitespace, should exhaust most of the golfing potential anyway.

The key trick used here is that, when you call a function expecting a number (as indicated by the `:n` in the function definition) in AnyDice, and pass it a die (i.e. a probability distribution) instead, AnyDice automatically evaluates the function for *all possible values* of the die, and combines the results into a new die.

Here's a screenshot of the output (in bar chart format) for the first three rolls:

(Note that the "0" column in each graph indicates the probability that the iteration stopped, due to the number of dice hitting *either* 0 or N, before the current roll. This happens to be a convenient way to represent the stopping condition, since of course rolling 0dN always yields 0.)

# Answer
> 1 votes
# R, 103 Bytes

A fairly straight forward implementation. Dice rolls are done by `sum(sample(n,i))`.

```
i=1;n=scan();while(i&i<=n){cat(i,'d',n,': ',s<-sum(sample(n,i)),'\n',sep='');i=ifelse(s<i*n/2,i-1,i+1)}

```

Test run

```
> i=1;n=scan();while(i&i<=n){cat(i,'d',n,': ',s<-sum(sample(n,i)),'\n',sep='');i=ifelse(s<i*n/2,i-1,i+1)}
1: 9
2:
Read 1 item
1d9: 9
2d9: 14
3d9: 10
2d9: 14
3d9: 9
2d9: 9
3d9: 12
2d9: 7
1d9: 9
2d9: 11
3d9: 17
4d9: 18
5d9: 25
6d9: 29
7d9: 33
8d9: 43
9d9: 45
>

```

# Answer
> 1 votes
# Julia, 77 bytes

```
n->(N=1;while 0<N<n k=sum(rand(1:n,N));print(N,"d$n: $k
");N+=1-2(2k<N*n)end)

```

Most of this should be self-explanatory - an actual newline is being used in the `print` string rather than using `println` to save a byte. `rand(1:n,N)` produces `N` random integers between 1 and `n`.

# Answer
> 0 votes
## QBIC, 83 bytes

```
:c=a{e=0[1,q|e=e+_rq,a|]?!q$+@d|!+a$+@:|+!e$~e<c/2|q=q-1\q=q+1]c=q*a~q=a|_X]~q=0|_X

```

Explanation:

```
q                    Tracks the number of dice (is implicitly 1 at the start)
:                    Takes input from a CMD line parameter
[1,q|e=e+_rq,a|]     Rolls the dice separately
?!q$+@d|!+a$+@:|+!e$ Prints the roll result (requires an unfortunate amount of casting...)
~e<c/2|q=q-1\q=q+1]  Checks whether to increase or decrease
~q=a|_X]~q=0|_X      Tests the amount of dice and quits on either boundary.

```

# Answer
> 0 votes
## PHP, 104 bytes

```
for($n=$argv[$k=1];$k&&$k<$n;print$k."d$n: $x\n",$k-=$x<$n*$k/2?:-1)for($x=$i=0;$i++<$k;)$x+=rand(1,$n);

```

Run with `php -r '<code>' <N>`

**breakdown**

```
for($n=$argv[$k=1];     // import input, init number of dice
    $k&&$k<$n;          // while 0<$k<$n
    print$k."d$n: $x\n",    // 2. print results
    $k-=$x<$n*$k/2?:-1      // 3. remove or add a die
)
    for($x=$i=0;$i++<$k;)   // 1. roll dice separately
        $x+=rand(1,$n);         // sum up results

```

# Answer
> 0 votes
## Python 3, 131 bytes

```
def f(n):
    import random;k=1
    while 0<k<n:
        r=sum([random.randint(1,n)for _ in range(k)]);print(f'{k}d{n}: {r}');k+=2*(r>=k*n/2)-1

```

Try it online!

Explanation:

```
def f(n): # function header, doesn't need to use int(input())
    import random;k=1 # initialize, can't use import* to save bytes
    while 0<k<n: # while k is in between 0 and n:
        r=sum([random.randint(1,n)for _ in range(k)]); # roll k dice and add them up
                                                      print(f'{k}d{n}: {r}'); # print to console, concatenation would take up even more bytes
                                                                             k+=2*(r>=k*n/2)-1 # add dice if r is >= to k*n/2, else remove dice

```

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


title: Parse WebSocket frames

text:
# Question
Title: Parse WebSocket frames
According to MDN, every WebSocket message is sent as one or more *frames*. Your job is to extract the payload given a (masked) client-to-server text frame. The steps to extract the payload is as follows:

* ignore byte 1; read byte 2
    + if it is 254, skip the next 2 bytes
    + if it is 255, skip the next 8 bytes,
    + otherwise, continue
* interpret the next 4 bytes as an XOR-cipher key
* decrypt the final bytes using the (repeating) key and interpret it as a UTF-8 encoded string

For reference, here is an ungolfed solution:

```
#!/usr/bin/env python3
frame = open(0, 'rb').read()

pos = 2
if frame[1] == 254:
    pos += 2 # skip 2 bytes
if frame[1] == 255:
    pos += 8 # skip 8 bytes

# read the key (4 bytes)
key = frame[pos:][:4]
pos += 4

# decode the payload
payload = bytes(x ^ key[i % 4] for i, x in enumerate(frame[pos:]))

# output
print(payload.decode("utf-8"))

```

## Test Cases

| frame (octets are represented in hex) | payload |
| --- | --- |
| `81 83 3D 54 23 06 70 10 6D` | `MDN` |
| `81 85 3D 54 23 06 55 31 4F 6A 52` | `hello` |
| `81 FE 01 BD 3D 54 23 06 71 3B 51 63 50 74 4A 76 4E 21 4E 26 59 3B 4F 69 4F 74 50 6F 49 74 42 6B 58 20 0F 26 5E 3B 4D 75 58 37 57 63 49 21 51 26 5C 30 4A 76 54 27 40 6F 53 33 03 63 51 3D 57 2A 1D 27 46 62 1D 30 4C 26 58 3D 56 75 50 3B 47 26 49 31 4E 76 52 26 03 6F 53 37 4A 62 54 30 56 68 49 74 56 72 1D 38 42 64 52 26 46 26 58 20 03 62 52 38 4C 74 58 74 4E 67 5A 3A 42 26 5C 38 4A 77 48 35 0D 26 68 20 03 63 53 3D 4E 26 5C 30 03 6B 54 3A 4A 6B 1D 22 46 68 54 35 4E 2A 1D 25 56 6F 4E 74 4D 69 4E 20 51 73 59 74 46 7E 58 26 40 6F 49 35 57 6F 52 3A 03 73 51 38 42 6B 5E 3B 03 6A 5C 36 4C 74 54 27 03 68 54 27 4A 26 48 20 03 67 51 3D 52 73 54 24 03 63 45 74 46 67 1D 37 4C 6B 50 3B 47 69 1D 37 4C 68 4E 31 52 73 5C 20 0D 26 79 21 4A 75 1D 35 56 72 58 74 4A 74 48 26 46 26 59 3B 4F 69 4F 74 4A 68 1D 26 46 76 4F 31 4B 63 53 30 46 74 54 20 03 6F 53 74 55 69 51 21 53 72 5C 20 46 26 4B 31 4F 6F 49 74 46 75 4E 31 03 65 54 38 4F 73 50 74 47 69 51 3B 51 63 1D 31 56 26 5B 21 44 6F 5C 20 03 68 48 38 4F 67 1D 24 42 74 54 35 57 73 4F 7A 03 43 45 37 46 76 49 31 56 74 1D 27 4A 68 49 74 4C 65 5E 35 46 65 5C 20 03 65 48 24 4A 62 5C 20 42 72 1D 3A 4C 68 1D 24 51 69 54 30 46 68 49 78 03 75 48 3A 57 26 54 3A 03 65 48 38 53 67 1D 25 56 6F 1D 3B 45 60 54 37 4A 67 1D 30 46 75 58 26 56 68 49 74 4E 69 51 38 4A 72 1D 35 4D 6F 50 74 4A 62 1D 31 50 72 1D 38 42 64 52 26 56 6B 13` | `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.` |

Standard loopholes are forbidden. Shortest code wins.

# Answer
> 12 votes
# JavaScript (Node.js), 60 bytes

```
a=>a.slice(K=[8,14][a[1]^255]^6).map((n,i)=>n^a[K-4+i%4])+''

```

Try it online!

Input a `Buffer`, output string.

Or 83 bytes in browser, which accept `Uint8Array` as input.

# Answer
> 4 votes
# Python,  ~~101~~  83 bytes (@sheared)

thanks to @tsh for golfing the decryption part and the neat dict work!

```
def n(f):f=f[(*[2]*254,4,10)[f[1]]:];return[x^m for x,m in zip(f[4:],f[:4]*len(f))]

```

Attempt This Online!

# Answer
> 4 votes
# , ~~44~~ ~~42~~ 35 bytes

*-~~2~~ 9 bytes thanks to Bubbler!*

```
4(}.]u:@XOR#$4$])}.}.~3^1-254*@-1&{

```

Try it online!

Expects a list of numeric bytes as input.

## Explanation

```
4(}.]u:@XOR#$4$])}.}.~3^1-254*@-1&{
                             *@-       sign of difference between
                          254          254
                                1&{    and the second byte
                      3^1-             transform to the correct start byte - 1
                   }.~                 chop off that many bytes from
                 }.                    the head of the input
 (  ------------)                      monadic forks
             4$]                       select the key
           #$                          repeat that to the length of entire message
    ]   XOR                            bitwise xor with the entire message
     u:@                               convert to characters
4 {.                                   remove xor'd key

```

# Answer
> 3 votes
# Raku, ~~64~~ 60 bytes

```
{Buf(.[^4] «+^«.[4..*]).decode}o{.[(2 max.[1]*6-1520)..*]}

```

Try it online!

(I discovered that I could shave off four bytes by calling `Buf` like a function to create a new buffer object, but the increasingly ancient version of Perl 6/Raku on TIO doesn't allow this syntax, so the link is to a previous version of my code that uses `.new`.)

This is two anonymous functions, composed together using the `o` operator.

The right brace-delimited expression is the first function to be applied, to an input list of integers, assumed to be in the range 0-255. It returns the tail of that list, starting with the xor key at the appropriate index given by the byte at index 1, `.[1]`. `.[1] * 6 - 1520` gives 10 if 255 is at that index, 4 if 254 is at that index, and some number less than zero for any other byte. `2 max` makes that number 2 if it's less than 2, giving the correct index for all cases.

The left brace-delimited function takes that key-plus-payload list of bytes and formats them into the output string. `Buf(...).decode` takes the list of bytes as the argument to construct a `Buf` object and decodes the utf-8 bytes into a regular string. The argument to `Buf` is `.[^4] «+^« .[4..*]`. `.[^4]` is the first four bytes (the xor key), and `.[4..*]` is rest of the bytes (the payload). `+^` is the bitwise-xor operator, and the guillemets that surround it make it a "hyperoperator" with very useful semantics. The elements of both lists are xor-ed in sequence, and since the guillemets are pointing leftwards at the list of key bytes, those bytes are cyclically re-read as many times as needed to match the number of payload bytes. An equivalent construction would be to reverse both the order of the lists and the direction of the guillemets: `.[4..*] »+^» .[^4]`.

# Answer
> 3 votes
# Java 19, 214 bytes

-45, see @Kevin Cruijseen's comments. Thanks!

```
interface A{static void main(String[]a){var f=java.util.HexFormat.of().parseHex(a[0]);int l=f.length,g=f[1]&255,p=g>254?10:g>253?4:2,x=p+4,i=x;while(i<l)f[i]^=f[p+(i++-x)%4];System.out.print(new String(f,x,l-x));}}

```

---

## Java 19, 259 bytes

-1 for space between `String[]` and `a`. Thanks!

```
interface A{static void main(String[]a){var f=java.util.HexFormat.of().parseHex(a[0]);var p=2;if((f[p]&0xff)==254)p+=2;if((f[p]&0xff)==255)p+=8;var x=p+4;for(var i=x;i<f.length;i++)f[i]=(byte)(f[i]^f[p+(i-x)%4]);System.out.print(new String(f,x,f.length-x));}}

```

## Java 19, 260 bytes

```
interface A{static void main(String[] a){var f=java.util.HexFormat.of().parseHex(a[0]);var p=2;if((f[p]&0xff)==254)p+=2;if((f[p]&0xff)==255)p+=8;var x=p+4;for(var i=x;i<f.length;i++)f[i]=(byte)(f[i]^f[p+(i-x)%4]);System.out.print(new String(f,x,f.length-x));}}

```

# Answer
> 1 votes
# C (GCC), 120 bytes

```
#define g getchar()
x[4];i;n;y;main(){g;for((y=g)>253&&(n=y-255?2:8);n+4;)x[n--&3]=g;for(;(n=g)+1;)putchar(n^x[i--&3]);}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, ~~22~~ 21 (or 20?) bytes

```
¦¬₅<.S>3sm.$D4£Þ^4.$ç

```

Input as a list of integers; output as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
¦           # Remove the first value of the (implicit) input
 ¬          # Push its new first value (without popping the headless list)
  ₅<        # Push 254 (255 decreased by 1)
    .S      # Compare:                  -1 if <254; 0 if ==254; 1 if >254
      >     # Increase it by 1:          0 if <254; 1 if ==254; 2 if >254
       3sm  # Take 3 to the power that:  1 if <254; 3 if ==254; 9 if >254
.$          # Remove that many leading items from the headless list
  D         # Duplicate the remaining list
   4£       # Pop the copy, leave just its first 4 values
     Þ      # Cycle this list indefinitely
      ^     # Bitwise-XOR the values at the same positions in the lists together
            # (ignoring trailing items of the infinite list)
       4.$  # Remove the four leading 0s †
ç           # Convert every integer to a character with that codepoint
            # (after which this list of characters is output implicitly)

```

`4.$` could be golfed to  (trim all leading 0s), if the encrypted text is guaranteed to never start with a leading ␀-byte.

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


title: Double-duty quine: quine!dlroW ,olleH

text:
# Question
Title: Double-duty quine: quine!dlroW ,olleH
Write a program that will output its own source code when run, and nothing else. Seems easy, right?

The catch is that when the source code is reversed, your program must output "Hello, World!" exactly, without the quotes.

This is code-golf, so lowest byte count wins.

**Edit**: Your quine must be a proper quine.

# Answer
> 9 votes
# Y, 19 bytes

```
Upxp"!dlroW ,olleH"

```

`U` captures a string with `U` at the beginning until the next `U` is met, in this case, the source code. `p` prints the item, and `x` is a termination link. When reversed, this looks like:

```
"Hello, World!"pxpU

```

This captures the string and prints it with `p`, again terminating the program with `x`.

Try it here!

# Answer
> 22 votes
# JavaScript (ES6), ~~42~~ 38 bytes

```
f=_=>/\//g&&"f="+f||"!dlroW ,olleH">=_

```

## Reversed

```
_=>"Hello, World!"||f+"=f"&&g//\/>=_=f

```

## Explanation

When reversed, it becomes an anonymous function that returns the string `Hello, World!`.

The regex `/\//g` becomes a comment when it is reversed, which allows the syntactically invalid `>=_=f` to be commented out in the reversed code.

# Answer
> 7 votes
# JavaScript (ES6), 71 bytes

```
trela=a=>alert("trela="+trela+"\ntrela\n``")//
`!dlroW ,olleH`
trela
``

```

### How it Works:

Line 1 defines function `trela` that when run outputs the program's source code. Line 2 is an unassigned string, does nothing. Lines 3 and 4 call `trela` abusing the template string syntax.

## Reversed:

```
``
alert
`Hello, World!`
//)"``n\alertn\"+alert+"=alert"(trela>=a=alert

```

### How it Works:

Line 1 is an unassigned string, does nothing. Lines 2 and 3 abuse the template string syntax to print `Hello, World!`. Line 4 is a comment.

# Answer
> 4 votes
# GolfScript, 33 bytes

### Forwards

```
{`".;1$~]"}"!dlroW ,olleH".;1$~]

```

Try it online!

### Backwards

```

]~$1;."Hello, World!"}"]~$1;."`{

```

Try it online!

# Answer
> 4 votes
# GolfScript, ~~29~~ 28 bytes

```
"`'.~]'#\"!dlroW ,olleH".~]

```

It has one trailing newline. Try it here.

Reversed:

```

]~."Hello, World!"\#']~.'`"

```

Try it here.

# Answer
> 2 votes
# RETURN, 94 bytes

```
"34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!'"34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!'

```

Reversed:

```
'!'d'l'r'o'w' ','o'l'l'e'H' %,,,,,,,,,,,,,¤¤43"'!'d'l'r'o'w' ','o'l'l'e'H' %,,,,,,,,,,,,,¤¤43"

```

`Try it here.`

Outputs to STDOUT. Until I find a better quine framework, this will have to do for now.

# Explanation

```
"34¤¤,,,,,,,,,,,,,% 'H'e'l'l'o',' 'w'o'r'l'd'!'"

```

This contains the quine string. In reverse, this is pushed to the stack but not outputted.

```
34¤¤,,,,,,,,,,,,,

```

This pushes a quote char to the stack and outputs the result twice until there is nothing left to output. In reverse, this will print the charcodes already on the stack.

```
% 'H'e'l'l'o',' 'w'o'r'l'd'!'

```

This one pops the top stack item (in reverse, this would pop a space char) and pushes a series of charcodes to the stack (in reverse, these charcodes would later be printed by the series of `,`'s).

# Answer
> 2 votes
# Fission 2, 42 bytes

Shameless adaptation of a excellent quine by @MartinBüttner in this answer

```
'!+O!'!d'!l'!r'!o'!W'! '!,'!o'!!l'!e'!H'R"

```

Try it online

And reversed

```
"R'H!'e!'l!!'o!',!' !'W!'o!'r!'l!'d!'!O+!'

```

Try it online

In the quine version the atom starts at the `R` heading right. The `"`starts print mode which wraps to the next `"` (itself). This prints everything out except the `"`. `'!+` set the atom to char `"`. `O` prints it out and destroys the atom ending the program.

The reversed version starts at the `R` again and for each character in `Hello, World` set the atom and prints `!` it out without destroying the atom. For the final character `!` the print `O` destroys the atom.

# Answer
> 1 votes
# Javascript ES6, 55 bytes

```
$=_=>`$=${$};$()//"!dlroW ,olleH"`;$()//"!dlroW ,olleH"

```

Quite simple, really.

# Answer
> 1 votes
# Python 2, 60 bytes / Python 3.8 (pre-release), 64 bytes

## Python 2: (60 bytes)

* Normal :

```
a="print'a=%r;exec a#\\42'%a#'!dlroW ,olleH'tnirp;";exec a#"

```
* Reversed:

```
"#a cexe;";print'Hello, World!'#a%'24\\#a cexe;r%=a'tnirp"=a

```

Try it online!

## Python 3: (64 bytes)

* Normal:

```
exec(a:="print('exec(a:=%r)#\\42'%a)#)'!dlroW ,olleH'(tnirp;")#"

```
* Reversed:

```
"#)";print('Hello, World!')#)a%'24\\#)r%=:a(cexe'(tnirp"=:a(cexe

```

Try it online!

## Explanation :

* I used a modification of the quine `a="print'a=%r;exec a'%a";exec a` adding some comments `#` to isolate the "hello world" part.
* I also used `\\42` to get the char `"` without breaking my strings or having some slashes `\` at the printing

#

* Thanks to the previous comments and a few well placed quotes, the reversed program is very straight forward

# Answer
> 0 votes
# Python 2, 131 bytes

### Forward:

```
print(lambda x:x+repr(x)+")#'!dlroW ,olleH' tnirp")('print(lambda x:x+repr(x)+")#\'!dlroW ,olleH\' tnirp")(')#'!dlroW ,olleH' tnirp

```

### Reverse:

```
print 'Hello, World!'#)'()"print '\Hello, World!'\#)"+)x(rper+x:x adbmal(tnirp'()"print 'Hello, World!'#)"+)x(rper+x:x adbmal(tnirp

```

The first half is a one-line quine, followed by a `#` to form a comment separating the first half from the simpler second half.

# Answer
> 0 votes
# C, 108 bytes

```
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}//};)"!dlroW ,olleH"(stup{)(niam

```

# Answer
> 0 votes
# Python 2, 70 bytes

```
_='_=%r;print _%%_#"dlroW ,olleH"tnirp';print _%_#"!dlroW ,olleH"tnirp

```

# Answer
> 0 votes
# \>\<\> (Fish), 25 bytes

```
"r00g>o<o>'Hello, World!'

```

Try it

## Reversed

```
'!dlroW ,olleH'>o<o>g00r"

```

Try it

---
Tags: code-golf, quine, source-layout, hello-world
---