title: 1-up your average quine

text:
# Question
Title: 1-up your average quine
A *1-up quine* is a program which is very similar to a quine. The one major difference is that instead of printing itself once, when **n** copies of the program are concatenated, the result prints the original program **n+1** times.

## Example

If your program is `Abc123`:

```
Abc123  ->  Abc123Abc123
Abc123Abc123  ->  Abc123Abc123Abc123
Abc123Abc123Abc123  -> Abc123Abc123Abc123Abc123

```

# Challenge

Your challenge is to create the shortest valid 1-up quine in any language. The usual quine rules apply, so you may not:

* Submit the empty program.
* Directly or indirectly read1 the source code.
* Use quining built-ins.

This is code-golf, so **shortest code in bytes wins.**

1This does not include using a hard-coded string or code block as part of your program.

# Answer
## GolfScript, 12 bytes

```
{`'.~'+:n}.~

```

Try it online!

### Explanation

This combines ideas from the standard GolfScript quine:

```
{'.~'}.~

```

And my recently discovered quine:

```
":n`":n`

```

The main idea is again to use `n` which is printed implicitly at the end of the program in order to get the additional copy of the quine. Since assigning the variable doesn't change anything when it's done again in subsequent copies, this will only add one copy. Here's a breakdown of the code:

```
{        # Standard quine framework. This pushes the block, duplicates it and runs the
         # second copy, such that it can process the first copy to create a quine.
  `      # Convert the block to its string representation.
  '.~'+  # Append the string '.~' to make a complete quine. This is simply left on the
         # stack to be printed at the end.
  :n     # Store the string in n such that one more copy is printed at the end.
}.~

```
> 13 votes

# Answer
# GolfScript, 12 bytes

```
{: ".~"][}.~

```

Try it online!

### How the source code works

```
{: ".~"][}.~

{        }    Define and push a code block.
          .~  Push a copy and execute it.
 :            Save the code block in the space character.
              Every subsequent space will now execute the code block.
   ".~"       Push that string.
       ]      Wrap everything up to the last [ in an array.
        [     Set a new array marker.

```

If the above source code is executed once, the stack will end up as

```
["" {: ".~"]} ".~"]

```

where the empty string at the beginning corresponds to the initial state of the stack (empty input).

Two copies of the source code would leave a final state of

```
["" {: ".~"]} ".~"] [{: ".~"]} ".~"]

```

three copies a final state of

```
["" {: ".~"]} ".~"] [{: ".~"]} ".~"] [{: ".~"]} ".~"]

```

and so on.

### What happens next

After executing the source code, the interpreter does the following.

1. It wraps the entire stack in an array, and pushes that array on the stack.

For two copies of the source code, the stack now contains

```
["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [["" {: ".~"][} ".~"] [{: ".~"][} ".~"]]

```
2. It executed `puts` with the intention of printing the wrapped stack, followed by a linefeed.

`puts` is defined as `{print n print}`, so it does the following.

1. `print` prints the wrapped up copy of the stack without inspecting it (i.e., without converting it to its string representation). This sends

    ```
    {: ".~"][}.~{: ".~"][}.~

    ```

    (the source code) to STDOUT and pops the stack copy from the top of the stack.

    The stack now contains

    ```
    ["" {: ".~"][} ".~"] [{: ".~"][} ".~"]

    ```
    2. executes the code block we defined previously.

    `:` begins by saving `[{: ".~"][} ".~"]` in the space character, then `".~"` pushes itself, `]` wraps the `".~"` in an array, and `[` sets a new array marker.
    3. `n` pushes a string consisting of a single linefeed.

    The stack now contains

    ```
    ["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n"

    ```
    4. is executed once more. However, it was redefined when we called it for the first time and now contains an array, not a code block.

    In fact, it pushes `[{: ".~"][} ".~"]`, leaving the stack as

    ```
    ["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n" [{: ".~"][} ".~"]

    ```
    5. Finally, `print` prints the topmost stack item without inspecting it, sending

    ```
    {: ".~"][}.~

    ```

    to STDOUT, 1-upping the source code.
> 13 votes

# Answer
# Javascript ES6 (REPL), 55 bytes

```
var a=-~a;$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();

```

*Saved 2 bytes thanks to @user81655!*

# Explanation

Here's the standard quine framework:

```
$=_=>`$=${$};$()`;$()

```

You should be able to see this framework inside the submission. More explanation below.

---

```
var a=-~a;

```

This is the counter, defaulted to 1. Basically, it tells us how much to repeat the quine and increments at the same time.

```
$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();

```

This is the quine part. We essentially repeat the quine string by the counter+1. Subsequent function calls will override the output.
> 11 votes

# Answer
# CJam, 14 bytes

```
{"_~"]-2>_o}_~

```

Try it online!

### How it works

```
{"_~"]-2>_o}_~

{          }    Define a code block and push it on the stack.
            _~  Push and execute a copy of it.
 "_~"           Push that string.
     ]          Wrap the entire stack in an array.
      -2>       Discard all but the last two elements (block and string).
         _o     Push and print a copy of that array.

```

After the last copy of the program has been executed, the array that contains the block and the string is still on the stack, so it is printed implicitly.
> 7 votes

# Answer
# NodeJS, ~~63~~ ~~61~~ ~~60~~ 55 bytes

*this will also work in JavaScript (ES6) if you consider multiple console messages to be separated by newlines (no REPL required)*

Saved 2 bytes thanks to @dev-null

```
(f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t()))()

```

*note that there is a newline at the end of the code.*

This was an interesting one, definitely one of my favorites for this site so far.

I'm fairly confident this can't be golfed much more. *(maybe SpiderMonkey's `print` function...)*

## Explanation

```
//FIRST ITERATION
            console.log(`(f=${f})()`)                   //logs to the console a quine of the source code using function f's toString()
                                     ||                 //causes the expression to evaluate to the second part, since console.log's return value is falsy
                                       (_=>t)           //a function that returns function t when called
       t=_=>                                            //defines function t to be the code above. When called, t will log a quine and then return a function that returns t.
      (                                      )(t())     //call t twice. (one call is done via the t() as an ignored parameter) This will print the quine twice.
 f=_=>                                                  //define f as the above code.
(                                                  )()  //call function f with no arguments. this results in a function returning t. (the result of calling t once)
                                                        //this newline is to compensate for console.log's behavior of adding a newline to its output
//SECOND ITERATION
(                                                  )    //call the function that returns t that was returned from the first iteration. This expression will result in whatever that function returns, which is t.
 f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t())     //this part evaluates to a function, which is passed as a parameter to the function that returns t, that ignores its parameter.
                                                    ()  //call whatever the last expression returned, which is the function t, with no parameters. This will print the quine once.
                                                        //this call will result in a function returning t, just like from the first iteration, so we can add on more iterations at will.

```
> 4 votes

# Answer
# Groovy, 83 bytes

```
s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//

```

There is one embedded and no trailing newline. This prints:

```
s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//

```

The function `f()` prints one copy of the quine. The initial program calls it twice. The first line of the appended code becomes a comment and only the second call to `f()` is executed.
> 4 votes

# Answer
# Ruby, 43 bytes

```
1;s="1;s=%p;$><<s%%s*n=2-0";$><<s%s*n=2-0

```

By itself, this prints itself `2-0` or `2` times. When concatenated to another copy of itself, the final print statement looks like `$><<s%s*n=2-01`, meaning it outputs itself just once (`01` being octal 1). So only the final copy of the string prints twice, the others print once.

The inline assignment to `n` is just to get the order of operations working correctly; state isn't actually being passed from one copy to the next.
> 4 votes

# Answer
## Ruby, 55 bytes

```
n||=2;s="n||=2;s=%p;$><<(s%%s)*n;n=1;";$><<(s%s)*n;n=1;

```

Nothing very interesting here, it is just a normal ruby quine with a counter.
> 2 votes

# Answer
# JavaScript (ES6), 164 bytes

```
console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))
console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))

```

Works in any JS testing page or console in Firefox, assuming that the space between two console messages counts as a newline.
> 2 votes

# Answer
# Perl 6, ~~58~~ 53 bytes

*Thanks to Jo King for -5 bytes.*

```
<say "<$_>~~.EVAL for 0..!.++;">~~.EVAL for 0..!.++;

```

Based on Jo King's quine.

Try it online!
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~65~~ ~~61~~ 55 bytes

```
a=2
exec(s:='print(end="a=2\\nexec(s:=%r)#"%s*a);a=1')#

```

Try it online!

---

# Python 2, 60 bytes

```
s='try:n\nexcept:n="s=%r;exec s"%s;print n\nprint n';exec s

```

Try it online!
> 2 votes

# Answer
# Japt, 40 bytes

```
Oo("+Q ²pT°?1:2 é4;POo("+Q ²pT°?1:2 é4;P

```

Test it online! Explanation to come.
> 1 votes

# Answer
#

## Noncompeting, 6 bytes

```
UCn*px

```

Y is a headcannon that I've had for a while, and this inspired me to write it. It is made for challenges in which sequencing is key, such as this. The code is divided into links by "node" characters. In this case, our code is put into two chains (originally), with the node being `C`.

```
U  C  n* px
1  N    2

```

`U` records a transcendental string, i.e., one that spans links. It records until it meets another `U`. If a `U` is not met by the end of the string, it wraps around. Also, `U` is included in the string by default. After recording the string, we proceed to the node `C`, which just moves us to the next link.

`n` pushes the number of chains. For our base case, this 2. For a sequence of `K` chains, there are `K+2` chains, as there are `K` nodes. `*` is string repittion. `p` prints the entire stack (in this case, one string), and `x` terminates the program.

In a text:

```
UCn*px
U..... record that string
 C     next link
  n*   repeat that string twice.
    px print and terminate

UCn*pxUCn*pxUCn*px
U.....U            record string
 C                 next link
  n*               repeat that string four times (three Cs)
    px             print and terminate

```

Try it here!
> 1 votes

# Answer
# Brachylog, 20 bytes

```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

```

Try it online!

Modified from this quine.

```
⊥                       Fail,
 ∨                      or
                w       print
  "⊥∨~kgjw₃w₅"          "⊥∨~kgjw₃w₅"
                 ₃      formatted
              gj        with itself;
                 ₃w₅    print it again at the end of the program if this route succeeds.

```

When this is concatenated with itself, every route except the last fails and the program moves on to the next one, executing each `w₃` and backtracking past every `w₅` except the very last one.

```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

```

Try it online!

```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

```

Try it online!

```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

```

Try it online!
> 1 votes

---
Tags: code-golf, quine, code-generation
---


title: Is this ordinal prime?

text:
# Question
Title: Is this ordinal prime?
You are given an countable ordinal \\$1 \< r \< \varepsilon\_0\\$. Determine whether or not it is prime. If not, provide exactly two ordinals \\$r\_0, r\_1 \< r\\$ such that \\$r\_0r\_1 = r\\$, following rules of ordinal multiplication, and furthermore satisfy at least one (**not necessarily both**) of the following:

1. \\$r\_0\\$ is a limit ordinal
2. \\$r\_0 \le r\_1\\$

More accurately, an ordinal expressed in Cantor normal form is a list \\$\[a\_1, a\_2, a\_3, \dots, a\_{n-1}, a\_n\]\\$, where when \\$1 \le i \< n\\$, \\$a\_i\\$ is an ordinal expressed in Cantor normal form and \\$a\_n\\$ is an integer. Furthermore, for \\$1 \< i \< n\\$, the ordinal inequality \\$a\_{i-1} \ge a\_i\\$ holds.

## Input

Any input that can provably describe any ordinal also expressible in Cantor normal form is accepted. For input forms deviating greatly from Cantor normal form, please also provide a brief way to convert a Cantor normal form ordinal to input.

## Output

If the given ordinal is prime, then a **constant result, distinct from non-prime inputs** must be returned.
Otherwise, return two ordinals, expressed the same way as the input, representing \\$r\_0\\$ and \\$r\_1\\$, respectively.

## Scoring

This is , so shortest program (in bytes) wins.

## Examples

An input of \\$\omega^2+1\\$, or `[2,1]` in Cantor normal form, would be marked prime.
On the other hand, an input of \\$\omega+2\\$, or `[1,2]` in Cantor normal form, would be composite and the program should return a pair `([2],[1,1])` in whatever form it accepted.
Remember that integers are ordinals too.
**You do not need to consider \\$r=1\\$.**

More examples:

```
[1,100] => [100] * [1, 1]
[2,1] => prime
[3,0] => [2,0] * [1,0]
[[1,1],2] => [2] * [[1,1],1]
[[1,1],0] => [[1,0],0] * [1,0]
[[1,0],0] => prime
[1,1,1] => [1,1] * [2]

```

# Answer
# Haskell, ~~1068 1042~~ 1012 bytes

-30, mostly from replacing if/then with guards. I'm sure it can be golfed more.

```
data W=W[W]Int deriving Show
f EQ y=y
f x _=x
m=1<0
k=1>0
[]#[]=EQ
[]#_=LT
_#[]=GT
(W x y:z)#(W a b:d)=f(x#a)$f(compare y b)$z#d
x?y=x#y>EQ
b x=break(\(W y _)->y#x/=GT)
x&[]=x
d&(x@(W v w):u)=case b v d of(y,W f m:_)|f#v>LT->y++(W v$m+w):u;(y,_)->y++x:u
x![]=x
d!(W v w:u)=case b v d of(_:_,_)->d;(_,W f m:g)->if w<m then(W f$m-w):g else g!u
[]%_=([],k)
x@(W g h:d)%b@(W e f:_)|b?x=([],m)|g!e?[]=(\(q,r)->([W(g!e)h]&q,r))$d%b|k=(\q->(q,(foldl(&)[]$t b<$>q)#x==EQ))[W[]$div h f]
t(W x y:z)(W[]n)=(W x$y*n):z
t(W x _:_)(W b n)=[W(x&b)n]
l=all(\(W e _)->e?[])
q=max
o[]=0
o(W e n:u)=q n$q(o e)$o u
v[]=0
v(W e n:u)=q(1+length u)$q(v e)$v u
d[]=0
d(W e n:u)=q(1+d e)$d u
e(W x _:[])(W y _:_)=x?y
e(_:x)y=e x y
g _ 0_ n=[[W[]x]|x<-[1..n]]
g m d s n|p<-g m(d-1)s n=fst$h s$filter(m?)$p++[[W x y]|x<-p,y<-[1..n]]
h 1z=(z,z)
h n z|(a,p)<-h(n-1)z,n<-[x++y|x<-z,y<-p,e x y]=(a++n,n)
r x=p x$g x(d x)(v x)$o x
p _[]="p"
p x(y:z)|(q,r)<-x%y,x?y&&x?q&&r&&(l y||not(l y&&l q||d y<2&&d q<2)||y#q<GT)=show y++"*"++show q|k=p x z

```

Try it online!

Or try a version that pretty-prints the inputs and outputs.

# Input Format

The input format is Cantor normal form, written as \\$\omega ^{\beta \_{1}}c\_{1}+\omega ^{\beta \_{2}}c\_{2}+\cdots+\omega ^{\beta \_{k}}c\_{k}\\$, where \\$k\\$ is a natural number, \\$ c\_{1},c\_{2},\ldots ,c\_{k}\\$ are positive integers, and \\$ \beta \_{1}\>\beta \_{2}\>\ldots \>\beta \_{k}\geq 0 \\$ are ordinal numbers.

Each term \\$\omega ^{b}c\\$ is written as `W b c` and terms are written as a list in `[]` separated by commas.

Examples:

`[]`\\$ = 0\\$

`[W[]1]`\\$ = 1\\$

`[W[W[]1]1]`\\$ = \omega\\$

`[W[W[]1]1,W[]1]`\\$ = \omega + 1\\$

`[W[W[]2]3,W[]4]` \\$=\omega^2\cdot 3 + 4\\$

`[W[W[W[]2]1]1,W[]4]` \\$=\omega^{\omega^2} + 4\\$

`[W[W[W[]1]1,W[]1]1,W[]1]`\\$ = \omega^{\omega+1} + 1\\$

# Test Cases

Output from the main version:

```
[W [W [] 2] 1,W [] 1] => p
[W [W [W [] 1] 1] 1] => p
[W [W [W [W [] 1] 1] 1] 1] => p
[W [W [] 1] 1,W [] 100] => [W [] 2]*[W [W [] 1] 1,W [] 50]
[W [W [] 3] 1] => [W [W [] 1] 1]*[W [W [] 2] 1]
[W [W [W [] 1] 1,W [] 1] 1,W [] 2] => [W [] 2]*[W [W [W [] 1] 1,W [] 1] 1,W [] 1]
[W [W [W [] 1] 1,W [] 1] 1] => [W [W [W [] 1] 1] 1]*[W [W [] 1] 1]
[W [W [] 1] 2,W [] 1] => [W [W [] 1] 1,W [] 1]*[W [] 2]
[W [] 2903591] => [W [] 1699]*[W [] 1709]

```

Output from the pretty-print version:

```
[W [W [] 2] 1,W [] 1] == w^2 + 1 => p
[W [W [W [] 1] 1] 1] == w^w => p
[W [W [W [W [] 1] 1] 1] 1] == w^(w^w) => p
[W [W [] 1] 1,W [] 100] == w + 100 => (2)*(w + 50)
[W [W [] 3] 1] == w^3 => (w)*(w^2)
[W [W [W [] 1] 1,W [] 1] 1,W [] 2] == w^(w + 1) + 2 => (2)*(w^(w + 1) + 1)
[W [W [W [] 1] 1,W [] 1] 1] == w^(w + 1) => (w^w)*(w)
[W [W [] 1] 2,W [] 1] == w*2 + 1 => (w + 1)*(2)
[W [] 2903591] == 2903591 => (1699)*(1709)

```

# Strategy

This is probably not the fastest solution, but I thought it might be relatively short for code golf. It works for all of the test cases and works well for natural numbers. For ordinals with many terms, this may take a very long time to run.

* Generate a sequence of ordinals which may divide the input.
* Test each ordinal in the sequence to determine whether it divides the input and meets the additional criteria. If it does, return a formatted string containing the divisor and quotient.
* If the sequence was exhausted, return "p" for prime.

# Implementation

I started with code I found online that implements ordinal addition and multiplication and uses the QuickCheck library to test that properties (theorems) are true for a large number of inputs.

I implemented left subtraction and then left division with remainder and verified that the operations were consistent with the following theorems.

Left subtraction: Let \\$x\\$ and \\$y\\$ be ordinals such that \\$x \geq y\\$. Then there exists a unique ordinal \\$z\\$ such that \\$x = y + z\\$.

Left division: Let \\$x\\$ and \\$y\\$ be ordinals. Suppose \\$y\neq0\\$. Then there exist unique ordinals \\$z\\$ and \\$w\\$ such that \\$x=y\cdot z+w\\$ and \\$w \< y\\$.

# Generated Sequences

To test whether an ordinal is prime, I generate a list of potential divisors. This would be easy for natural numbers, but infinite ordinals are greater than infinitely many ordinals.

I check the given ordinal to determine the depth, maximum number of terms (at each depth), and maximum coefficient.

I then recursively generate ordinals that are less than the given one and up to the given depth, term count, maximum coefficient. I don't have a proof that this is sufficient, but intuitively it seems like it would be.

Here are some examples.

Example 1: \\$\omega^2\cdot 3 + 4\\$. Depth: 2, Max term count: 2, Max coefficient: 4. Generated list of potential divisors, length 26: \\$1, 2, \omega, \omega + 1, \omega + 2, \omega\cdot2, \omega\cdot2 + 1, \omega\cdot2 + 2, \omega^2, \omega^2 + 1, \omega^2 + 2, \omega^2 + \omega, \omega^2 + \omega + 1, \omega^2 + \omega + 2, \omega^2 + \omega\cdot2, \omega^2 + \omega\cdot2 + 1, \omega^2 + \omega\cdot2 + 2, \omega^2\cdot2, \omega^2\cdot2 + 1, \omega^2\cdot2 + 2, \omega^2\cdot2 + \omega, \omega^2\cdot2 + \omega + 1, \omega^2\cdot2 + \omega + 2, \omega^2\cdot2 + \omega\cdot2, \omega^2\cdot2 + \omega\cdot2 + 1, \omega^2\cdot2 + \omega\cdot2 + 2\\$

Example 2: \\$\omega^\omega\cdot3+4\\$. Depth: 3, Max term count: 2, Max coefficient: 4. Generated terms list length: 151,994. Since that list is generated lazily, the program still gives a fast answer.

As the depth and maximum term count increase, the lengths of the generated sequences increase very quickly.

# Note

For the last given test case, \\$\omega\cdot2+1=(\omega+1)\cdot2\\$, I was unable to satisfy either of the two given additional criteria (\\$\_0\\$ is a limit ordinal, \\$\_0 \leq r\_1\\$). However, I was able to satisfy the following criteria stated on Wikipedia, which is a slight variation of the given criteria:

* Every limit prime occurs before every successor prime
* If two consecutive primes of the prime factorization are both limits or both finite, then the second one is at most the first one.

If anyone is interested, I could provide a less golfed version of this code.
> 9 votes

---
Tags: code-golf, math, number, primes
---


title: Minified Intcode Computer

text:
# Question
Title: Minified Intcode Computer
As the trip through the solar system on your way to rescue Santa gets a little droll, so perhaps some optimizations to your Intcode Computer are in order. Namely, making it as small as possible because you've got nothing better to do with your time.

*Check out Advent of Code if you haven't already, the guy that makes the puzzles is amazing; Day 11 blew my mind. I might be cribbing the specs for the Intcode Computer, but why not challenge people to minify it?*

## Here are the specifications for an Intcode Computer:

Links to the day where the specifications are introduced will be included. These pages will contain example programs to use as test cases as well as supplemental explanation, as I presume I don't have to explain what it means to "read from" or "write to" a memory address.

* An Intcode program is a list of integers (for example, `1,0,0,3,99`). To run one, start by looking at the first integer (called position `0)` this will be the opcode (enumerated below). Following an opcode will be its arguments (if any, each opcode will detail how many). *Entries may take programs in any reasonable format, including how to handle any input to an Intcode program.*
* Intcode Computers have an instruction pointer that, after executing an instruction moves forward a number of positions based on the opcode (1 plus the number of arguments). (Day 2)
* Each parameter of an instruction is handled based on its parameter mode. The rightmost two digits of an opcode indicate the opcode itself, while the remaining digits (read from right to left) indicate the argument mode (how the literal value of the argument is handled). (Day 5)
    + `0` is position mode. Read from the position indicated; eg. `mem[a]`
    + `1` is immediate mode. Read as a literal value; eg. `a`
        - Parameters that an instruction writes to will never be in immediate mode.
    + `2` is relative mode. Read from the position indicated by adding the RelativeCounter to the value; eg. `mem[a+r]`
* Intcode Computers have a `RelativeCounter` which is a value that is used as an offset for relative mode arguments. This value starts at `0` (during which, relative mode acts identically to position mode). (Day 9)
    + The `RelativeCounter` may hold a negative value.
* The computer's available memory should be much larger than the initial program. Memory beyond the initial program starts with the value 0 and can be read or written like any other memory. (It is invalid to try to access memory at a negative address, though.)
* The computer should have support for large numbers and negative numbers; `long`s are sufficient.

## Opcodes:

Arguments will be noted as `A`, `B`, etc. where `A` is the first argument, `B` is the second, and so on.

* `1`: Adds `A` and `B` and stores the result in `C`
* `2`: Multiplies `A` and `B` and stores the result in `C`
* `3`: Reads an integer from input and stores the result in `A`
* `4`: Outputs the value read from `A`
* `5`: Jump-if-true. If `A` is non-zero, it sets the instruction pointer to the value of `B`
* `6`: Jump-if-equal. If `A` is zero, it sets the instruction pointer to the value `B`
* `7`: Less than. If `A` is less than `B`, it stores `1` in the position given by `C`. Otherwise, it stores `0`
* `8`: Equals. If `A` is equal to `B`, it stores `1` in the position given by `C`. Otherwise, it stores `0`
* `9` Adjusts the RelativeCounter by the value of `A`. The relative base increases (or decreases, if the value is negative) by the value of the parameter.
* `99`: Terminates the program
* Other opcodes are invalid.

### Opcode & paramater mode detail

Taken from Day 5:

```
ABCDE
 1002

DE - two-digit opcode,      02 == opcode 2
 C - mode of 1st parameter,  0 == position mode
 B - mode of 2nd parameter,  1 == immediate mode
 A - mode of 3rd parameter,  0 == position mode,
                                  omitted due to being a leading zero

```

## Test cases

`[3,9,8,9,10,9,4,9,99,-1,8]` Using position mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not).
`[3, 3, 1107, -1, 8, 3, 4, 3, 99 ]` Using immediate mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not). (From Day 5)
`[109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]` takes no input and produces a copy of itself as output.
`[1102, 34915192, 34915192, 7, 4, 7, 99, 0]` should output a 16-digit number.
`[104, 1125899906842624, 99]` should output the large number in the middle. (From Day 9)
`[109, -1, 4, 1, 99]` outputs -1
`[109, -1, 104, 1, 99]` outputs 1
`[109, -1, 204, 1, 99]` outputs 109
`[109, 1, 9, 2, 204, -6, 99]` outputs 204
`[109, 1, 109, 9, 204, -6, 99]` outputs 204
`[109, 1, 209, -1, 204, -106, 99]` outputs 204
`[109, 1, 3, 3, 204, 2, 99]` outputs the input
`[109, 1, 203, 2, 204, 2, 99]` outputs the input (From Reddit regarding Day 9)
`[3, 11, 3, 12, 1, 11, 12, 9, 104, 0, 99]` takes two inputs and outputs their sum

*Day 9 features a self-test program that will output opcodes that do not appear to be operating correctly, provided that your Intcomputer is fully functional to Day 5 specifications. It is very long and contains per-user unique code relevant to part 2's puzzle, as such it is not included here.*

Day 7, Day 11, Day 13, Day 15, Day 17, Day 19, Day 21, and Day 23 all contain Intcode programs as well (as does, presumably, Day 25 if the pattern holds).

And remember, this is ! But that only applies to the Intcode Computer itself, any auxillary code to handle executing it is not counted towards your score.

### A Helpful Hint

When testing your intcode computer, it is very helpful to run the diagnostic program. Here's a copy for those without an AOC account.

Sometimes, your program will constantly output `203` when running this program. That means that opcode `03` doesn't work when placed in "relative mode". Quite a few of us on the CGCC Discord were experiencing this issue.

For information on how to fix this, read here

# Answer
# Python 3, ~~480 476 474 418~~  416 bytes

-56 bytes thanks to Value Ink

```
def a(c,i,o):
 p=g=r=0;c+=[0]*9999
 def v(b):r;x=c[p+b];return eval(["c[x]","x","c[x+r]"][m[b]])
 def s(b,e):c[c[p+b]+r*(m[b]>1)]=e
 while g!=99:
  g=c[p];m=[0]*4;k,g=g//100,g%100;n=1
  while k:k,m[n]=k//10,k%10;n+=1
  if g<3or 6<g<9:x,y=v(1),v(2);s(3,[x==y,x+y,x*y,x<y][g&3]);p+=4
  if g==3:s(1,i());p+=2
  if g==4:o(v(1));p+=2
  if g==5:p=v(2)if v(1)else p+3
  if g==6:p=p+3 if v(1)else v(2)
  if g==9:r+=v(1);p+=2

```

Takes as input the code, an input function (called with no arguments whenever the code requests input), and an output function (called with one argument, the value just output, whenever the program outputs something). I included all of the test cases given in the TIO link.

Try it online!
> 3 votes

# Answer
# JavaScript (V8),  ~~234~~  230 bytes

Expects `([program], [input])`, where *input* is ordered from last to first. Prints to stdout.

```
f=(P,i,p=r=0)=>(n=P[p++])-99&&([A,B]=(g=n=>o--?[(v=P[p++],k=n%10|0)-1?P[v+=k>1&&r]||0:v,...g(n/10)]:[])(n/100,o=~-(n%=10)%6>>1||3),n<4?P[v]=n<2?A+B:n<3?A*B:i.pop():n<5?print(A):n<7?!A^n>5?0:p=B:n<9?P[v]=n<8?A<B:A==B:r+=A,f(P,i,p))

```

Try it online!

## How?

The implementation is rather straightforward, except the computation of the number of parameters for a command \\$n \le 9\\$, for which we use the following formula:

```
(n - 1) % 6 >> 1 || 3

```

Which gives:

```
 n | -1 | %6 | >>1 | ||3 | action
---+----+----+-----+-----+--------------
 1 |  0 |  0 |  0  |  3  | A+B -> P[C]
 2 |  1 |  1 |  0  |  3  | A*B -> P[C]
 3 |  2 |  2 |  1  |  1  | input -> A
 4 |  3 |  3 |  1  |  1  | output A
 5 |  4 |  4 |  2  |  2  | p=B if A!=0
 6 |  5 |  5 |  2  |  2  | p=B if A==0
 7 |  6 |  0 |  0  |  3  | A<B  -> P[C]
 8 |  7 |  1 |  0  |  3  | A==B -> P[C]
 9 |  8 |  2 |  1  |  1  | r+=A

```

## Commented

### Helper function

\\$g\\$ is a helper function that retrieves \\$o\\$ parameters according to the upper digits of the current command, which are passed in \\$n\\$.

```
g = n =>                        // n = command / 100
  o-- ?                         // decrement o; if it was not equal to 0:
    [                           //   update the list of parameters
      (                         //
        v = P[p++],             //     v = next value read from the program
        k = n % 10 | 0          //     k = floor(n mod 10)
      ) - 1 ?                   //     if k is not equal to 1:
        P[v += k > 1 && r]      //       read P[v] if k = 0 or P[v + r] if k = 2
        || 0                    //       if undefined, use 0 instead
      :                         //     else:
        v,                      //       immediate mode: use v
      ...g(n / 10)              //     recursive call with n / 10
    ]                           //   end of update
  :                             // else:
    []                          //   stop recursion

```

### Main function

```
f = (                           // f is a recursive function taking:
  P,                            //   P[] = program
  i,                            //   i[] = input
  p = r = 0                     //   p = program pointer, r = relative counter
) =>                            //
  (n = P[p++]) - 99 && (        // read the next command n and stop if it's 99; otherwise:
    [A, B] = g(                 //   retrieve the first 2 parameters A and B (the latter
                                //   may be undefined) by invoking g:
      n / 100,                  //     pass n / 100
      o = ~-(n %= 10) % 6 >> 1  //     set o = number of parameters for this command,
          || 3                  //             using the formula described above
    ),                          //   end of call to g
    n < 4 ?                     //   if n is less than 4:
      P[v] =                    //     update P[v]:
        n < 2 ? A + B           //       if n = 1, store A + B
              : n < 3 ? A * B   //       if n = 2, store A * B
                      : i.pop() //       if n = 3, store the next input
    :                           //   else:
      n < 5 ?                   //     if n = 4:
        print(A)                //       output A
      :                         //     else:
        n < 7 ?                 //       if n = 5 or n = 6:
          !A ^ n > 5 ? 0        //         jump if (A == 0) XOR (n == 6) is false
                     : p = B    //
        :                       //       else:
          n < 9 ?               //         if n = 7 or n = 8:
            P[v] =              //           update P[v]:
              n < 8 ? A < B     //             test A < B if n = 7
                    : A == B    //             or A == B if n = 8
          :                     //         else:
            r += A,             //           update r
    f(P, i, p)                  //   recursive call for the next command
  )                             // end

```
> 2 votes

# Answer
# AWK, 285 283 bytes

```
{for(split(i,v);o<99;r+=o>8?x:0){o=$++p;a=int(o/100)%10;b=int(o/1000)%10;w=$++p+1+!!a*r;x=--a?$w:$p;y=$++p+1+!!b*r;y=--b?$y:$p;z=$++p+1+!(o<10^4)*r;o%=100;if(o~3)$w=v[++j];if(o~4)printf"%.f\n",x;if(o~/1|2|7|8/)$z=o<2?x+y:o<3?x*y:o<8?x<y:x==y;else{--p;p=o~5?x?y:p:o~6?!x?y:p:p-1}}}

```

Try it online!

This essentially works by treating the input fields as the locations in memory, instead of initializing an array to store the program.

An extra 3 bytes (included in score) are required for the `-F,` switch, which sets the comma as the field separator.

## Usage examples

`<code>` stands for the program posted above.

Interpret an Intcode program stored in a file named `intcode.txt`:

```
awk -F, '<code>' intcode.txt

```

Interpret an Intcode program using a Here-string:

```
awk -F, '<code>' <<< 9,1,204,-1,2205,-1,8,99,0

```

Pass a value as input:

```
awk -F, -v i=1 '<code>' intcode.txt

```

Pass multiple input values:

```
awk -F, -v i=1,2,3 '<code>' intcode.txt

```
> 1 votes

---
Tags: code-golf, interpreter
---


title: Make it explode!

text:
# Question
Title: Make it explode!
Take a matrix of positive integers as input, and **make it explode!**

---

The way you explode a matrix is by simply adding zeros around every element, including the outside borders.

Input/output formats are optional as always!

### Test cases:

```
1
-----
0 0 0
0 1 0
0 0 0
--------------

1 4
5 2
-----
0 0 0 0 0
0 1 0 4 0
0 0 0 0 0
0 5 0 2 0
0 0 0 0 0
--------------

1 4 7
-----
0 0 0 0 0 0 0
0 1 0 4 0 7 0
0 0 0 0 0 0 0
--------------

6
4
2
-----
0 0 0
0 6 0
0 0 0
0 4 0
0 0 0
0 2 0
0 0 0

```

# Answer
> 59 votes
# Operation Flashpoint scripting language, 182 bytes

```
f={t=_this;c=count(t select 0);e=[0];i=0;while{i<c*2}do{e=e+[0];i=i+1};m=[e];i=0;while{i<count t}do{r=+e;j=0;while{j<c}do{r set[j*2+1,(t select i)select j];j=j+1};m=m+[r,e];i=i+1};m}

```

**Ungolfed:**

```
f=
{
  // _this is the input matrix. Let's give it a shorter name to save bytes.
  t = _this;
  c = count (t select 0);

  // Create a row of c*2+1 zeros, where c is the number of columns in the
  // original matrix.
  e = [0];
  i = 0;
  while {i < c*2} do
  {
    e = e + [0];
    i = i + 1
  };

  m = [e]; // The exploded matrix, which starts with a row of zeros.
  i = 0;
  while {i < count t} do
  {
    // Make a copy of the row of zeros, and add to its every other column
    // the values from the corresponding row of the original matrix.
    r = +e;
    j = 0;
    while {j < c} do
    {
      r set [j*2+1, (t select i) select j];
      j = j + 1
    };

    // Add the new row and a row of zeroes to the exploded matrix.
    m = m + [r, e];
    i = i + 1
  };

  // The last expression is returned.
  m
}

```

**Call with:**

```
hint format["%1\n\n%2\n\n%3\n\n%4",
    [[1]] call f,
    [[1, 4], [5, 2]] call f,
    [[1, 4, 7]] call f,
    [[6],[4],[2]] call f];

```

**Output:**

**In the spirit of the challenge:**

# Answer
> 10 votes
# Jelly,  ~~12~~  11 bytes

-1 byte thanks to Erik the Outgolfer (no need to use swapped arguments for a join)

```
j00,0jµ€Z$⁺

```

**Try it online!** Or see a test suite.

A monadic link accepting and returning lists of lists.

### How?

```
j00,0jµ€Z$⁺ - Link: list of lists, m
          ⁺ - perform the link to the left twice in succession:
         $  -   last two links as a monad
      µ€    -     perform the chain to the left for €ach row in the current matrix:
j0          -       join with zeros                [a,b,...,z] -> [a,0,b,0,...,0,z]
  0,0       -       zero paired with zero = [0,0]
     j      -       join                     [a,0,b,0,...,0,z] -> [0,a,0,b,0,...,0,z,0]
        Z   -     and then transpose the resulting matrix

```

# Answer
> 7 votes
# Haskell, 38 bytes

```
a%l=a:(=<<)(:[a])l
f l=(0%)<$>(0<$l)%l

```

Try it online!

# Answer
> 6 votes
# MATL, 12 bytes

```
FTXdX*0JQt&(

```

Input is a matrix with `;` as row separator.

**Try it online!**

### Explanation

```
FT     % Push [0 1]
Xd     % Matrix with that diagonal: gives [0 0; 0 1]
X*     % Implicit input. Kronecker product
0      % Push 0
JQt    % Push 1+j (interpreted as "end+1" index) twice
&(     % Write a 0 at (end+1, end+1), extending the matrix. Implicit display

```

# Answer
> 5 votes
# Japt, 18 bytes

```
Ov"y ®î íZ c p0Ã"²

```

Test it online! (Uses the `-Q` flag so the output is easier to understand.)

Similar to the Jelly answer, but a whole lot longer...

### Explanation

The outer part of the code is just a workaround to simulate Jelly's :

```
  "             "²   Repeat this string twice.
Ov                   Evaluate it as Japt.

```

The code itself is:

```
y ®   î íZ c p0Ã
y mZ{Zî íZ c p0}   Ungolfed
y                  Transpose rows and columns.
  mZ{          }   Map each row Z by this function:
     Zî              Fill Z with (no argument = zeroes).
        íZ           Pair each item in the result with the corresponding item in Z.
           c         Flatten into a single array.
             p0      Append another 0.

```

Repeated twice, this process gives the desired output. The result is implicitly printed.

# Answer
> 5 votes
## Husk, 12 bytes

```
₁₁
Tm»o:0:;0

```

Takes and returns a 2D integer array. Try it online!

## Explanation

Same idea as in many other answers: add zeroes to each row and transpose, twice. The row operation is implemented with a fold.

```
₁₁         Main function: apply first helper function twice
Tm»o:0:;0  First helper function.
 m         Map over rows:
  »         Fold over row:
   o         Composition of
      :       prepend new value and
    :0        prepend zero,
       ;0    starting from [0].
            This inserts 0s between and around elements.
T          Then transpose.

```

# Answer
> 5 votes
## Mathematica, 39 bytes

```
r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r

```

Try it at the Wolfram sandbox! Call it like "`r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r@{{1,2},{3,4}}`".

Like many other answers, this works by transposing and riffling zeros in each row then doing the same thing again. Inspired by Jonathan Allan's Jelly answer specifically, but only because I happened to see that answer first.

# Answer
> 4 votes
# Dyalog APL, 24 bytes

*4 bytes saved thanks to @ZacharyT*

*5 bytes saved thanks to @KritixiLithos*

```
{{⍵↑⍨-1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~104 101 97 93~~ 86 bytes

* @Zachary T saved 3 bytes: unused variable `w` removed and one unwanted space
* @Zachary T saved yet another 4 bytes: `[a,b]` as just `a,b` while appending to a list
* @nore saved 4 bytes: use of slicing
* @Zachary T and @ovs helped saving 7 bytes: squeezing the statements in for loop

```
def f(a):
 m=[(2*len(a[0])+1)*[0]]
 for i in a:r=m[0][:];r[1::2]=i;m+=r,m[0]
 return m

```

Try it online!

# Answer
> 3 votes
# Octave, 41 bytes

```
@(M)resize(kron(M,[0 0;0 1]),2*size(M)+1)

```

Try it online!

# Answer
> 3 votes
# Python 3, 118 bytes

```
def a(b):
    z='00'*len(b[0])+'0'
    r=z+'\n'
    for c in b:
        e='0'
        for d in c:e+=str(d)+'0'
        r+=e+'\n'+z+'\n'
    return r

```

First time golfing! Not the best, but I'm quite proud if I can say so myself!

* -17 bytes from Wheat comments
* -4 bytes from inlining the second for loop

# Answer
> 3 votes
## R, 65 bytes

Thanks to Jarko Dubbeldam and Giuseppe for very valuable comments!

Code

```
f=function(x){a=dim(x);y=array(0,2*a+1);y[2*1:a[1],2*1:a[2]]=x;y}

```

Input for the function must be a matrix or two dimensional array.

Test

```
f(matrix(1))
f(matrix(c(1,5,4,2),2))
f(matrix(c(1,4,7),1))
f(matrix(c(6,4,2)))

```

Output

```
> f(matrix(1))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    1    0
[3,]    0    0    0
> f(matrix(c(1,5,4,2),2))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    1    0    4    0
[3,]    0    0    0    0    0
[4,]    0    5    0    2    0
[5,]    0    0    0    0    0
> f(matrix(c(1,4,7),1))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    0    0    0    0    0
[2,]    0    1    0    4    0    7    0
[3,]    0    0    0    0    0    0    0
> f(matrix(c(6,4,2)))
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    6    0
[3,]    0    0    0
[4,]    0    4    0
[5,]    0    0    0
[6,]    0    2    0
[7,]    0    0    0

```

# Answer
> 3 votes
# Python 2, 64 bytes

```
lambda l:map(g,*map(g,*l))
g=lambda*l:sum([[x,0]for x in l],[0])

```

Try it online!

The function `g` intersperses the input between zeroes. The main function transposes the input while applying `g`, then does so again. Maybe there's a way to avoid the repetition in the main function.

# Answer
> 2 votes
# Mathematica, 55 bytes

```
(a=ArrayFlatten)@{o={0,0},{0,a@Map[{{#,0},o}&,#,{2}]}}&

```

# Answer
> 2 votes
# PHP, 98 bytes

Input as 2D array, Output as string

```
<?foreach($_GET as$v)echo$r=str_pad(0,(count($v)*2+1)*2-1," 0"),"
0 ".join(" 0 ",$v)." 0
";echo$r;

```

Try it online!

# PHP, 116 bytes

Input and Output as 2D array

```
<?foreach($_GET as$v){$r[]=array_fill(0,count($v)*2+1,0);$r[]=str_split("0".join(0,$v)."0");}$r[]=$r[0];print_r($r);

```

Try it online!

# Answer
> 2 votes
## Clojure, 91 bytes

```
#(for[h[(/ 2)]i(range(- h)(count %)h)](for[j(range(- h)(count(% 0))h)](get(get % i[])j 0)))

```

Iterates over ranges in half-steps.

# Answer
> 2 votes
# Perl 6, 33 bytes

```
{map {0,|$_,0},0 xx$_,|$_,0 xx$_}

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), ~~73~~ 72 bytes

```
a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g)

```

### Formatted and commented

Inserting zeros horizontally and vertically are very similar operations. The idea here is to use the same function **g()** for both steps.

```
a =>                            // a = input array
  (g = a =>                     // g = function that takes an array 'a',
    (                           //     builds a new array 'r' where
      r = [b],                  //     'b' is inserted at the beginning
      a.map(v => r.push(v, b)), //     and every two positions,
      b = 0,                    //     sets b = 0 for the next calls
      r                         //     and returns this new array
  ))(a, b = a[0].map(_ => 0))   // we first call 'g' on 'a' with b = row of zeros
  .map(g)                       // we then call 'g' on each row of the new array with b = 0

```

### Test cases

```
let f =

a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g)

console.log(JSON.stringify(f([
  [1]
])))

console.log(JSON.stringify(f([
  [1, 4],
  [5, 2]
])))

console.log(JSON.stringify(f([
  [1, 4, 7]
])))

console.log(JSON.stringify(f([
  [6],
  [4],
  [2]
])))
```

# Answer
> 2 votes
# Java 8, ~~183~~ ~~166~~ ~~162~~ ~~129~~ 119 bytes

```
m->{int a=m.length,b=m[0].length,i=a*b,r[][]=new int[a-~a][b-~b];for(;i-->0;)r[i/b*2+1][i%b*2+1]=m[i/b][i%b];return r;}

```

Input and output as a `int[][]`.

-33 bytes by creating a port of *@auhmaan*'s C# answer.
-10 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
m->{                             // Method with integer-matrix as both parameter & return
  int a=m.length,                //  Set `a` to the input-height
      b=m[0].length,             //  Set `b` to the input-width
      i=a*b,                     //  Index integer, starting at `a*b`
      r[][]=new int[a-~a][b-~b]; //  Result integer-matrix with dimensions a*a+1 by b*b+1
  for(;i-->0;)                   //  Loop `i` in the range (a*b, 0] (so over each cell):
    r[i/b*2+1][i%b*2+1]=         //   Fill the current cell of the result-matrix:
      m[i/b][i%b];               //    With the correct input-integers
  return r;}                     //  Return result integer-matrix

```

# Answer
> 2 votes
# Charcoal, 49 bytes

```
Ａ⪪θ;αＡ””βＦ⁺¹×²Ｌ§α⁰Ａ⁺β⁰βＡ⁺β¶βＦα«βＡ0δＦιＡ⁺δ⁺κ⁰δ⁺δ¶»β

```

Try it online!

The input is a single string separating the rows with a semicolon.

# Answer
> 2 votes
# C++17 + Modules, 192 bytes

Input as rows of strings from *cin*, Output to *cout*

```
import std.core;int main(){using namespace std;int i;auto&x=cout;string s;while(getline(cin,s)){for(int j=i=s.length()*2+1;j--;)x<<0;x<<'\n';for(auto c:s)x<<'0'<<c;x<<"0\n";}for(;i--;)x<<'0';}

```

# Answer
> 2 votes
## C#, 146 bytes

---

### Data

* **Input** `Int32[,]` `m` The matrix to be exploded
* **Output** `Int32[,]` The exploded matrix

---

### Golfed

```
(int[,] m)=>{int X=m.GetLength(0),Y=m.GetLength(1),x,y;var n=new int[X*2+1,Y*2+1];for(x=0;x<X;x++)for(y=0;y<Y;y++)n[x*2+1,y*2+1]=m[x,y];return n;}

```

---

### Ungolfed

```
( int[,] m ) => {
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    return n;
}

```

---

### Ungolfed readable

```
// Takes an matrix of Int32 objects
( int[,] m ) => {
    // To lessen the byte count, store the matrix size
    int
        X = m.GetLength( 0 ),
        Y = m.GetLength( 1 ),
        x, y;

    // Create the new matrix, with the new size
    var
        n = new int[ X * 2 + 1, Y * 2 + 1 ];

    // Cycle through the matrix, and fill the spots
    for( x = 0; x < X; x++ )
        for( y = 0; y < Y; y++ )
            n[ x * 2 + 1, y * 2 + 1 ] = m[ x, y ];

    // Return the exploded matrix
    return n;
}

```

---

### Full code

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBench {
    public static class Program {
        private static Func<Int32[,], Int32[,]> f = ( int[,] m ) => {
            int
                X = m.GetLength( 0 ),
                Y = m.GetLength( 1 ),
                x, y,

                a = X * 2 + 1,
                b = Y * 2 + 1;

            var
                n = new int[ a, b ];

            for( x = 0; x < X; x++ )
                for( y = 0; y < Y; y++ )
                    n[ a, b ] = m[ x, y ];

            return n;
        };

        public static Int32[,] Run( Int32[,] matrix ) {
            Int32[,]
                result = f( matrix );

            Console.WriteLine( "Input" );
            PrintMatrix( matrix );

            Console.WriteLine( "Output" );
            PrintMatrix( result );

            Console.WriteLine("\n\n");

            return result;
        }

        public static void RunTests() {
            Run( new int[,] { { 1 } } );
            Run( new int[,] { { 1, 3, 5 } } );
            Run( new int[,] { { 1 }, { 3 }, { 5 } } );
            Run( new int[,] { { 1, 3, 5 }, { 1, 3, 5 }, { 1, 3, 5 } } );
        }

        static void Main( string[] args ) {
            RunTests();

            Console.ReadLine();
        }

        public static void PrintMatrix<TSource>( TSource[,] array ) {
            PrintMatrix( array, o => o.ToString() );
        }
        public static void PrintMatrix<TSource>( TSource[,] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 xIndex = 0; xIndex < array.GetLength( 0 ); xIndex++ ) {
                List<String>
                    inner = new List<String>();

                for( Int32 yIndex = 0; yIndex < array.GetLength( 1 ); yIndex++ ) {
                    inner.Add( valueFetcher( array[ xIndex, yIndex ] ) );
                }

                output.Add( $"[ {String.Join( ", ", inner )} ]" );
            }

            Console.WriteLine( $"[\n   {String.Join( ",\n   ", output )}\n]" );
        }
    }
}

```

---

### Releases

* **v1.0** \- `146 bytes` \- Initial solution.

---

### Notes

* None

# Answer
> 1 votes
# Dyalog APL, 24 bytes

```
{{⍵↑⍨¯1-⍴⍵}⊃⍪/,/2 2∘↑¨⍵}

```

Any improvements are welcome and wanted!

# Answer
> 1 votes
# Python 2, 92 bytes

```
n=input()
a=[[0]*(2*len(n[0])+1)for i in[0]+2*n]
for l,v in zip(a[1::2],n):l[1::2]=v
print a

```

Try it online!

# Answer
> 1 votes
## JavaScript (ES6), ~~80~~ 78 bytes

```
a=>[...a,...a,a[0]].map((b,i)=>[...b,...b,0].map((_,j)=>i&j&1&&a[i>>1][j>>1]))

```

# Answer
> 1 votes
# Python 3 \+ Numpy, 87 bytes

```
from numpy import*
def f(a):b=zeros((2*len(a)+1,2*len(a[0])+1));b[1::2,1::2]=a;return b

```

Try it online!

# Answer
> 1 votes
# Pyth, 13 bytes

```
uCm+0s,R0dG2Q

```

Demonstration

Another 13:

```
uC.iL+0m0dG2Q

```

# Answer
> 1 votes
# APL (Dyalog), 22 bytes

Prompts for matrix, returns enclosed matrix.

```
{⍺⍀⍵\a}/⍴∘0 1¨1+2×⍴a←⎕

```

Try it online!

`a←⎕` prompt for matrix and assign to *a*

the dimensions of *a* (rows, columns)

multiply by two

`1+` add one

`⍴∘0 1¨` use each to **r**eshape (cyclically) the numbers zero and one

`{``}/` reduce by inserting the following anonymous function between the two numbers:

`⍵\a` expand\* the columns of *a* according to the right argument

`⍺⍀a` expand\* the rows of that according to the left argument

* 0 inserts a column/row of zeros, 1 inserts an original data column/row

# Answer
> 0 votes
# , 24 bytes

```
0,.0,[:,./^:2(0,.~,&0)"0

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 22 bytes

```
"vy0ý0.ø})"©.V€Sø®.Vø»

```

Try it online!

---

Actually uses the same piece of code 2x, so I can store it as a string and use Eval for -10 bytes.

# Answer
> 0 votes
# Python 2, 92 bytes

```
def n(a):
	l,g='0 ',len(a[0])*2+1;print l*g
	for i in a:print l+' 0 '.join(i)+' 0';print l*g

```

Try it online!

# Answer
> 0 votes
# 05AB1E, ~~11~~ 8 bytes

```
2Fε€0Ć}ø

```

Try it online or verify all test cases.

**Explanation:**

```
2F      # Loop 2 times:
  ε     #  Map each row of the matrix to:
        #  (which uses the (implicit) input-matrix in the first iteration)
   €0   #   Add a leading 0 before each item in the list
     Ć  #   Enclose the list, appending its own first item (to add a trailing 0 as well)
  }ø    #  After the map: zip/transpose; swapping rows/column
        # (after the loop, the result is output implicitly)

```

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


title: Make it rain characters

text:
# Question
Title: Make it rain characters
*Inspired by this chat mini-challenge.*

Given a string as input (ASCII printable characters only), output the string with the letters "raining" down. Each letter must be a random number of lines downward (random between `0` and the length of the string, each having non-zero probability), and only one character per column. All possible outputs must again have a non-zero probability of occurring.

That's maybe a little confusing, so here's an example (taken from that CMC):

```
Hello World

          d
H
       o
  llo

         l
      W
 e
        r

```

Note how the `H` is one space down, the `d` is zero down, and the `llo` all happen to line up. The `r` is the farthest down, at `9`, but is still less than the string length away from the top. This is just one example, there are dozens of other possibilities for input `Hello World`.

Other examples could be:

```
test

t
 e
  s
   t

PP&CG

  & G
 P

P  C

```

---

* Input and output can be given by any convenient method.
* The input is guaranteed non-empty (i.e., you'll never receive `""` as input).
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately (e.g., feel free to pad as a rectangle).
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 5 votes
# , 104 bytes

```
function(s){m=matrix(" ",l<-nchar(s),l)
m[cbind(1:l,sample(l,l,T))]=el(strsplit(s,""))
write(m,1,l,,"")}

```

Try it online!

Input as a string; writes to stdout.

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

Takes input as a list of characters. Returns a matrix of characters.

```
a=>a.map((_,y)=>a.map((c,x)=>Math.random()<.5|!a[y+1]?(a[x]=' ',c):' '))

```

Try it online!

# Answer
> 4 votes
# Pyth - 9 bytes

Outputs list of lines.

```
.tm+*;OlQ

 .t                       Transpose, padding with spaces
  m      (Q implicit)     Map over input
   +    (d implicit)      Concatenate to loop var
    *                     String repeat
     ;                    This refers to the var replaced by loop var, which is d=" "
     O                    Random number less than
      lQ                  Length of input

```

Try it online.

# Answer
> 4 votes
# Japt, 8 bytes

*-1 byte from @Shaggy*

```
y_iUÊö ç

```

---

```
y_iUÊö ç        Full Program. Implicit input U
y_              transpose and map each row in U (Call it X)
  i             Insert at the beginning of X:
       ç        " " repeated ↓ many times
   UÊö          random integer in [0, length of U]
                implicit transpose back and output

```

Try it online!

# Answer
> 4 votes
# , ~~30~~ 19 bytes

```
|:@,.]{.~"+_2-#?@##

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 16 bytesSBCS

Anonymous tacit prefix function

```
⍉∘↑⊢↑¨⍨∘-∘?≢⍴1+≢

```

length of string

`1+` one added to that

`≢⍴` "length" copies of that

`∘?` random integers in range 1…those, and then…

`∘-` negate, and then…

`⊢↑¨⍨` take than many elements from each character, padding on the left with spaces

`∘↑` mix list of strings into matrix, padding with spaces on the right

transpose

Try it online!

# Answer
> 3 votes
# Julia, 69 bytes

```
f(s)=(n=length(s);z=fill(' ',n,n);for i=1:n z[rand(1:n),i]=s[i]end;z)

```

This defines a function `f` that accepts a `String` or `Vector{Char}` and returns a `Matrix{Char}`.

Ungolfed:

```
function f(s)
    n = length(s)
    z = fill(' ', n, n)  # an n×n matrix of spaces
    for i = 1:n
        # set a random entry in the ith column to the ith character in s
        z[rand(1:n),i] = s[i]
    end
    z
end

```

Example:

```
julia> f("test")
4×4 Array{Char,2}:
 't'  ' '  ' '  ' '
 ' '  ' '  ' '  ' '
 ' '  'e'  ' '  't'
 ' '  ' '  's'  ' '

```

This could surely be better; my golfing skills are pretty rusty.

Try it online!

# Answer
> 2 votes
# Ruby, ~~59~~ ~~57~~ 55 bytes

```
->a{a.map{|c|s=[' ']*z=a.size;s[rand z]=c;s}.transpose}

```

Try it online!

Inputs 1D, outputs 2D array of characters.

# Answer
> 2 votes
# Japt, 8 bytes

```
yÈùUÊö Ä

```

Try it

```
yÈùUÊö Ä     :Implicit input of string U
y            :Transpose
 È           :Pass each column through the following function and transpose back
  ù          :  Left pad with spaces to length
   UÊ        :    Length of U
     ö       :    Random number in the range [0,UÊ)
       Ä     :    Plus 1

```

# Answer
> 2 votes
# Jelly, 10 bytes

```
³LŻX⁶x;)z⁶

```

Try it online!

```
      )    | For each input character
³L         | Length of original input
  Ż        | 0..length
   X       | Random number from that list
    ⁶x     | That number of spaces
       ;   | Concatenate to the character
        z⁶ | Finally transpose with space as filler

```

# Answer
> 2 votes
# PHP, 88 bytes

```
for($o='';$i<$l=strlen($argn);$o[$i+$l*rand(0,$l)]=$argn[$i++]);echo chunk_split($o,$l);

```

Try it online!

Or **94 bytes** using PHP's cryptographic random integers function.

```
for($o='';$i<$l=strlen($argn);$o[$i+$l*random_int(0,$l)]=$argn[$i++]);echo chunk_split($o,$l);

```

Try it online!

Input from `STDIN`, output to `STDOUT`. Run as:

```
$ echo Hello World|php -nF rain.php
   l  W
  l

 e      r d

H      o

         l

    o

```

-1 byte (empty string instead of space) and +1 byte (err on side of rules) thx to @ASCII-only!

# Answer
> 1 votes
# Charcoal, ~~10~~ 9 bytes

```
↑Ｅθ◧ι⊕‽Ｌθ

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte thanks to @ASCII-only. Explanation:

```
  θ         Input string
 Ｅ          Map over characters
        θ   Input string
       Ｌ    Length
      ‽     Random value
     ⊕      Incremented
    ι       Current character
   ◧        Padded to length
↑           Print rotated

```

As ASCII-only points out, you can move the letters randomly up instead of down for the same effect (except that there might be extra white space at the bottom rather than the top). Printing an array of characters upwards is equivalent to printing a string normally, so the padding then just offsets each character vertically by a random amount.

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

```
εIgÝΩú}ζ»

```

Input as a string or list of characters (either is fine).

Try it online.

**Much slower 9-bytes alternative:**

```
gDÝsãΩúζ»

```

Input as a list of characters.

Try it online.

Both use the legacy version of 05AB1E, since the new version requires an explicit `€S` before the `ζ`..

**Explanation:**

```
ε       # Map each character in the (implicit) input to:
 Ig     #  Take the length of the input
   Ý    #  Create a list in the range [0, input-length]
    Ω   #  Pop and push a random integer from this list
     ú  #  Pad the current character with that many leading spaces
}ζ      # After the map: zip/transpose; swapping rows/columns (with space as default filler)
  »     # Then join all strings by newlines (and it output implicitly as result)

g          # Get the length of the (implicit) input-list
 D         # Duplicate this length
  Ý        # Create a list in the range [0, input-length]
   sã      # Take the cartesian product of this list that many times
     Ω     # Pop and push a random list from this list of lists of integers
      ú    # Pad the characters in the (implicit) input-list with that many spaces
       ζ   # Zip/transpose; swapping rows/columns (with space as default filler)
        »  # Then join all strings by newlines (and it output implicitly as result)

```

# Answer
> 1 votes
# C (gcc), ~~131~~ 125 bytes

-6 bytes thanks to ceilingcat

```
f(char*s){int l=strlen(s),R[l],i=l,j;for(srand(&l);i--;)R[i]=rand()%l;for(;++i<l*l;printf("\n%c"+!!j,i/l^R[j=i%l]?32:s[j]));}

```

Try it online!

# Answer
> 1 votes
# K (oK), 20 bytes

**Solution:**

```
+c$(-1-c?c:#x)$++x:

```

Try it online!

**Explanation:**

```
+c$(-1-c?c:#x)$++x: / the solution
                 x: / store input as x
                +   / flip (enlist)
               +    / flip again (break into chars)
              $     / pad (each) character
   (         )      / do this together
           #x       / length of x
         c:         / save as c
      -c?           / choose (?) c times from c
    -1              / subtract from -1
 c$                 / pad to length of x
+                   / flip

```

# Answer
> 1 votes
# Perl 5 `-F`, ~~50~~ 49 bytes

*-1 by @DomHastings*

```
map$;[rand@F][$i++]=$_,@F;say map$_||' ',@$_ for@

```

Try it online!

# Answer
> 1 votes
# PowerShell, ~~108~~ ~~102~~ 98 bytes

-4 bytes thanks to mazzy

```
$a=1..($z=($y=$args|% t*y).count)|%{random $z}
1..$z|%{-join($y|%{" $_"[$a[$i++%$z]-eq+$r]});$r++}

```

Try it online!

Basically iterates `1..length` of the string twice, once to get random line locations for each character, and a second time to actually build each line using those indices. Figuring out how to do it in one sweep is where the big byte savings are.

# Answer
> 1 votes
# AWK, ~~120~~ 118 bytes

```
{while(i++<NF)r[i]=int(rand()*NF)+1;for(;l++<NF;j=k=0){while(k++<NF)if(r[k]==l){printf"%*c",k-j,$k;j=k}print FS}}

```

Try it online!

I've included the 5 bytes in the score for the necessary `-F ''` switch, but I had to use the `BEGIN{FS=""}` directive for the TIO link since it doesn't process the command-line switch properly.

# Answer
> 0 votes
# Python - 92 bytes

```
import random
lambda s:map(None,*[(random.randrange(len(s))*' '+c).ljust(len(s))for c in s])

```

# Answer
> 0 votes
# SmileBASIC 3, 62 bytes

```
LINPUT T$L=LEN(T$)CLS
FOR I=0TO L-1LOCATE,RND(L+1)?T$[I];
NEXT

```

# Answer
> 0 votes
# Red, 84 bytes

```
func[s][foreach n random collect[repeat n length? s[keep n]][print pad/left s/:n n]]

```

Try it online!

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

```
from random import*
def f(s):
	e=range(len(s))
	p=[choice(e)for t in s]
	for r in e:print(''.join((r-p[i]and' 'or s[i]for i in e)))

```

Try it online!

# Answer
> 0 votes
# Python 3, 208 bytes

```
import random as r;x=input();R=range(len(x));c=[r.choice(R) for i in R];y=[' '*c[i]+x[i]+' '*(len(x)-c[i]) for i in R];R=range(len(y));print('\n'.join([''.join(r) for r in [[y[i][j] for i in R] for j in R]]))

```

Creates a list of random choices, then makes a list of columns with blank space everywhere except at the index specified by each random choice. The columns are transposed into rows and printed out with newlines between them.

Try it online!

---
Tags: code-golf, string, ascii-art, random
---


title: Newtons Method by Recursive Quines

text:
# Question
Title: Newtons Method by Recursive Quines
Your task is to calculate the square root of 2 using Newton's Method - with a slight twist. Your program is to calculate an iteration using Newton's Method, and output the source code for the following iteration (which must be able to do the same).

Newton's method is fairly exhaustively described on Wikipedia

To calculate square root 2 using Newtons method, you:

* Define `f(x) = x^2 - 2`
* Define `f'(x) = 2x`
* Define `x[0]` (the initial guess) `= 1`
* Define `x[n+1] = x[n] - (f[n] / f'[n])`

Each iteration will move x\[n\] closer to the square root of two. So -

* `x[0] = 1`
* `x[1] = x[0] - f(x[0])/f'(x[0]) = 1 - (1 ^ 2 - 2) / (2 * 1) = 1.5`
* `x[2] = x[1] - f(x[1])/f'(x[1]) = 1.5 - (1.5 ^ 2 - 2) / (2 * 1.5) = 1.416666667`
* `x[3] = x[2] - f(x[2])/f'(x[1]) = 1.416666667 - (1.416666667 ^ 2 - 2) / (2 * 1.416666667) = 1.414215686`
* and so on

Your program will:

* Calculate `x[n]` where `n` is the amount of times the program has been run
* Output the source code to a valid program in the same language which must calculate `x[n+1]` and satisfy the same criteria of this question.
* The first line of the source code must be the calculate result, properly commented. If the source requires something particular (such as a shebang) on the first line, the result may be put on the second line.

Note that

* Your program must use an initial guess of `x[0] = 1`
* The Standard Loopholes apply
* Any in-build power, square root or xroot functions are forbidden
* Your program must not accept any input whatsoever. It must be entirely self contained.

Your score is the size of your initial program in UTF-8 bytes. The lowest score wins.

# Answer
> 19 votes
# Common Lisp, 223 95 68 66

```
(#1=(lambda(x p)(format t"~S~%~S"p`(,x',x,(+(/ p 2)(/ p)))))'#1#1)

```

Now that I read the problem statement more carefully (thanks, primo!) I noticed that the first line must *be* the result of calculation, not that it needs to *contain* the result. Thus, I think my earlier attempts did not quite follow the rules. This one should.

Example use (SBCL 1.1.15):

```
$ sbcl --script nq.lisp | tee nq2.lisp
1
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 3/2)
$ sbcl --script nq2.lisp | tee nq3.lisp
3/2
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 17/12)
$ sbcl --script nq3.lisp | tee nq4.lisp
17/12
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 577/408)
$ sbcl --script nq4.lisp | tee nq5.lisp
577/408
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 665857/470832)
$ sbcl --script nq5.lisp | tee nq6.lisp
665857/470832
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 886731088897/627013566048)
$

```

# Answer
> 17 votes
## Python 53 bytes

*Saved 7 bytes due to @Mukundan.*

```
x=1.
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o

```

I've simplified the formula slightly, using the following substitutions:

```
  x-(x²-2)/(2x)
= (2x²)/(2x)-(x²-2)/(2x)
= (2x²-x²+2)/(2x)
= (x²+2)/(2x)
= (x+2/x)/2
= x/2+1/x

```

I hope that's not an issue.

The program proceeds in the following manner:

```
$ python newton-quine.py
x=1.5
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o

$ python newton-quine.py
x=1.41666666667
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o

$ python newton-quine.py
x=1.41421568627
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o

$ python newton-quine.py
x=1.41421356237
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o

```

etc.

# Answer
> 13 votes
# CJam, 20 bytes

```
1
{\d_2/1@/+p"_~"}_~

```

Try it online.

### Output

```
$ cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~'); echo
1.5
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~')); echo
1.4166666666666665
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~'))); echo
1.4142156862745097
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~')))); echo
1.4142135623746899
{\d_2/1@/+p"_~"}_~

```

### How it works

```
1       " Push the initial guess.                                                 ";
{       "                                                                         ";
  \d    " Swap the code block with the initial guess and cast to Double.          ";
  _2/   " Duplicate the initial guess and divide the copy by 2.                   ";
  1@/   " Push 1, rotate the initial guess on top and divide.                     ";
  +p    " Add the quotients and print.                                            ";
  "_~"  " Push the string '_~'.                                                   ";
}       "                                                                         ";
_~      " Duplicate the code block (to leave a copy on the stack) and execute it. ";

```

# Answer
> 8 votes
# ECMAScript 6, 38 36

```
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.5)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4166666666666665)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4142156862745097)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4142135623746899)

```

---

## JavaScript, 51

```
(function f(x){return "("+f+")("+(x/2+1/x)+")"})(1)

```

This is the same as the above, for older browsers.

# Answer
> 6 votes
# Lua 129

Probably way too long, but the Lua quine sucks because the nested `[[ ]]` is a deprecated feature. But it works regardless:

```
x=1.0;x=x/2.+1./x;l=[[io.write('x=',x,';x=x/2.+1./x;l=[','[',l,']','];',l)]];io.write('x=',x,';x=x/2.+1./x;l=[','[',l,']','];',l)

```

It's a bit nicer to see if you add newlines instead of colons:

```
x=1.0
x=x/2.+1./x
l=[[io.write('x=',x,'\nx=x/2.+1./x\nl=[','[',l,']','];',l)]];io.write('x=',x,'\nx=x/2.+1./x\nl=[','[',l,']','];',l)

```

# Answer
> 4 votes
# J - ~~102~~ 88 bytes

This is as horrible as I'm at making quines (I will probably revise this when I get better ideas). J's floats are limited to 5 decimal places, but by replacing first line with `x=:1x` it would be a fraction with infinite precision.

```
Edit 1: I got better idea. Also added the explanation.

```

---

```
x=:1
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''

```

First few iterations:

```
x=:1.5
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''

x=:1.41667
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''

x=:1.41422
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''

```

### Explanation

```
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:) The quine-function
                         3&}.,],{:,{:  Build the second row
                         3&}.          Get everything but the first 3 characters from the string
                             ,]        Get the whole string and concat
                               ,{:     Get the last item (') and concat
                                  ,{:  -||-
 (3&{.,[:":(x%2)+1%x"_)                Build the first row
       [:":(x%2)+1%x"_                 Calculate x/2 + 1/x (stolen from Pythoneer) and stringify
  3&{.                                 Take the first 3 characters from the string (x=:)
      ,                                Concatenate 'x=:' and the result
                       ,:              Concatenate the two rows

```

# Answer
> 3 votes
# Ruby, 65

```
x=1.0
puts"x=#{x/2+1/x}",<<'1'*2,1
puts"x=#{x/2+1/x}",<<'1'*2,1
1

```

As too often happens, this is almost a straight port of the Python solution.

# Answer
> 1 votes
# Perl 5, (`-M5.01`) 58 bytes

```
$x=1.;$_=q(say'$x='.($x/2+1/$x).qq(;\$_=q($_);eval));eval

```

Try it online!

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


title: Draw a big ASCII X

text:
# Question
Title: Draw a big ASCII X
# Problem

Inspired by a previous challenge doing something similar

Given positive integer input `n` output a shape that follows this pattern:

input `n=1`:

```
* *
 *
* *

```

input `n=2`:

```
**  **
 ****
  **
 ****
**  **

```

input `n=3`:

```
***   ***
 *** ***
  *****
   ***
  *****
 *** ***
***   ***

```

and so on...

It has these properties:

`n*2+1` lines tall

the "arms" are `n` wide except when they merge

the center line is `n` wide

if `n` is even the lines above and below the center are `n*2` wide

if `n` is odd the lines above and below the center are `n*2-1` wide

# Rules

* Trailing newlines accepted
* Standard loopholes apply
* **Shortest bytes win**
* Output may be print out or a string or array of strings

# Edits

* `n=0` doesn't need to be handled
* Trailing spaces allowed

# Answer
> 10 votes
# Charcoal, ~~13~~ 12 bytes

Thanks to @ErikTheOutgolfer for a byte

```
ＦＮ«ＰX⁺*×*Ｉθ→

```

Try it online!

This is my first ever Charcoal answer, and I'm pretty sure it's not golfed as well as it could be, but I figured I'd start somewhere.

```
 ＦＮ«            # For input() (i in range(0,input()))
     Ｐ           # Print
       X          # In an 'X' shape
        ⁺*×*Ｉθ   # '*'+'*'*int(first_input)
               →  # Move the cursor right one

```

# Answer
> 14 votes
# MATL, 16 bytes

```
EQXyG:Y+tP+g42*c

```

**Try it online!**

### Explanation

Consider input `2` as an example. Stack contents are shown with more recent ones below.

```
EQ    % Implicitly input n. Push 2*n+1
      %   STACK: 5
Xy    % Identity matrix of that size
      %   STACK: [1 0 0 0 0;
                  0 1 0 0 0;
                  0 0 1 0 0;
                  0 0 0 1 0;
                  0 0 0 0 1]
G:    % Push [1 2 ... n]
      %   STACK: [1 0 0 0 0;
                  0 1 0 0 0;
                  0 0 1 0 0;
                  0 0 0 1 0;
                  0 0 0 0 1],
                 [1 2]
Y+    % 2D convolution, extending size
      %   STACK: [1 2 0 0 0 0;
                  0 1 2 0 0 0;
                  0 0 1 2 0 0;
                  0 0 0 1 2 0;
                  0 0 0 0 1 2]
tP+   % Duplicate, flip vertically, add
      %   STACK: [1 2 0 0 2 1;
                  0 1 2 1 2 0;
                  0 0 1 4 0 0;
                  0 1 2 1 2 0;
                  1 2 0 0 1 2]
g     % Convert to logical
      %   STACK: [1 1 0 0 1 1;
                  0 1 1 1 1 0;
                  0 0 1 1 0 0;
                  0 1 1 1 1 0;
                  1 1 0 0 1 1]
42*   % Multiply by 42.
      %   STACK: [42 42  0  0 42 42;
                   0 42 42 42 42  0;
                   0  0 42 42  0  0;
                   0 42 42 42 42  0;
                  42 42  0  0 42 42]
c     % Convert to char. Char 42 is '*'. Char 0 is displayed as space
      %   STACK: ['**  **';
                  ' **** ';
                  '  **  ';
                  ' **** ';
                  '**  **']

```

# Answer
> 9 votes
# Jelly, 15 bytes

```
Ḥ‘Ḷ⁶ẋ;€”*ẋ$»Ṛ$Y

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 18 bytes

```
Å4bS{I·ƒDÂ~„ *èJ,À

```

Try it online!

**Explanation**

Example for `n=2`

```
Å4                   # push a list of 4s with length as the input
                     # STACK: [4,4]
  b                  # convert each to binary
                     # STACK: [100, 100]
   S{                # split into digit list and sort
                     # STACK: [0, 0, 0, 0, 1, 1]
     I·ƒ             # input*2+1 times do
        D            # duplicate top of stack
                     # 1st iteration: [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1]
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0]
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0]
         Â~          # or each item in the duplicate with its reverse
                     # 1st iteration: [0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1]
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0]
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0]
           „ *èJ     # use the resulting binary list to index into the string " *"
                     # 1st iteration: [0, 0, 0, 0, 1, 1], "**  **"
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], " **** "
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], "  **  "
                ,    # print
                 À   # rotate list left

```

# Answer
> 4 votes
# , ~~18~~ 17 bytes

Saved a byte thanks to @DJMcMayhem's input trick.

```
Àé*ÄJÀälÀñ2ÙÀl2x>

```

Try it online!

Explanation

```
Àé*ÄJÀäl

```

This inserts `[n]*'*'+[n]*' '+[n]*'*'`

```
        Àñ        ' [arg] times
          2Ù      ' Duplicate the current line down twice
            Àl    ' Move right [arg] times
              2x  ' Delete two characters
                > ' Indent this line one space

```

Each iteration of the loop the buffer goes from

```
|**   ***

```

To

```
***   ***
 |** ***
***   ***

```

Where `|` is the cursor with a `*` under it

# Answer
> 3 votes
# Haskell, 88 87 86 bytes

-1 thanks to @Laikoni

```
(!)=replicate
x n=[zipWith max(reverse m)m|m<-[i!' '++n!'*'++(n*2-i)!' '|i<-[0..n*2]]]

```

Try it online!

# Answer
> 3 votes
# , 23 bytes

```
Àé*ÄJÀälÀñÙãlxx>ñyHæGVp

```

Try it online!

Hexdump:

```
00000000: c0e9 2ac4 4ac0 e46c c0f1 d9e3 6c78 783e  ..*.J..l....lxx>
00000010: f179 48e6 4756 70                        .yH.GVp

```

For whatever reason, this challenge is significantly harder in V than the last one. Since our general approach of *n times, grow an 'x'* won't work here, we'll instead construct the top of the X, copy it and flip it, then attaching the two parts together.

Explanation:

```
Àé*ÄJÀäl                " Insert ('*' * n) + (' ' * n) + ('*' * n)
                        " The obvious way would be 'Àé*ÀÁ ÀÁ*', but this
                        " non-obvious way saves us a byte
        Àñ      ñ       " 'n' times:
          Ù             "   Duplicate this line (below us)
           ãl           "   Move to the center of this line
             xx         "   Delete two characters
               >        "   And indent this line with one space.

```

Doing the indent at the *end* of the loop, allows us to take advantage of implicit endings. This also conveniently creates *n+1* lines, which is exactly the top half of the 'X'. Let's say the input was 4. Then at this point, the buffer looks like this:

```
****    ****
 ****  ****
  ********
   ******
    ****

```

And we're on the last line. So then we:

```
                yH      " Copy the whole buffer and move to the first line
                  æG    " Reverse every line
                    Vp  " And paste what we just copied *over* the current
                        " line, deleting it in the process

```

# Answer
> 3 votes
# C#, 139 130 115 bytes

-1 byte by creating a string and calling `WriteLine`, thus saving the check for the new line.
-6 bytes thanks to Kevin and his master golfing techniques!
-2 bytes by replacing `n*3-n` with `n*2`.
-15 bytes after Kevin kindly pointed me in the right direction: I can just return the string instead of printing it, thus saving the call to `System.Console.WriteLine()`. And some other tips also...

```
n=>{var s="";for(int i,j=0;j<=n*2;j++,s+='\n')for(i=0;i<n*3;)s+=i>=j&i<j+n|i<=n*3-j-1&i++>=n*2-j?'*':' ';return s;}

```

Try it online!

Ungolfed:

```
class Program
{
    static void Main(string[] args)
    {
        System.Func<int, string> g = n =>
        {
            var s = "";
            for (int i, j = 0; j <= n*2; j++, s += '\n')
                for (i = 0; i < n*3;)
                    s += i >= j & i < j+n | i <= n*3-j-1 & i++ >= n*2-j ? '*' : ' ';
            return s;
        };

        System.Console.Write(f(1));
        System.Console.Write(f(2));
        System.Console.Write(f(3));
        System.Console.Write(f(5));
        System.Console.Write(f(8));

        System.Console.ReadKey();
    }
}

```

It just iterates along the rows and columns of the space needed to print the big X and prints either a `'*'` or a `' '` depending on the condition.

# Answer
> 2 votes
# Jelly, ~~24~~ ~~23~~ 16 bytes

```
Ḥ‘Ḷ⁸+þṬ+Ṛ$a”*o⁶Y

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~93~~ ~~90~~ ~~89~~ 83 bytes

-3 bytes thanks to Leaky Nun
-1 byte thanks to Zachary T
-6 bytes thanks to xnor

```
n=input()
x=n*'*'+n*'  '
exec"print`map(max,x,x[::-1])`[2::5];x=' '+x[:-1];"*(n-~n)

```

\[Try it online!\]\[TIO-j3xwsktf\]

Starts with a string like `'*** '` for `n=3`, applying `map/max` to pick the `*` over the spaces for each position, then append a space and remove the last character from the string and do this all again.

# Answer
> 2 votes
# MATLAB, 153 126 bytes (17.6%↓)

Thanks to @LuisMendo's comment, function `disp()` can output chars without single quotes, thus I could prevent using `fprintf` with `formats` and omit a few bytes. Besides, his comment reminds me that I need use `char(32)` to present a space rather than `char(0)` (null).

```
n=input('')
r=2*n+1
c=3*n
a=0
for i=0:n-1
a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)];
end
a((a+flipud(a))>0)=10
disp([a+32 ''])

```

Try it online!

### MATLAB, 153 bytes

```
n=input('')
r=2*n+1
c=3*n
a=0
for i=0:n-1
a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)];
end
a((a+flipud(a))>0)=42
fprintf([repmat('%c',1,c),'\n'],char(a)')

```

Result example: n=10

```
**********          **********
 **********        **********
  **********      **********
   **********    **********
    **********  **********
     ********************
      ******************
       ****************
        **************
         ************
          **********
         ************
        **************
       ****************
      ******************
     ********************
    **********  **********
   **********    **********
  **********      **********
 **********        **********
**********          **********

```

# Answer
> 1 votes
# Haskell, 70 bytes

```
f n=[[last$' ':['*'|y<-[1..n],(c-n-y)^2==r^2]|c<-[1..3*n]]|r<-[-n..n]]

```

Try it online!

Outputs a list of strings.

For each position of row `r`, column `c`, uses a formula to determine whether it falls in one of the two diagonal bands and so is `*`.

# Answer
> 1 votes
# Javascript (ES2017), ~~155~~ 157 bytes

```
n=>[...e=[...Array(n+1)].map((a,i)=>[...d=((b=''.padEnd(n))[c='slice'](i)+'*'.repeat(n)+b[c](0,i))[c](n/2)].reverse().join``+d[c](n%1)),...e.reverse()[c](1)]

```

Returns an array of strings. I perform operations on arrays then mirror it. This could probably be optimized with matrices like the other answers, but I wanted to be unique.

Edit: As pointed out by Neil, for even values of `n`, the center line was not `n` wide, so I added a modulus to detect even/odd when slicing the column.

```
n=5
['*****     *****',
 ' *****   ***** ',
 '  ***** *****  ',
 '   *********   ',
 '    *******    ',
 '     *****     ',
 '    *******    ',
 '   *********   ',
 '  ***** *****  ',
 ' *****   ***** ',
 '*****     *****']

```

**Ungolfed**

```
n => {
  e = [...Array(n+1)].map((a, i) => {   // Create and iterate over array with n+1 elements
    b = ''.padEnd(n)                    // String of n spaces
    d = (b.slice(i) + '*'.repeat(n) + b.slice(0, i)).slice(n/2) // Create row string
    return [...d].reverse().join`` + d.slice(1) // Mirror and combine row horizontally
  })
  return [...e,...e.reverse().slice(1)] // Mirror and combine vertically
}

```

**Quadrant**

```
n=5
   *****
  *****
 *****
*****
****
***

```

**Mirrored Horizontally**

```
n=5
*****     *****
 *****   *****
  ***** *****
   *********
    *******
     *****

```

**Mirrored Vertically**

```
n=5
*****     *****
 *****   *****
  ***** *****
   *********
    *******
     *****
    *******
   *********
  ***** *****
 *****   *****
*****     *****

```

# Answer
> 1 votes
# Java 10, ~~119~~ ~~118~~ 111 bytes

```
n->{var r="";for(int i=0,j;i<n-~n;i++,r+="\n")for(j=0;j<n*3;r+=j>=i&j<i+n|j<n*3-i&++j>n*2-i?"*":" ");return r;}

```

Port from *@CarlosAlejo*'s amazing C# answer, after I helped him golf a few things. **So make sure to upvote him as well!**
-4 bytes thanks to *@ceilingcat*.

Try it here.

# Answer
> 0 votes
# Mathematica, 148 bytes

```
T=Table;(a=Join[T[T["*",i],{i,(n=#)+2,2n,2}],T[Join[t=T["*",n],T[" ",y],t],{y,1,n,2}]];Column[Row/@Join[Reverse@a,{T["*",n]},a],Alignment->Center])&

```

# Answer
> 0 votes
## R, 102 bytes

Code:

```
n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M)

```

Test:

```
> n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M)
1: 10
2:
Read 1 item
**********          **********
 **********        **********
  **********      **********
   **********    **********
    **********  **********
     ********************
      ******************
       ****************
        **************
         ************
          **********
         ************
        **************
       ****************
      ******************
     ********************
    **********  **********
   **********    **********
  **********      **********
 **********        **********
**********          **********

```

# Answer
> 0 votes
## CJam, 24 bytes

```
{:T2*){S*T'**+}%_W%..e>}

```

This is a block that takes a number from the stack and outputs a list of lines to the stack.

### Explanation:

```
{                        e# Stack:           | 2
 :T                      e# Store in T:      | 2, T=2
   2*                    e# Multiply by 2:   | 4
     )                   e# Increment:       | 5
      {                  e# Map over range:  | [0
       S                 e#   Push space:    | [0 " "
        *                e#   Repeat string: | [""
         T               e#   Push T:        | ["" 2
          '*             e#   Push char '*': | ["" 2 '*
            *            e#   Repeat char:   | ["" "**"
             +           e#   Concatenate:   | ["**"
              }%         e# End:             | ["**" " **" "  **" "   **" "    **"]
                _        e# Duplicate:       | ["**" " **" "  **" "   **" "    **"] ["**" " **" "  **" "   **" "    **"]
                 W%      e# Reverse:         | ["**" " **" "  **" "   **" "    **"] ["    **" "   **" "  **" " **" "**"]
                   ..e>  e# Overlay:         | ["**  **" " ****" "  **" " ****" "**  **"]
                       } e# End

```

# Answer
> 0 votes
# **Python 2**, 110 bytes

```
x=a=0
n=c=input()
while x<2*n+1:
    print ' '*a+'*'*n+' '*c+'*'*(2*n-2*a-c)
    x+=1
    a=n-abs(n-x)
    c=max(0, n-2*a)

```

This program breaks each line into 4 parts, first spaces, first stars, second spaces and then second stars. For each horizontal line of the X it calculates how many stars or spaces are needed for each of the 4 sections of the line, then constructs and prints that string.

# Answer
> 0 votes
# Retina, 144 bytes

```
.+
 $&$* $&$* $&

$`#$'¶
¶\d+$

( *)#( *)(\d+)
$1$3$**$2#$3$* #$2$3$**$1
( +)(\*+)( *)(# +#)\3\2\3 +
$3$2$1$4$1$2$3
+` (# +#)
$1
+` #...
#
##

```

Try it online! Explanation:

```
.+
 $&$* $&$* $&

```

Add 2n+1 spaces before the input value (one for each output line).

```
$`#$'¶

```

Replace each space with a `#` and collect the results. This gives a diagonal line of `#`s, space padded on both sides, with the input value suffixed.

```
¶\d+$

```

Delete the original input value, as we now have a copy on each line.

```
( *)#( *)(\d+)
$1$3$**$2#$3$* #$2$3$**$1

```

Build up two diagonal lines of n `*`s, with a separator column of `n` spaces wrapped in a pair of `#`s.

```
( +)(\*+)( *)(# +#)\3\2\3 +
$3$2$1$4$1$2$3

```

On those lines where the `*`s are nearer the middle, swap the two halves around. This gives an appearance resembling `> | | <`.

```
+` (# +#)
$1

```

Move the `| |`s as far left as they will go, giving a sort of `>> > <` appearance.

```
+` #...
#

```

For each space between the `#`s, delete the three following characters. This joins the `> <` into an `X`.

```
##

```

Delete the now unnecessary `#`s.

# Answer
> 0 votes
# 05AB1E, 16 bytes

```
ENI>1})¦'*…×82SΛ

```

Try it online.

**Explanation:**

```
E      # Loop N in the range [1, (implicit) input]:
 N     #  Push loop-index N
  I>   #  Push the input, and increase it by 1
    1  #  Push 1
})     # After the loop: wrap all values on the stack into a list
  ¦    # And remove the very first 1
'*    '# Push "*"
…×82S  # Push "×82" as list: ["×",8,2]
Λ      # Use the Canvas builtin with these three arguments
       # (after which it is output implicitly)

```

*Canvas explanation:*

The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the list we generate at the start with the loop. For an input \\$n=3\\$, the list will look like this: \\$\[4,1,2,4,1,3,4,1\]\\$ (or more in general: for sequence \\$x\_n\\$ in \\$\[2,n\]\\$, the list will be \\$\[n+1,1,x\_1,n+1,1,x\_2,n+1,1,x\_3,...\]\\$).
2. The string to 'draw', which in this case is `"*"`.
3. The directions, which in this case is `["×",8,2]`. These will be the directions `[cross, reset-to-origin, →]`.

With these arguments, it will draw as follows (let's take the \\$n=3\\$ as example again):

```
Draw an X-shaped cross of character "*" with arms of length 4:
*     *
 *   *
  * *
   *
  * *
 *   *
*     *

Reset back to the origin (8), and draw 2-1 characters "*" in direction 2 (→):
(NOTE: The origin is the center of this first cross.)
*     *
 *   *
  * *
   **
  * *
 *   *
*     *

Draw an X-shaped cross of character "*" with arms of length 4 again:
**    **
 **  **
  ****
   **
  ****
 **  **
**    **

Reset back to the origin (8), and draw 3-1 characters "*" in direction 2 (→):
**    **
 **  **
  ****
   ***
  ****
 **  **
**    **

Draw an X-shaped cross of character "*" with arms of length 4 again:
***   ***
 *** ***
  *****
   ***
  *****
 *** ***
***   ***

```

See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Largest monetary amount impossible to make with two types of coin
Suppose we have two different types of coin which are worth relatively prime positive integer amounts. In this case, it is possible to make change for all but finitely many quantities. Your job is to find the largest amount that cannot be made with these two types of coin.

## Task

Input: A pair of relatively prime integers \\$(a,b)\\$ such that \\$1\<a\<b\\$.

Output: The largest integer that cannot be expressed as \\$ax+by\\$ where \\$x\\$ and \\$y\\$ are nonnegative integers.

## Scoring:

This is code golf so shortest answer in bytes wins.

## Example:

Input \\$(3,11)\\$

\\$4\cdot 3- 1\cdot 11=1\\$, so if \\$n\geq 22\\$ we can write \\$n=q\cdot 3 + 2\cdot 11 +r\\$ where \\$q\\$ is the quotient and \\$r\in\\{0,1,2\\}\\$ the remainder after dividing \\$n-22\\$ by \\$3\\$. The combination \\$(q+4r)\cdot 3 + (2-r)\cdot 11 = n\\$ is a nonnegative combination equal to \\$n\\$. Thus the answer is less than \\$22\\$. We can make \\$21=7\cdot 3\\$ and \\$20=3\cdot 3 + 1\cdot 11\\$ but it's impossible to make \\$19\\$ so the output should be \\$19\\$.

## Test Cases:

```
[ 2,  3] => 1

[ 2,  7] => 5

[ 3,  7] => 11

[ 3, 11] => 19

[ 5,  8] => 27

[ 7, 12] => 65

[19, 23] => 395

[19, 27] => 467

[29, 39] => 1063

[ 1,  7] => error / undefined behavior (inputs not greater than one)

[ 6, 15] => error / undefined behavior (not relatively prime).

[ 3,  2] => error / undefined behavior (3 > 2)

[-3,  7] => error / undefined behavior (-3 < 0)

```

# Answer
> 15 votes
# , ~~7~~,~~6~~ 3 bytes

-1 byte thanks to FrownyFrog !

-3 bytes thanks to Grimmy!

```
*-+

```

Try it online!

```
     -    subtract
      +   the sum of the arguments
    *     from their product

```

# Answer
> 10 votes
# Husk, 4 bytes

```
←¤*←

```

Try it online!

# Explanation

As proved in lots of places, the answer for inputs `a` and `b` is `ab-a-b = (a-1)(b-1)-1`. `¤` is the 'combine' combinator, so `¤*←` is a function that applies  (decrement) to each argument and 'combines' the results by multiplication. Then I decrement the result to get the final output.

# Answer
> 9 votes
# Wolfram Language (Mathematica), 8 bytes

```
1##-+##&

```

Try it online!

---

# Wolfram Language (Mathematica), 15 bytes

```
FrobeniusNumber

```

Try it online!

# Answer
> 7 votes
# 05AB1E, 3 bytes

```
<P<

```

Try it online!

```
<         # decrement both inputs
 P        # product
  <       # decrement

```

# Answer
> 4 votes
# Perl 6, ~~43~~ 13 bytes

```
(*-1)*(*-1)-1

```

Try it online!

Turns out there's a much shorter way to calculate the answer.

# Perl 6, 43 bytes

```
->\a,\b{max ^(a*b)∖((a X*^b)X+(^a X*b)):}

```

Try it online!

# Answer
> 4 votes
# Python 3, 18 bytes

```
lambda a,b:a*b-a-b

```

Try it online!

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

```
×-+

```

Try it online!

Dyadic train where `a f b` computes `(a×b)-(a+b)`.

# Jelly, 3 bytes

```
×_+

```

Try it online!

Dyadic link that takes two numbers `a` and `b` as left and right arguments. Works the same as the APL version, just with the symbol `_` instead of `-` to represent subtraction.

# Answer
> 3 votes
# C (clang), <sup>~~31~~</sup> 22 bytes

```
f(a,b){return~-a*b-a;}

```

Try it online!

Saved 9 bytes thanks to ceilingcat!!!

# Answer
> 3 votes
# Jelly, 3 bytes

```
P_S

```

Try it online!

A monadic link taking a pair of integers. Same method as most other answers (product minus sum).

# Answer
> 3 votes
# Pyth, 5 bytes

```
-*FQs

```

Try it online!

Product minus sum.

```
t*FtM

```

Try it online!

a,b -\> (a-1)\*(b-1)-1

# Answer
> 2 votes
# Pyth, ~~8~~ 7 bytes

```
t*thQte

```

Try it online!

Uses the formula (a-1)(b-1) - 1. Takes input as a Python array of 2 integers.

-1 by using implicit appended Q

# Answer
> 2 votes
# C (gcc), 18 bytes

```
f(a,b){a=~-a*b-a;}

```

Noodle9's answer except using `a=` instead of `return`.

Try it online!

# Answer
> 2 votes
# Java 8, 13 bytes

```
a->b->a*b-a-b

```

Try it online.

**Explanation:**

Similar as most other answers, it calculate the product minus the sum:

```
a->b->         // Method with two integer parameters and integer return-type
      a*b      //  Return the two parameters multiplied by each other,
         -a-b  //  after we've also subtracted both parameters from this product

```

# Answer
> 2 votes
# Whitespace, 59 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S N
S _Duplicate_input][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S T S S T   S N
_Copy_0-based_2nd][T    S S N
_Multiply_top_two][S N
T   _Swap_top_two][T    S S T   _Subtract_top_two][S N
T   _Swap_top_two][T    S S T   _Subtract_top_two][T    N
S T _Print_as_integer_to_STDOUT]

```

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

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

**Explanation in pseudo-code:**

```
Integer a = STDIN as integer
Integer b = STDIN as integer
Integer c = a * b
c = c - a - b
Print c as integer to STDOUT

```

Not much golfing involved, except for using the first input as heap-address for the second input, since it's guaranteed to be positive and we push it to stack right away.

# Answer
> 1 votes
# Japt, 4 bytes

```
×-Ux

```

Try it here

# Answer
> 1 votes
# Keg, 5 bytes

```
*¿¿+-

```

Simply a port of other answers. Uses latest github interpreter.

# Answer
> 1 votes
# Excel, 12 bytes

```
=A1*B1-A1-B1

```

Same approach as other answers.

# Answer
> 1 votes
# JavaScript (V8), 13 bytes

```
a=>b=>a*b-a-b

```

Try it online!

Same solution as other answers, I almost didn't post it but for once I found a question without a JS answer, so may as well. In fact this is the exact same as Kevin Cruijssen's answer, replacing Java's lambda `->` with Javascript's `=>`. I've included a very basic testing framework in my TIO link so it does all the test cases. Most invalid inputs still execute.

# Answer
> 1 votes
# Brainf\*ck, 36 bytes

Cell layout: cells 1 and 2 are input, cell 3 is where the final answer is built, cell 4 is auxiliary

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

```

Or, with words:

```
,-               read a and decrement
>                move to cell 2
,-               read b and decrement
<                move back to a
 [-              while a isn't 0, decrement once and
  >              move to b (to add b to cells 3 and 4)
  [-             decrement b
   >+>+<<        add 1 to cells 3 and 4, go back to b
  ]
  >>             move to cell 4
  [-<<+>>]       copy cell 4 to cell 2 (i.e. put b again in cell 2
 <<<             move back to a
 ]
>>-.             go to cell 3, decrement and output

```

Try it online \- this is not a link to tio.run. In this site I linked I was able to give input as `\02\05` so that I could try smaller test cases, and I also get a "memory dump" to check the weird characters that were printed actually correspond to the answer.

Here, have a tio.run link as well.

# Answer
> 1 votes
# AWK, 14 bytes

```
$0=$1*$2-$1-$2

```

Try it online!

Assumes input in the form of `x y`.

# Answer
> 0 votes
# , 11 7 bytes

```
a*b-a-b

```

Where `a` and `b` are the 2 numbers.

Thanks to Jo King for pointing out my error.

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