# Question
Title: Write a program that prints a program that's almost quine
Your task is to make a program in `L` that takes `n` as an input number, output a program `p` in `L` that prints its own first `n` characters.

## Rules

* The program `p` has to be irreducible, See an example below.
* **PAY ATTENTION TO THIS RULE:** If a program takes an input as `n`, the first `n` characters of the output would be the same as the first `n` characters of the program taking `n + 1` as input.
* Standard loopholes apply
* You have to make a full program.
* A trailing newline of the output of the program `p` is allowed if the first `n` characters of the program `p` doesn't have a newline

## Example

I'm using pseudocode as `L`

if `n` = 10, an example of `p` would be

```
PRINT "PRINT \"PRI"

```

but not

```
// comment
PRINT "// comment"

```

because it breaks the first rule above (if you removed `com` and still makes the same output).

This is , so you have to make your program shortest as possible (in bytes).

# Answer
> 7 votes
# Charcoal, 1 byte

Try it online! Port of @Ausername's Vyxal answer. Explanation: Simply outputs `n` `-`s; strings of printable ASCII need no delimiter in Charcoal, so as a program, it just prints the string of `-`s, i.e. itself.

# Answer
> 6 votes
# Raku, ~~20~~ 18 bytes

```
say 1 x get,".put"

```

Try it online!

Outputs a number with `n` digits followed by a `.put`

# Answer
> 4 votes
# Python 3, 48 bytes

```
print('a'*int(input())+'=1;print(locals()[-1])')

```

Try it online!

# Answer
> 3 votes
# Vyxal, 3 bytes

```
\1*

```

Try it Online! Literally prints that many 1s.

# Answer
> 3 votes
# Retina, 13 bytes

```
.+
*KKK
KK
K`

```

Try it online! Explanation: Outputs a string of length `n+2` alternating between `K` and ```. This creates a program in Retina that outputs the part of the string after the `K`` which is also equal to the first `n` characters of the program. Retina can also execute the resulting program for you automatically: Try it online! Or see both the program and its output: Try it online!

# Answer
> 3 votes
# Ruby, 26 bytes

```
$><<?1*gets.to_i+'=>x;p x'

```

Uses the Ruby 3 pattern match syntax to bind the integer to `x`.

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
1¸sиJ

```

Try it online!

Sort-of port of emanresu A's Vyxal answer:

```
1¸sиJ  # Implicit input                 STACK:
1¸     # Push ['1']                     ['1'], 5
  sи   # Repeat input number of times   ['1', '1', '1', '1', '1']
    J  # Join by ''                     '11111'
       # Implicit output

```

# Answer
> 0 votes
# Julia 1.0, 36 bytes

```
print('1'^parse(Int,ARGS[]),|>,show)

```

Try it online!

port of Jo King's answer

will print something like `1111|>show` (equivalent to `show(1111)`)

# Answer
> 0 votes
# ///, 65 bytes

```
/9/8*//8/7*//7/6*//6/5*//5/4*//4/3*//3/2*//2/1*//1/0*//*0/9*//0//

```

Try it online!

Converts decimal to unary.

# ///, 0 bytes

Try it online!

Takes input as unary. For me, That's cheating.

# Answer
> 0 votes
# Bash, 25 bytes

```
eval echo\ echo\$_{0..$1}

```

Attempt This Online!

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


# Question
Title: How many times will you have to golf a quine?
For this challenge, you must create a programme which takes an integer `x` and outputs its source `x` many times.

**Rules**

* This is codegolf, the aim is to golf your programme to have the least amount of bytes
* If you submit a function, the function must take `x` as a parameter and either return or print the entirety of your code `x` many times to STDOUT. The function body must also not be empty
* If you submit a lambda, it is not required for you to assign it to a variable
* Standard loophole restrictions apply.
* Empty programmes are forbidden
* Your programme only has to work when `x` is a whole integer larger than or equal to 0
* Your programme may also not directly read any part of its source code

# Answer
# Python 2, 50 bytes

Note the trailing comma and newline.

```
s='s=%r;print s%%s*input(),\n';print s%s*input(),

```

Try it online!
> 8 votes

# Answer
# Japt, 14 bytes

```
"iQ ²pU"iQ ²pU

```

Try it online!

# Explanation

```
"iQ ²pU"iQ ²pU
"iQ ²pU"       # Take this string
        iQ     # Prepend a quote
           ²   # Double the string (= source code)
            pU # Duplicate input times

```
> 6 votes

# Answer
# RProgN 2, 8 bytes

```
{`{.*¶}{

```

The RProgN2 Loop quine works particularly well for this!

```
{     } # A function literal
       {# Without a matching }, this loops back to the second instruction, which essentially runs the function. This is a bug, but it works to make the "Looping Quine".
 `{.    # Append the literal {, stringifying the function.
    *   # Multiply the stringified function by the input.
     ¶  # Terminate the program.

```

Try it online!
> 5 votes

# Answer
# Mathematica, ~~40~~ 33 bytes

*Thanks to lanlock4 for saving 7 bytes!*

```
StringRepeat[ToString[#0], #1] &

```

Pure function taking a nonnegative integer argument. `ToString[#0]` is the standard Mathematica way to access the current pure function's definition; `StringRepeat[..., #1]` concatenates (input) copies of that string together. For example,

```
StringRepeat[ToString[#0], #1] & [2]

```

yields:

```
StringRepeat[ToString[#0], #1] & StringRepeat[ToString[#0], #1] &

```
> 4 votes

# Answer
# Python 2, 70 bytes

This solution works if `x=0`. There is a single trailing newline.

```
s='s=%r;exec"print%%r;"%%(s%%s)*input()';exec"print%r;"%(s%s)*input()

```

**Try it online**

---

## Python 2, 60 bytes (invalid)

This assumes that `x>=1`, but the OP clarified that `x` can be zero. There is a single trailing newline.

```
s='s=%r;print(s%%s*input())[:-1]\n';print(s%s*input())[:-1]

```

**Try it online**
> 4 votes

# Answer
# , 11 bytes

```
ÀñAÀÑ~"qpx

```

Try it online!

This is an extremely trivial modification of the standard extensible V quine. We simply use `À` to run it *arg1* times.
> 3 votes

# Answer
# dc, 31 bytes

```
[[1-rd91Pn93P[dx]Pdx]s.rd0<.]dx

```

Try it online!

Explanation:

```
[[1-rd91Pn93P[dx]Pdx]s.rd0<.]dx
[     91Pn93P[dx]P          ]dx  # Same old regular quine
 [1-rd            dx]s.rd0<.     # Loop until the counter is zero

```
> 3 votes

# Answer
# Japt, 14 bytes

```
*E îQi"*E îQi"

```

Try it online!
> 3 votes

# Answer
# Underload, 12 bytes

```
(a(:^)*~^):^

```

Try it online!

Function submission, because Underload has no other way to take input. (The TIO link shows the number 4 given as input, and adds code to print the resulting output).

This is just a universal quine constructor `(a(:^)*):^`, plus `~^` ("make a number of copies equal to the argument").
> 2 votes

# Answer
# 05AB1E, 23 bytes

```
"34çìDJ¹.D»"34çìDJ¹.D»

```

Try it online!
> 2 votes

# Answer
# Python 2, 41 bytes

```
_="input('_=%r;exec _'%_*input())";exec _

```

Try it online!

Does a kinda hacky output using `input` instead of `print`, since `print` has a weird bug involving printing a newline when it isn't supposed to.... Exits with an EOF error.

### Explanation:

```
_="input('_=%r;exec _'%_*input())"; # Set _ to a string
exec _                              # Execute that string
input(                        )     # "print"
      '_=%r;exec _'%_               # The source code with _ formatted in
                     *input()       # Actual input many times

```
> 2 votes

# Answer
# CJam, ~~20~~ 12 bytes

8 bytes saved thanks to Martin Ender

```
{"_~"+ri*}_~

```

Try it online!

### Exaplanation

```
{       e# Begin a block literal:
 "_~"+  e#  Add whatever's on the stack to the beginning of the array ['_', '~'].
 ri*    e#  Repeat the resulting array a number of times equal to the input.
}       e# Close the block. Push it on the stack.
_~      e# Copy it and run it.

```
> 1 votes

# Answer
# Jelly, 10 bytes

```
“;⁾vṾẋɠ”vṾ

```

Try it online!

### How it works

```
“;⁾vṾẋɠ”vṾ  Main link. No arguments.

“;⁾vṾẋɠ”    Set the argument and the return value to the string ';⁾vṾẋɠ'.
         Ṿ  Uneval; yield '“;⁾vṾẋɠ”'.
        v   Eval ';⁾vṾẋɠ' with argument '“;⁾vṾẋɠ”'.
  ⁾vṾ           Yield 'vṾ'.
 ;              Concatenate '“;⁾vṾẋɠ”' and 'vṾ', yielding the source code.
      ɠ         Read an integer from STDIN.
     ẋ          Repeat the source code that many times.

```
> 1 votes

# Answer
# GNU Make, 49 bytes

```
$(foreach ,$(shell seq $1),$(strip $(value $0)))

```

Make will join the copies by a single space, so I have to include the additional space character at the end and remove it with a `strip` in between in order to follow the requirement faithfully.
> 1 votes

# Answer
# Pyth, 17 bytes

```
j*]jN*2]"j*]jN*2]

```

Try it online!

Trivial extension to the pretty-well-known `jN*2]"jN*2]` quine, but can probably be golfed down
> 1 votes

# Answer
## Betaload, 203 bytes

Newlines added for clarity:

```
(a(:^)*(!()):#(}:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*{)>(0)(!()){:^}(1)(){:^}(2)(:*){:^}(
3)(::**){:^}(4)(:*:*){:^}(5)(::*:**){:^}(6)(:*::**){:^}(7)(::*::***){:^}(8)(:*:*:*){:^}(9)(
::**::**){:^}R^^S):^

```

I gave myself the restriction that it must read from STDIN rather than from the top of the stack like an Underload answer typically would. I also used proper, decimal input, which makes up most of the code.

### Explanation:

I wrap the program up in a quine-wrapper: `(a(:^)*` and `):^`. This means all code inside the quine wrapper will have the program's source code at the bottom of the stack.

In order to convert digits into a normal Church numeral, I use the technique of replacing each digit with the code to multiply by 10 and add that digit:

```
0 -> (::*:**:*)*
1 -> (::*:**:*)*(:)~*(*)*
2 -> (::*:**:*)*(::)~*(**)*
3 -> (::*:**:*)*(:::)~*(***)*

```

There's a lot of repetition here, so let's package it up into a subprogram that will take a Church numeral from the top of the stack and use it to construct the "digit string:"

```
:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*

```

I put this into a new environment so that it can be accessed quickly:

```
#(}:(:)~^a((::*:**:*)*)~*(~*)*~(*)~^a*(*)*{)>

```

Now I can create the replacement code for `R`. `R` uses the top elements of the stack to form a lookup table to replace a string from STDIN with Betaload code. It works like this:

```
()
(0)(code for 0)
(1)(code for 1)
(2)(code for 2)
...
R

```

However, we can use the subprogram we just made to generate the code segments:

```
(0)(!()){:^}
(1)(){:^}
(2)(:*){:^}
(3)(::**){:^}
...

```

When `R` is run, it will transform the input into a series of subprograms that build up a Church numeral. When this subprogram is executed, it creates that Church numeral on the next element on the stack (0, which was placed down earlier). This means that, after `R^`, the top value on the stack will be the Church numeral. We then `^` one more time to apply the Church numeral to the final element in the stack (the program's source code) to get the answer.

Fun fact: I've had the MD for this submission for several months. I'd kept it after misunderstanding a question (that I can't seem to find anymore). I had to dig it up from my Recycle Bin to post it here.
> 1 votes

# Answer
## Perl, 48 bytes

```
print"$_\47"x(2*pop)for'print"$_\47"x(2*pop)for'

```

`\47` is the octal escape for a single quote (`'`). It is interpreted inside double quotes (`"`), but not inside single quotes.
> 1 votes

# Answer
# Javascript ES6, ~~27~~ 37 bytes

```
_=>alert(`${f.name}=${f}`.repeat(_))

```

**Edit**

+10 bytes if `f=` should be also displayed

---

```
f=

_=>alert(`${f.name}=${f}`.repeat(_))

f(2);
```
> 1 votes

# Answer
# PHP, 194 bytes

```
<?php $a="PD9waHAgJGE9IiMiOyRpPSRhcmd2WzFdO3doaWxlKCRpLS0pZWNobyBzdHJfcmVwbGFjZShjaHIoMzUpLCRhLGJhc2U2NF9kZWNvZGUoJGEpKTs=";$i=$argv[1];while($i--)echo str_replace(chr(35),$a,base64_decode($a));

```

Try it online!

Not golfy at all, as b64 quines tend to be.
> 1 votes

# Answer
# Go, ~~257~~ 254 bytes

This pains me.

```
package main;import(."fmt";."strings";."strconv";."os");func main(){s:="package main;import(.\"fmt\";.\"strings\";.\"strconv\";.\"os\");func main(){s:=%q;n,_:=Atoi(Args[1]);Print(Repeat(Sprintf(s,s),n))}";n,_:=Atoi(Args[1]);Print(Repeat(Sprintf(s,s),n))}

```

Try it online!
> 1 votes

# Answer
# Microscript II, 22 bytes:

```
"v{lqp}sN*h"v{lqp}sN*h

```

# Microscript II, 20 bytes (but technically invalid as it accesses the source code of a code block):

```
{s""+`"~sN*"s`+}~sN*

```
> 1 votes

# Answer
# Python 3, 69 Bytes

```
s='s=%r\nx=int(input())\nprint(s%%s*x)\n'
x=int(input())
print(s%s*x)

```
> 1 votes

# Answer
# C, ~~144~~ 116 bytes

```
i;main(a){for(i=getchar()-48;i--;)printf(a="i;main(a){for(i=getchar()-48;i--;)printf(a=%c%s%c,34,a,34);}",34,a,34);}

```
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
0"D34çý×?"D34çý×?

```

Modification of the default `0"D34çý"D34çý` by adding `×?`.

Try it online.

**Explanation:**

```
0                   # Push 0 to the stack
                    #  STACK: [0]
 "D34çý×?"          # Push the string 'D34çý×?' to the stack
                    #  STACK: [0, 'D34çý×?']
          D         # Duplicate this string
                    #  STACK: [0, 'D34çý×?', 'D34çý×?']
           34ç      # Push '"' to the stack
                    #  STACK: [0, 'D34çý×?', 'D34çý×?', '"']
              ý     # Join the stack by this '"' delimiter
                    #  STACK: ['0"D34çý×?"D34çý×?']
               ×    # Repeat the string the (implicit) input amount of times
                    #  input = 2 → STACK: ['0"D34çý×?"D34çý×?0"D34çý×?"D34çý×?']
                ?   # Output to STDOUT without trailing newline

```
> 1 votes

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

```
n=>{var s="n=>{{var s={0}{1}{0};for(int i=0;i++<n;)Write(s,(char)34,s);}}";for(int i=0;i++<n;)Write(s,(char)34,s);}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~27~~ 25 bytes

```
"34çs«DJ¹FD,"34çs«DJ¹FD,

```

Try it online!
> 0 votes

# Answer
# Pyth, 13 bytes

```
*jN*2]"*jN*2]

```

Test suite

The standard Pyth quine plus two `*` for the repetition.
> 0 votes

# Answer
# Vyxal, 6 bytes

```
`I*`I*

```

Try it Online!

Quine cheese (סּ͡͡ ◞סּ͡͡ )

## Explained

```
`I*`I*
`I*`    # The string "I*"
    I   # with itself quoted, prepended
     *  # Repeated input times

```

Created with the help of Luminespire.
> 0 votes

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


title: How Many Paint Tins Do I Need?

text:
# Question
Title: How Many Paint Tins Do I Need?
# Task

Take in **3** inputs. The **length** of the wall, the **height** of the wall and the **coverage** of the paint. Output how many tins of paint are required.

# Output

Since there's no way to purchase `1/3` tin of paint, you'll need to round the amount of paint tins up to the nearest integer.

# Assumptions/Stipulations

* Only 1 coat of paint is required
* Round up in terms of paint tins required

# Test Cases

> Length: 20 meters | Height: 7 meters | Coverage: 12 meters = 12 tins of paint

| Input | Output |
| --- | --- |
| `1/1/10` | `1` |
| `5/5/10` | `3` |
| `2/3/8` | `1` |
| `5/8/8` | `5` |
| `45/5/18` | `13` |
| `20/7/12` | `12` |
| `1/1/1` | `1` |
| `200/10/14` | `143` |

## Current Winners! (28th November 2023)

Jelly - 3 bytes - Jonathan Allan https://codegolf.stackexchange.com/a/267131/91342

Uiua - 3 bytes - chunes https://codegolf.stackexchange.com/a/267109/91342

Vyxal 3 - 3 bytes - Nick Kennedy https://codegolf.stackexchange.com/a/267138/91342

APL - 3 bytes - Tbw https://codegolf.stackexchange.com/a/267134/91342

Vyxal - 3 bytes - Iyxal https://codegolf.stackexchange.com/a/267112/91342

# Answer
# Uiua,  ~~4~~  3 bytes

```
⌈×÷

```

Try it!

-1 thanks to alephalpha

Takes input in the order `coverage length height`

```
⌈×÷
  ÷  # divide first two args
 ×   # multiply by third
⌈    # ceiling

```
> 6 votes

# Answer
# Jelly, 3 bytes

```
P÷Ċ

```

A monadic Link that accepts the dimensions on the left and the paint tin coverage on the right and yields the number of tins required.

**Try it online!**

### How?

```
P÷Ċ - Link: Dimensions, Coverage
P   - product {Dimensions}
 ÷  - divide by {Coverage}
  Ċ - ceiling

```
> 6 votes

# Answer
# Vyxal 3, 3 bytes

```
÷×⌈

```

Try it Online!

Similar to most other answers. Divide by coverage, multiply by other dimension, take ceiling.
> 5 votes

# Answer
# APL (Dyalog Classic), 3 bytes

```
⌈÷/

```

Try it online!

Written as a tacit function that takes a vector with entries length, coverage, and height, in that order.

`÷/`, read as Divide Reduce, calculates `length ÷ coverage ÷ height`. Since APL evaluates right to left, this gives `length ÷ (coverage ÷ height) = (length × height) ÷ coverage`.  takes the ceiling of the result.
> 4 votes

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

```
(a,b,c)=>(a*b+c-1)/c|0

```

Try it online!

# JavaScript (Node.js), 20 bytes suggested by Arnauld

```
(x,y,z)=>~-(x*y+z)/z

```

Try it online!
> 3 votes

# Answer
# APL+WIN, 6 bytes

Prompts for three numbers. Coverage followed by wall dimensions:

```
⌈⎕×⎕÷⎕

```

Try it online! Thanks to Dyalog Classic
> 3 votes

# Answer
# Python 3.8 (pre-release), ~~25~~ 23 bytes

```
lambda l,h,c:-(-l*h//c)

```

Try it online!

---

Edit

* -2 bytes thanks to Neil
> 3 votes

# Answer
# Arturo, 15 bytes

```
$=>[ceil//&*&&]

```

Try it!

```
$=>[ceil//&*&&]
$=>[          ]  ; a function
          &*&    ; multiply first arg by second
        //   &   ; divide by third
    ceil         ; ceiling

```
> 3 votes

# Answer
# Scala 3, 20 bytes

```
(l,h,c)=>(l*h+c-1)/c

```

Attempt This Online!
> 3 votes

# Answer
# Charcoal, 8 bytes

```
Ｉ±÷×ＮＮ±Ｎ

```

Try it online! Link is to verbose version of code. Explanation: Port of @SevC\_10's Python answer.

```
    Ｎ       First input as a number
   ×        Multiplied by
     Ｎ      Second input as a number
  ÷         Integer divided by
       Ｎ    Third input as a number
      ±     Negated
 ±          Negated
Ｉ           Cast to string
            Implicitly print

```
> 3 votes

# Answer
# Retina 0.8.2, 39 bytes

```
.+
$*
1(?=1*¶(1+)¶)
$1
(1+)(?=1*¶1+¶\1)

```

Try it online! Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:

```
.+
$*

```

Convert to unary.

```
1(?=1*¶(1+)¶)
$1

```

Multiply only the first number by the second.

```
(1+)(?=1*¶1+¶\1)

```

Partition the first number into as few values as possible that do not exceed the third number and output the size of the partition.
> 3 votes

# Answer
# Japt, 5 bytes

```
×/V c

```

Try it here
> 3 votes

# Answer
# sclin, 6 bytes

```
/ * |^

```

Try it on scline! Takes input as `H L C`.
> 3 votes

# Answer
# Vyxal `r`, 3 bytes

```
*/⌈

```

Try it Online!

Hehehehe flag go brrrr
> 2 votes

# Answer
# PowerShell, 40 bytes

```
param($l,$h,$c)[math]::Ceiling($l*$h/$c)

```

Try it online!

Thanks Julian!

# PowerShell, 47 bytes

```
$c={param($l,$h,$c)[math]::Ceiling(($l*$h)/$c)}

```

Try it online!

Thought I'd throw my own suggestion in :-)
> 2 votes

# Answer
# C (gcc), <sup>~~27~~</sup> 24 bytes

```
f(l,h,c){l=(l*h+c-1)/c;}

```

Try it online!

*Saved 3 bytes thanks to Sisyphus!!!*
> 2 votes

# Answer
# Google Sheets, 18 bytes

```
=roundup(A1*B1/C1)

```

Put the input in cells `A1:C1`.

In Microsoft Excel, `roundup()` requires a second parameter (**19 bytes**):

```
=roundup(A1*B1/C1,)

```
> 2 votes

# Answer
# ARBLE, 11 bytes

```
ceil(l*h/c)

```

Not the most imaginative answer. Arguments as `coverage, height, length`

Try it online!
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
/*î

```

Inputs in the order \\$coverage,length,height\\$.

Try it online or verify all test cases.

**Explanation:**

```
/    # Divide the second (implicit) input length by the first (implicit) input coverage
 *   # Multiply it to the third (implicit) input height
  î  # Ceil it
     # (after which the result is output implicitly)

```
> 2 votes

# Answer
# MathGolf, 3 bytes

```
*╠ü

```

Inputs (as floats) in the same order as the challenge description: \\$length,height,coverage\\$.

Try it online.

**Explanation:**

```
*    # Multiply the first two (implicit) inputs: height*length
 ╠   # Divide it by the third (implicit) input: (height*length)/coverage
  ü  # Ceil it
     # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# Pyth, 34 bytes

```
K.Q)=+Z*@K0@K1;J0;W>Z0=-Z@K2=+J1;J

```

Try it online!

I just wanted to try out in `Pyth`. Unfortunately, `Pyth` doesn't support float division so, had to use `while` to do the trick.

#### Explanation

**K.Q)** \- get input in a newline, as in the question's order and store it as `list` in `K`

**\<Z** \- used to store the product of `length` and `height` i.e `area`

**W\>Z0=-Z@K2=+J1** \- used to iterate until the area isn't `0` and decrement the `area` by `coverage` (`@K2`); and increment `J` by `1`
> 1 votes

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


title: Abstract Rewriting Challenge (Robbers)

text:
# Question
Title: Abstract Rewriting Challenge (Robbers)
This is a somewhat -like challenge. This is the robbers' thread; the cops' thread is here.

# Robbers

The cops will post abstract rewriting systems. Your task is to crack their submissions by proving that the target string either can or can not be reached from the source string by applying their rewrite rules. (You can do this either by posting a sequence of rewrite rules that starts with the source string and ends with the target, or by proving mathematically that this does, or does not, exist.)

See the cops' thread for details and definitions.

# Answer
> 17 votes
# jimmy23013

Let's work backwards for this one. We first turn the digits into their binary representations. We go from `VW626206555675126212043640270477001760465526277571600601` to `VW++__+_++__+____++_+_++_++_+++_++++_+__+_+_++__+___+_+____+___++++_+______+_+++___+__++++++________++++++____+__++_+_++_+_+_++__+_+++++++_++++__+++_______++______+`. Next, we keep applying the inverse of `DCW:W+` and `DW:W_` until we clear all symbols. Our result is now `VDCDCDDDCDDCDCDDDCDDDDDCDCDDCDDCDCDDCDCDDCDCDCDDCDCDCDCDDCDDDCDDCDDCDCDDDCDDDDCDDCDDDDDCDDDDCDCDCDCDDCDDDDDDDCDDCDCDCDDDDCDDDCDCDCDCDCDCDDDDDDDDDCDCDCDCDCDCDDDDDCDDDCDCDDCDDCDCDDCDDCDDCDCDDDCDDCDCDCDCDCDCDCDDCDCDCDCDDDCDCDCDDDDDDDDCDCDDDDDDDCW`. We now want to make this string match `VD+C+W`; that is, we want to move all of the `D`s to the left of all of the `C`s. This can be done by reversing `DCC:CD`. We do this by repeating the following algorithm:

1. Find the first `D` that is to the right of a block of `C`s.
2. Move the `D` to the left of that block.
3. Double the number of `C`s.

Through some math, we can determine that we will end up with 123 `D`s and 4638704741628490670592103344196019722536654143873 `C`s (you were right about this not fitting in an SE answer... I doubt this would fit if stored as states of all of the atoms in the Earth combined :P).

If we keep applying the reverse of `V:VD`, we can get rid of all of the `D`s now, so we get `VCCC.......CCCW`. We convert the `V` back into `YZ`. Now we have `YZCCC.......CCCW`.

We want to be able to get rid of all of the `C`s and have it in the form `YAAA...AAABBB...BBBZW`. Fortunately, this can be done by the following method. Firstly, we inverse-apply `YB:Y` 587912508217580921743211 times to get `YBBB.......BBBZCCC.......CCCW`. Then, we repeat the following sequence of steps (where `[?*]` means any number of `?`, not necessarily greater than zero):

1. Inverse-apply `CZ:ZC` 587912508217580921743211 times to get `Y[A*]BBB.......BBBCCC.......CCCZCCC.......CCCW`
2. Inverse-apply `CB:BC` many times to get `Y[A*]BCBCBC.......BCBCBCZCCC.......CCCW`
3. Inverse-apply `AZ:Z` and `AB:BCA` many times to get `Y[A*]ABBB.......BBBZCCC.......CCCW`

Through induction, we see that we can move the `BZ` combination all the way to the end (except before the `W`) and then the number of `A`s is 1/587912508217580921743211 of the number of `C`s, leaving us with 7890127658096618386747843 `A`s. We now have `YAAA.......AAABBB.......BBBZW`. Convert the `ZW` back to a `U`, then inverse-apply `U:BU` many times to keep only 2 `B`s and then convert the `BBU` to a `T`, and you now have `YAAA.......AAAT`. Then, you can inverse-apply `T:AAAAAT` many times to get `YAAAT` because the number of `A`s was 3 larger than a multiple of 5.

Thanks for the challenge!

# Answer
> 10 votes
# feersum

This is a sokoban puzzle. The starting position is:

```
          ___#
#___####_____#
#_#_#_##_#_!##
##______##_###
##__####_#_###
###__###__

```

The ending position is:

```
          ___#
#___####_____#
#_#_#_##_#_###
##____!__#_###
##__####_#_###
###__###__

```

It can be solved using the following key sequence:

> ←←→↓↓←↑←←←←←←↓↓→↑←↑↑↑←←↓→↑→↓↓→→→→→→↓→↑↑↓↓←↓←↑→↑←←←←↑←←↓→→→→→↓→→↑↑→↑↑←↓←←↓↓→↑←↑→→↑→→↓←↓←←↓↓→↑←←←←←←←↑↑←←↓→→↓→↓↓←↑←↑→↑↑←←↓→↑→↓↓←↓→↑→→→→→→↓↓←↑→↑←←←←←←→→→→→→↑↑←↓→↓←↑↑→→↑→→↓←↓←→↑↑←↓←↓↑→→↓←↑←←↓↓↓→→↑↑↓↓←←↑↑→↓↑↑→↑→→↓←↓←↓←←↑↑→→↑→↓←↓↓←←←←←↑←←↓→→→→→←←←←←↑↑←←↓→→↓↓←↑→→→→

Here is a bash program that converts the key sequence to sed commands and applies them. The sed commands contains only replacing commands using the rewrite rules defined in the cop's answer, and labelling and branching commands that doesn't modify the string. It confirms that you can get the target string using only the rewrite rules.

```
s="___##___####_____##_#_#_##_#_!####______##_#####__####_#_######__###__"
input=

while
    printf '\n%80s\n' "$s"|fold -w14
    read -n 1
    [ "$REPLY" = $'\e' ]
do
    read -n 2
    case "$REPLY" in
    [A)
        s="$(sed '
s:!:wLW_:
        :a
s:L:<<<<<<<<<<<<<:
s:#w<:w#:
s:_w<:w_:
s:_<:<_:
s:#<:<#:
s:#wW:wLX!:
s:_W:W_:
s:#W:W#:
s:_wW:!:
s:_X:X_:
s:#X:X#:
s:_wX:#:
        ta' <<<"$s")";;
    [B)
        s="$(sed '
s:!:_VRv:
        :a
s:R:>>>>>>>>>>>>>:
s:>v#:#v:
s:>v_:_v:
s:>_:_>:
s:>#:#>:
s:Vv#:!URv:
s:U_:_U:
s:U#:#U:
s:Uv_:#:
s:V_:_V:
s:V#:#V:
s:Vv_:!:
        ta' <<<"$s")";;
    [C)
        s="$(sed '
s:!#_:_!#:
        te
s:!_:_!:
        :e' <<<"$s")";;
    [D)
        s="$(sed '
s:_#!:#!_:
        te
s:_!:!_:
        :e' <<<"$s")";;
    esac
    input="$input${REPLY:1}"
done

echo "$input"

```

Try it online!

Try it online (with escape code removed)!

For up and down, `!:wLW_` or `!:_VRv` is applied for once correspondingly, and the relevant rules are applied repeatedly until the `!` appeared again. For right, one of `!#_:_!#` and `!_:_!` is applied. For left, one of `_#!:#!_` and `_!:!_` is applied.

See the output in the links for the position after each move.

# Answer
> 9 votes
## boboquack

For a given string, take all the letters (a = 0, b = 1, c = 2), sum them up and take the modulo 3. Then none of the rewrite rules change that value. The source string has a value of 1, and the target has a value of 2. Therefore, no combination of rules will transform the source string to the target string.

# Answer
> 6 votes
# xnor

> Rule 1 `x:xn` Rule 2 `no:oon` Rule 3 `nr:r` Rule 4 `ooooooooooo:`

We use `[X,Y]` to indicate a run of Y `X`s

> Starting from `xn[o,A]r`,
>
> 1. Applying Rule 2 once we have `x[o,2]n[o,A-1]r`.
> 2. Applying Rule 2 once more we have `x[o,4]n[o,A-2]r`
> 3. Applying until the `o`s between `n` and `r` becomes 0, we have `x[o,2*A]nr`.
> 4. Applying Rule 3 once we have `x[o,2*A]r`.
> 5. Applying Rule 1 once we have `xn[o,2*A]r`.
>
> So, we have an algorithm to generate from `xn[o,A]r` to `xn[o,2*A]r`.

Starting from `xnor = xn[o,1]r`, repeating 10 times the algorithm -- except in the 10th loop we stop at Step 4, having `x[o,1024]r`.

Applying Rule 4, this clears 1023 = 11 * 93 `o`s, leaving `xor`.

# Answer
> 2 votes
# VortexYT

There is no way of eliminating `F`s without creating/using other characters; thus, we must use `I:F` as the last step to get to the target. No rule gives a single `I` without other unwanted characters thus you can't get to the target string.

Equivalently, if you try to map backwards from the source, you can only get from `F` to `I` before you have no more options.

# Answer
> 1 votes
# The Empty String Photographer

The target string cannot be reached because there is no right-to-left override in the rules. That's even easier than the effort I put into formatting the original answer. Very unfunny. :p

---
Tags: cops-and-robbers, repeated-transformation, grammars
---


title: Create Bernard from Desmos

text:
# Question
Title: Create Bernard from Desmos
# Background

In the online graphing calculator Desmos, there is a certain shape that appears in the lower left portion of the graph in many high detail graphs, which the Desmos community has dubbed "Bernard". You can see an example of it in this graph and an isolated version of it in this graph. This shape is a consequence of the quadtree algorithm which Desmos utilizes to actually graph equations. I barely comprehend how it all works, but by descending into "deeper", or more detailed, quadrants, a more detailed Bernard can be created.

(Don't take my word for how Bernard is formed, I barely understand how it works myself.)

A screenshot of what Bernard looks like for posterity:

In this challenge, you will write code that will print out a 2d array version of a depth-`n` Bernard.

# How to create Bernard?

Given a positive integer `n`, create a \\$2^n\times2^n\\$ grid of `1`'s and `0`'s.

If \\$n=1\\$, then fill in the \\$2\times2\\$ grid like so:

```
0 1
1 1

```

That is your output.

If \\$n\>1\\$, then recursively fill in the grid in the following way:

1. Split the grid into 16 blocks of size \\$2^{n-2}\times2^{n-2}\\$.
2. Fill in the square regions according to the below diagram, and recurse on the region labelled `R`:

```
0 0 1 1
0 0 0 R
1 1 1 1
1 1 1 1

```
3. If the region `R` is a \\$1\times1\\$ or a \\$2\times2\\$ region, then finish this step and output the resulting array. If the region `R` is a \\$1\times1\\$ region, then fill its only entry with `1`. If `R` is a \\$2\times2\\$ region, then fill it in the following way:

```
0 1
1 1

```
4. If step 3 does not apply, then repeat steps 1-4 but on region `R`.

# Worked example: `n=4`

`n` is 4, so we will have a \\$16\times16\\$ grid. Following step 1, we fill the grid in the following way (with `R` denoting the region we will recurse on):

```
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 R R R R
0 0 0 0 0 0 0 0 0 0 0 0 R R R R
0 0 0 0 0 0 0 0 0 0 0 0 R R R R
0 0 0 0 0 0 0 0 0 0 0 0 R R R R
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

```

The region `R` is \\$4\times4\\$, so we recurse. The region `R` should now look like this, with the new `R` inside the grid denoting where to recurse:

```
0 0 1 1
0 0 0 R
1 1 1 1
1 1 1 1

```

Because `R` is now \\$1\times1\\$, we fill it in, so it becomes:

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

```

Placing this back into the original \\$16\times16\\$ grid, we obtain the desired output:

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

```

# Task

Given a positive integer `n` as input, return a \\$2^n\times2^n\\$ 2d array which represents the depth-`n` Bernard.

# Test Cases

```
n=1
0 1
1 1

n=2
0 0 1 1
0 0 0 1
1 1 1 1
1 1 1 1

n=3
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

n=4
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

```

---

This is , so shortest code in bytes wins!

# Answer
# K (ngn/k), 21 bytes

```
(|,/2\,'/4\10+)/[;+1]

```

Try it online!

Same algorithm, but uses a bit of base trick to generate the zero- and one-matrices at appropriate places.

```
10+    Map 0 to 10 and 1 to 11
4\     Base 4; 10 becomes (2 2) and 11 becomes (2 3)
2\     Base 2; 2 becomes (1 0) and 3 becomes (1 1)

```

---

# K (ngn/k), 23 bytes

```
(,/(1|)\|,'/|^:\)/[;+1]

```

Try it online!

A straightforward implementation. Uses the recurrence pattern:

```
f(n+1) = [ zeros, f(n) reversed ]
         [ ones,  ones          ]

```

### How it works

```
(,/(1|)\|,'/|^:\)/[;+1]    a function that takes n and
(               )/         applies the recurrence n times on
                    +1     the 1x1 matrix containing a single 1:
             ^:\    converge-scan using "test if each atom is null"; gives (mat; zeros)
         ,'/|       reverse the order and horizontally join the two matrices
        |           reverse vertically
   (1|)\      converge-scan using "max with 1"; gives (mat; ones)
 ,/           join vertically

```
> 12 votes

# Answer
# Desmos, ~~94~~ 92 bytes

```
f(n)=[0^{0^{4^{round(u+.5log_4dd)-u}-x}}forx=L,y=L]
d=3y-2^n2
u=(0^{0^d}+n)/2
L=[2^n...1]-.5

```

Try it on Desmos!

The matrix is returned in row-major order.

*-2 bytes thanks to @Aiden Chow (`log_4(dd)/2``.5log_4dd`)*

Golfing note: `0^{0^{E-x}` can be converted to `\{E>x,0\}`, but this requires moving `E=round(u+.5log_4d)-u` to its own line and doing `\for`  instead of just `for`, so that is equal or +1 byte.

## How it Works

The top third of matrix Bernard consists of right-aligned blocks of height \\$2^{n-2},2^{n-4},\ldots,2^{\operatorname{mod}(n,2)}\\$, and the bottom two-thirds consists of right-aligned blocks of height \\$2^{n-1},2^{n-3},\ldots,2^{\operatorname{mod}(n+1,2)}\\$. Each block has width equal to twice its height, and the top and bottom converge near `y=m=2^n/3`.

The main difficulty is for each `y`, find the height of the current block.

First we find the distance of `y` from the convergence y-value `m`. This is \\$D=y-\frac{2^n}{3}\\$

To figure out how many steps this is away, consider a situation where `n` is even, so the top third has step sizes \\$1,4,16,\ldots\\$. The partial sums of this geometric sequence are \\$p(k)=\frac{4^k-1}{3}\\$, e.g. \\$p(2)=\frac{4^2-1}{3}= 5 = 1+4\\$.

Then \\$(x,y)\\$ on the top third is in step size \\$4^k\\$ iff \\$p(k)\leq D\<p(k+1)\\$. This can be re-arranged to \\$4^k\leq 3D+1\leq 4^{k+1}\\$, so \\$k=\operatorname{floor}(\log\_4(3D+1))\\$

Ignoring golfing and the bottom side, this would give `{x < floor(log_4(3D+1)): 1, 0}` for the condition for filling in 1.

The final golfed code uses \\$d=3y-2^{n+1}\approx 3D+1\\$ (the `y` values are flipped, so this is really proportional to the distance of `y` from `2^n*2/3`, explaining `2^{n+1}` instead of `2^n`).

Hence we have `{x < floor(log_4(d)): 1, 0}` as the current condition. See what it looks like on Desmos.

There's a few problems left: nothing is filled in for the bottom two-thirds, and the heights of the top third is twice as big as it should be for odd `n`.

Let's deal with the first problem first by just replacing `log_4(d)` with `log_4(abs(d))` to handle negative `d`, or equivalently `log_4(d^2)/2`, which golfs to `.5log_4dd`. Then our condition becomes `{x < floor(log_4(d)): 1, 0}`. See on Desmos.

The issue now is that the heights of the top third are twice too big for odd `n`, and the heights of the bottom two-thirds are twice too big for even `n`. The solution comes down to handling off-by-half in the exponent of `4^{...}` by adding and subtracting `u=(0^{0^d}+n)/2` withing/outside the `round`. If `d` is positive (top third) and `n` is even, then `u` is an integer, so it doesn't affect the `round`. If `d` is negative (bottom two-thirds) and `n` is odd, then `u` is an integer, so it doesn't affect the `round`. Otherwise, `n` is a half-integer, so it causes `round` to behave like `1+floor`, fixing the sizing issues.
> 9 votes

# Answer
# Python, 76 bytes

```
f=lambda n:(x:=1<<n>>1)and[x*[0]+j for j in f(n-1)[::-1]]+x*[x*[1,1]]or[[1]]
```

Attempt This Online!

Straight-forward recursion. Take the previous upside down, add a block of zeros on the left and a block of ones below.

Just seeing that @Bubbler used the same recursion a few hours before me.
> 6 votes

# Answer
# Jelly, 15 bytes

```
2Ṛ;»Ṁ²ƊƊ¡’Bz0ZU

```

A full program that accepts a positive integer from STDIN and prints a list representation of the Bernard.

**Try it online!** (The footer prints the result as a grid instead of in the raw list format.)

### How?

Builds the Bernard in chunks consisting of the equal rows, starting with the row with the single `1`. At each step we reverse what we have so far and append the next chunk. Each new chunk has as many rows as we've built so far but with double the number of `1`s.

Under the hood, each row is first calculated as one more than its binary value. This starts at `2` and squares for each new chunk.

```
2Ṛ;»Ṁ²ƊƊ¡’Bz0ZU - Main Link: no arguments
2               - literal two
        ¡       - repeat STDIN times starting with X=2:
       Ɗ        -   last three links as a monad - f(X):
 Ṛ              -     reverse the current list
                        (2 gives its decimal digits reversed = [2])
      Ɗ         -     last three links as a monad - f(Z=that):
    Ṁ           -       maximum of Z
   »            -       vectorised maximum with Z -> an array of the same shape as
                                      Z, all populated with the maximum value in Z
     ²          -       square them
  ;             -     (reversed X) concatenate with (that)
         ’      - decrement all the values
          B     - convert them to binary lists
           z0   - transpose with filler zero  }
             Z  - transpose                   } prepends zeros
              U - reverse each

```
> 6 votes

# Answer
# PARI/GP, 52 bytes

```
n->matrix(l=2^n,,i,j,j+2^#binary(bitxor(i-1,l\3))>l)
```

For input \\$n\\$, the number of \\$1\\$s in the \\$i\\$-th row (\\$1\\$-index) is \\$2^{\\#\operatorname{binary}(\operatorname{bitxor}(i-1,\lfloor2^n/3\rfloor))}\\$, where \\$\\#\operatorname{binary}\\$ means the number of the binary digits. This is because the binary representation of \\$\lfloor2^n/3\rfloor\\$ is \\$(1010\dots)\\$.

Attempt This Online!
> 5 votes

# Answer
# Factor, ~~90~~ ~~89~~ 83 bytes

```
[ 2^ 3 dupn iota -rot '[ _ 3 /i bitxor bit-length 2^ 1 <array> _ 0 pad-head ] map ]

```

Try it online!

Port of @alephalpha's PARI/GP answer.
> 5 votes

# Answer
# Python, ~~121~~ 104 bytes

```
lambda n:[[*map(int,f"{m:0{2**n}b}")]for m in g(n)]
g=lambda n:[1][n:]or g(n-1)[::-1]+2**~-n*[2**2**n-1]
```

Attempt This Online!

This is a much more interesting method, but is not well golfed because Python isn't great at converting binary numbers into a matrix (at least as far as I am aware).

Works by taking a start list of `[1]`. For each integer `i` up to `n`, reverse the list and add to it `2**~-n*[2**2**n-1]`. This outputs the following pattern

```
[1, 3]
[3, 1, 15, 15]
[15, 15, 1, 3, 255, 255, 255, 255]
[255, 255, 255, 255, 3, 1, 15, 15, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535]

```

Which is then converted into binary, with each item in the list forming a row in the matrix.

-17 bytes thanks to @pxeger

---

# Python, ~~119~~ 117 bytes

```
f=lambda n:[[1]][n:]or-(-(p:=2**n)//4)*[(q:=p//2)*[0]+q*[1]]+[l+r for l,r in zip(p//4*[p//4*3*[0]],f(n-2))]+q*[[1]*p]
```

Attempt This Online!

Follows the algorithm as outlined in the question
-2 bytes thanks to pxeger
> 4 votes

# Answer
# JavaScript (ES6), 95 bytes

A rather straightforward recursive construction.

```
n=>[...Array(1<<n)].map((_,y,a)=>a.map(g=(k=n,x,_,Y=y)=>k--?Y>>k|x>>k&g(k,x%=m=1<<k,_,~Y%m):1))

```

Try it online!

### Commented

```
n =>                  // n = input
[...Array(1 << n)]    // build an array of 2 ** n entries
.map((_, y, a) =>     // for each item at position y in this array a[]:
  a.map(              //   iterate over a[] again using ...
  g = (               //   ... the recursive callback function g taking:
    k = n,            //     k = dimension, initialized to n
    x,                //     x = horizontal position
    _,                //     (ignored reference to the array)
    Y = y             //     Y = vertical position
  ) =>                //
    k-- ?             //     decrement k; if it was not 0:
      Y >> k |        //       insert a '1' if we are in the lower part (*)
      x >> k &        //       or we are in the right part and the result
      g(              //       of this recursive call is also 1:
        k,            //         pass the new value of k
        x %=          //         update x to x modulo m,
          m = 1 << k, //         where m = 2 ** k
        _,            //         (useless reference to the array)
        ~Y % m        //         update Y to (-Y - 1) modulo m
      )               //       end of recursive call
    :                 //     else:
      1               //       insert a '1' and stop the recursion
  )                   //   end of inner map()
)                     // end of outer map()

```

*(\*) The sign of Y is inverted at each iteration, so the 'lower' part is actually the upper part when Y is negative.*
> 3 votes

# Answer
# 05AB1E, 17 bytes

```
ÎF¼RNoF¾ª]oÅ10ζRø

```

Try it online or verify all test cases. (The footer is to pretty-print the matrix.)

**Explanation:**

Step 1: Create alternating lists of \\$2^x\\$ amount of 0-based values depending on the input:

```
Î          # Push 0 and the input
 F         # Loop `N` in the range [0, input):
  ¼        #  Increase `¾` by 1 (it's 0 by default)
   R       #  Reverse the current list (or 0 in the first iteration)
    No     #  Push 2 to the power `N`
      F    #  Inner loop that many times:
       ¾ª  #   Append `¾` to the list
           #   (`ª` will convert the 0 to [0] in the very first iteration)
 ]         # Close both loops

```

See just this step online for all test cases.

Step 2: Calculating \\$2^v\\$ for each of these values determines the amount of trailing `1`s per row:

```
  o        # Map each value to 2 to the power that value
   Å1      # Then convert each inner value to a list of that many 1s

```

See the first two steps online for all test cases.

Step 3: Add leading `0`s to each row, and output the resulting matrix:

```
      ζ    # Zip/transpose this list of rows; swapping rows/columns,
     0     # using a 0 as filler-character for unequal length rows
       R   # Reverse the list of lists
        ø  # Zip/transpose the matrix back
           # (after which it is output implicitly as result)

```
> 3 votes

# Answer
# Uiua, 19 bytes

```
⍥(⊂⊃∘=.⍉⊂⊃-⍉.⇌):¤¤1

```

Try it online!

## How it works

```
⍥(⊂⊃∘=.⍉⊂⊃-⍉.⇌):¤¤1
                   ¤¤1 1x1 matrix containing a single 1
                  :    flip the values on the stack, bringing n to the top of the stack
⍥                      repeat the following n times:
                ⇌      reverse the matrix's rows, flipping it vertically
               .       duplicate
           ⊃-⍉        apply subtraction from the duplicate and transpose in parallel
                       subtraction from the same matrix results in a 0 matrix
        ⊂             join the resulted matrices vertically
      ⍉               transpose back, reverting the previous transpose and making the join horizontal
      .               duplicate
   ⊃∘=                apply identity (keep, do nothing) and equality against the duplicate in parallel
                      equality against the same matrix results in a 1 matrix
  ⊂                   join

```
> 3 votes

# Answer
# Python 3, 138 bytes

```
import re
def f(n):r=[int(bin(i)[2:])for i in range(2**n)];return[[1-bool(re.match('1(13)*(12|0)',str(x+y+y+10**n)))for x in r]for y in r]

```

Try it online!
> 2 votes

# Answer
# Python 3 with numpy, ~~77~~ 76 bytes

```
from numpy import*
f=lambda n:n<eye(1)or kron(c_[:4:2,1:3],f(n-1)[::-1]+1)>1

```

Try it online!

* `n<eye(1)` produces `[[True]]` for n=0, the base case, and `[[False]]` for positive n, causing the expression after it to be used.
* `c_[:4:2,1:3]` produces \\$ \begin{pmatrix}0&1\\2&2\end{pmatrix}\\$, and is 1 byte shorter than the direct way of writing that matrix.
* The grid for n-1 is recursively obtained and flipped vertically, and then 1 is added, making it consist of 1s and 2s. `kron` then produces a copy of it in the top-right quadrant (\>1 where the pre–+1 version had a 1), a doubled copy of it in each bottom quadrant (always \>1), and zero in the top-left quadrant (never \>1).
> 2 votes

# Answer
# Haskell, 111 bytes

```
data T a=C a|Q(T a)(T a)(T a)(T a)
f 0=C 1
f 1=Q(C 0)(C 1)(C 1)$C 1
f n=Q(C 0)(Q(C 1)(C 1)(C 0)$f$n-2)(C 1)$C 1
```

The matrix is represented as a quadtree. (I don't know if this output format is accepted).
> 2 votes

# Answer
# BQN, 19 bytes

```
{(∾⟜×⟜⋆0¨∾˘⌽)⍟≍≍1}

```

Try it here!

*-1 thanks to @att*

## Explanation

Input is *x*.

* `(...)⍟≍≍1` execute *x* times on matrix `[[1]]`...
* `0¨⊸∾˘` row-wise prepend matrix of 0s
* `1¨⊸∾` column-wise prepend matrix of 1s
* column-wise reverse

Example of how one iteration works:

0 1      # start
1 1

0 0 0 1  # 0¨⊸∾˘
0 0 1 1

1 1 1 1  # 1¨⊸∾
1 1 1 1
0 0 0 1
0 0 1 1

0 0 1 1  # ⌽
0 0 0 1
1 1 1 1
1 1 1 1
```
</code></pre>
> 2 votes

# Answer
# Charcoal, 26 bytes

```
↑1ＦＥＮＸ²ι«‖↓ＵＯ⊗ιι1Ｍ⊕ι↑»‖ＵＢ0

```

Try it online! Link is to verbose version of code. Explanation: Works by drawing the horizontal mirror image of Bernard, using the property that each Bernard is the vertical mirror image of the previous Bernard extended to the left with `0`s and then extended down with `1`s.

```
↑1

```

Output the lone `1` on its own row, leaving the cursor above the row.

```
ＦＥＮＸ²ι«

```

Loop `n` times, adding `2ⁱ` rows each time, thus resulting in a total of `2ⁿ` rows.

```
‖↓

```

Reflect vertically, leaving the cursor below Bernard.

```
ＵＯ⊗ιι1

```

Draw the next size rectangle of `1`s.

```
Ｍ⊕ι↑

```

Move back to the top of the Bernard.

```
»‖

```

Reflect horizontally to complete the Bernard.

```
ＵＢ0

```

Fill the background with `0`s.
> 1 votes

# Answer
# Vyxal , 20 bytes

```
0?(ṘnEn›ẋJ)E1vẋ0ÞṪṘ∩

```

Try it Online!
> 1 votes

# Answer
# brev, 190 bytes

```
(define(b n)(define(e d v)(make-list(expt 2(- n d))v)) `(,@(e 2 `(,@(e 1 0),@(e 1 1))),@((over(append(e 1 0)(e 2 0)x))(b(- n 2))),@(e 1(e 0 1))))(define(b 1)'((0 1)(1 1)))(define(b 0)'((1)))

```

236 with whitespace added back in:

```
(define (b n)
  (define (e d v)
    (make-list
     (expt 2 (- n d)) v))
  `(,@(e 2 `(,@(e 1 0) ,@(e 1 1)))
    ,@((over (append (e 1 0) (e 2 0) x)) (b (- n 2)))
    ,@(e 1 (e 0 1))))

(define (b 1) '((0 1) (1 1)))
(define (b 0) '((1)))

```

Bonus! I like coming up with my own solution but here's my implementation of Bubbler's idea, at 135 bytes (displayed here with 15 unnecessary bytes of whitespace for readability)

```
(define (u n) ((fn `(,@((over `(,@((over 0) x) ,@x)) (reverse x)) ,@((over `(,@((over 1) x) ,@((over 1) x))) x))) (u (- n 1))))

(define (u 0) '((1)))

```
> 1 votes

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

```
f=n=>n?f(n-1).reduce((v,e)=>[p=[...e.map(_=>0),...e],...v,p.map(_=>1)],[]):[[1]]

```

Try it online!

# Python 3.8 (pre-release), 75 bytes

```
f=lambda n,g=[]:n and f(n-1,[0]*(p:=2**~-n)+g)[::-1]+p*[g+[1,1]*p]or[g+[1]]

```

Try it online!
> 0 votes

# Answer
# Python 3.8 (pre-release), 72 bytes

```
f=lambda n,z=0:[l:='0'*z+2**n*'1'][n:]or f(m:=n-1,z+2**m)[::-1]+2**m*[l]

```

Try it online!
> 0 votes

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


title: Which skill to train?

text:
# Question
Title: Which skill to train?
**Story** (skip, if you prefer the naked task): You need five skills for an imaginary sport: Speed, strength, endurance, accuracy and tactics. If you achieve a score in each of these disciplines, you can work out how well you have mastered the sport as a whole. But, as your coach always says: concentrate on your strengths, because they count more!

**Rule:** The weakest score counts to the second power, the second weakest to the third power and so on. The strongest score counts with the sixth power!

Let's take an **example**: A beginner has the scores `3, 2, 4, 1, 2`. Then they achieve a total of `1*1 * 2*2*2 * 2*2*2*2 * 3*3*3*3*3 * 4*4*4*4*4*4 = 127401984`.

And what should they train, their greatest strength, i.e. improve the third discipline from 4 to 5? That would give them a score of 486000000. Or would it be better to work on their weakness, the fourth discipline? Great, that would give them 509607936. But even better would be to work on the second or fifth skill, then they could achieve 644972544!

So this is the **task: name the number of the skill that needs to be improved by 1 to achieve the highest score!**

**Input:** a list of five positive integers

**Output:** the index of the number to be increased for the maximum product (write in the answer whether the index is 0-based or 1-based). If more than one share the same result, name only one of them, no matter which.

The shortest code wins!

**Test data** (index 1-based)

```
3, 2, 4, 1, 2      --> 2
7, 19, 12, 20, 14  --> 4
13, 12, 19, 9, 20  --> 1
13, 18, 12, 12, 14 --> 5
18, 19, 18, 16, 13 --> 2
14, 14, 19, 17, 11 --> 3

```

# Answer
# APL(Dyalog Unicode), 14 bytes SBCS

```
⊃∘⍒(1+÷)*1+⍋∘⍋

```

Try it on APLgolf!

```
         ⍋∘⍋    relative ranking
       1+       exponents
   1+÷          1+1/n = (n+1)/n
      *         power
⊃∘⍒             max index

```
> 8 votes

# Answer
# Jelly, ~~9~~ 8 bytes

```
‘÷*ỤỤ‘ƊM

```

Try it online!

A monadic link taking a list of five integers and returning the index of the skill to improve (wrapped in a length 1 list). Run as a full program, will print the integer without any list braces.

## Explanation

```
‘         | Increment by 1
 ÷        | Divide by original list
  *   Ɗ   | To the power of:
   ỤỤ‘    | - The result of finding the indices needed to sort the list, repeating that process and then incrementing by 1
       M  | Indices of maximum

```

This should work even where there are ties either in the original list or created by increasing one of the skills.

I’ve subsequently realised this uses the same method as the existing APL answer, so be sure to upvote that one!
> 7 votes

# Answer
# Python, 69 bytes

```
lambda s:s.index(max(s,key=lambda t:(~t/-t)**sum(map(t.__ge__,s),1)))

```

Attempt This Online!

0-based.
> 6 votes

# Answer
# Vyxal 3, 11 bytes

```
∥ϩėꜝ↑↑2+*ƓḞ

```

Try it Online!

Port of l'apl

## Explained

```
∥ϩėꜝ↑↑2+*ƓḞ
∥            # Apply both of these to the input:
 ϩėꜝ         #   Reciprocals of each, incremented
    ↑↑       #   Grade up, twice
      2+     # Increment the result of ^ by 2
        *    # Power of reciprocals to ^
         ƓḞ  # Find the maximum index by finding the maximum without popping and finding its position

```

Created with the help of Luminespire.
> 5 votes

# Answer
# 05AB1E, 14 bytes

```
āΣIāyQ+{ā>mP}θ

```

1-based.

Try it online or verify all test cases.

**Explanation:**

```
ā            # Push a list in the range [1, input-length]
 Σ           # Sort it by:
  I          #  Push the input-list again
   ā         #  Push a list in the range [1, input-length] again
    y        #  Push the current item we're sorting on
     Q       #  Equals check, so we have a list of 0s with a 1 at the current item
      +      #  Add the two lists together, so the current position is increased by 1
       {     #  Now sort this updated input-list
        ā    #  Push a list in the range [1, input-length] once again
         >   #  Increase it by 1
          m  #  Take the items in the sorted updated list to the power these values
           P #  Take the product of that
 }θ          # After the sort-by: pop and push the last item
             # (so `Σ...}θ` basically translates to a maximum-by builtin)
             # (which is output implicitly as result)

```
> 5 votes

# Answer
# , 35 bytes

```
\(x,`-`=order)(-(1+1/x)^(--x+1))[5]

```

Attempt This Online!

An anonymous function taking an integer vector and returning an integer. Uses the same method as my Jelly answer (and therefore some other answers including @att’s APL one).
> 4 votes

# Answer
# Nekomata, 12 bytes

```
çᵚᶠ≥Mŗ→ᵐ∏x$Ṃ

```

Attempt This Online!

Based on @att's APL answer, with some hacks because Nekomata doesn't have built-ins for ranking, grade-up, or sort-by.

```
çᵚᶠ≥Mŗ→ᵐ∏x$Ṃ    Takes [3,2,4,1,2] as an example
ç               Prepend 0
                -> [0,3,2,4,1,2]
 ᵚ              For each element of the original list:
  ᶠ≥              Filter the list by <= that element
                -> [[0,3,2,1,2],[0,2,1,2],[0,3,2,4,1,2],[0,1],[0,2,1,2]]
    M           Element-wise max with the original list
                -> [[3,3,3,3,3],[2,2,2,2],[4,4,4,4,4,4],[1,1],[2,2,2,2]]
     ŗ→         1 + 1 / that
                -> [[4/3,4/3,4/3,4/3,4/3],[3/2,3/2,3/2,3/2],[5/4,5/4,5/4,5/4,5/4,5/4],[2,2],[3/2,3/2,3/2,3/2]]
       ᵐ∏       Product of each
                -> [1024/243,81/16,15625/4096,4,81/16]
         x$Ṃ    0-based index of the maximum
                -> 1 or 4

```

This returns all possible results. If you want only one result, you can add the `-1` flag.
> 3 votes

# Answer
# Uiua, 13 bytes

```
⊢⍖ⁿ+2⍏⍏:+1÷,1

```

Try it!

0-indexed. Port of lyxal's Vyxal 3 answer.

```
⊢⍖ⁿ+2⍏⍏:+1÷,1
            1  # push 1
           ,   # copy the input to top of stack
          ÷    # divide (reciprocals)
        +1     # increment
       :       # flip (bring second copy of input to top)
     ⍏⍏        # rise (grade up) twice
   +2          # add two to each
  ⁿ            # power
⊢⍖             # index of maximum

```
> 3 votes

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

```
x=>x.map((t,i)=>[(t/++t)**x.filter(v=>v<t).push(0),i]).sort()[0][1]

```

Try it online!

0-index
> 2 votes

# Answer
# Charcoal, 19 bytes

```
Ｉ⊟⌈Ｅθ⟦Ｘ∕⊕ιι⊕№÷θ⊕ι⁰κ

```

Try it online! Link is to verbose version of code. 0-indexed. Explanation: Port of @l4m2's JavaScript answer.

```
    θ               Input list
   Ｅ                Map over elements
         ι          Current element
        ⊕           Incremented
       ∕            Divided by
          ι         Current element
      Ｘ             Raised to power
            №       Count of
                 ⁰  Literal integer `0` in
              θ     Input list
             ÷      Integer divided by
                ι   Current element
               ⊕    Incremented
           ⊕        Incremented
                  κ Current index
     ⟦              Make into list
  ⌈                 Take the maximum
 ⊟                  Get just the index
Ｉ                   Cast to string
                    Implicitly print

```
> 2 votes

# Answer
# Desmos, 49 bytes

```

f(l)=[(1+1/i)^{6-l[l>i].\count}\for i=l].\argmax

```

Port of Albert.Lang's Python answer, so make sure to upvote that answer too!

Try It On Desmos!

This uses a so-called fragile function `argmax` which means that the expression containing the function (which looks empty because it doesn't render properly) will break if basically any key is pressed when you are focused on that expression. Also, because `argmax` isn't an "official" function, I don't have a prettified version of the code as simply typing `argmax` into the calculator won't yield a valid function.

For reference, this is the shortest answer I could come up with without the usage of the `argmax` fragile function (54 bytes):

```
f(l)=sort([1...5],[(1+1/i)^{6-l[l>i].count}fori=l])[5]

```
> 2 votes

# Answer
# GAWK, 104 101 bytes

```
{for(i=m=1;i<6;i++){++$i;split($0,_);asort(_,a);for(k=t=1;k<6;)if((t*=a[k]^++k)>m){m=t;n=i}--$i}}$0=n

```

Try it online!

* -3 bytes, forgot about default value of fieldsep for `split()` function.

It's index 1-based.
> 1 votes

# Answer
# Haskell, 111 bytes

```
import Data.List
f y=snd$maximum[(product$zipWith(^)(sort$t++(x+1):d)[2..],i)|i<-[0..4],(t,x:d)<-[splitAt i y]]

```

Attempt This Online!
> 1 votes

# Answer
# Python 3 (197 bytes)

```
e=enumerate
x=lambda s:max((((lambda s:(f:=lambda n:n[0]if len(n)==1 else n[0]*f(n[1:]))([j**i for i,j in e(sorted(s),2)]))(j[:i]+[j[i]+1]+j[i+1:]),i)for i,j in e([s]*len(s))),key=lambda i:i[0])[1]

```

Try it online
> 1 votes

# Answer
# Scala, 171 bytes

A port of @matteo\_c's Haskell answer in Scala.

---

Golfed version. Try it online!

```
y=>(0 to 4).map{i=>val(s,l)=y.splitAt(i);val t=s++((l.headOption.getOrElse(0)+1)::l.tail);(t.sorted.zipWithIndex.map{case(v,j)=>math.pow(v,j+2)}.product,i)}.maxBy(_._1)._2

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val testcases = List(
      (List(3, 2, 4, 1, 2     ),   2),
      (List(7, 19, 12, 20, 14 ), 4),
      (List(13, 12, 19, 9, 20 ), 1),
      (List(13, 18, 12, 12, 14), 5),
      (List(18, 19, 18, 16, 13), 2),
      (List(14, 14, 19, 17, 11), 3))

    val results = testcases.map { case (i, o) => f(i) == o - 1 }

    println(results)
  }

  def f(y: List[Int]): Int = {
    val results = for {
      i <- 0 until 5
      split = y.splitAt(i)
      (t, d) = (split._1, split._2.headOption.getOrElse(0) + 1 :: split._2.tail)
      sorted = (t ++ d).sorted
      product = sorted.zipWithIndex.map { case (v, idx) => Math.pow(v, idx + 2) }.product
    } yield (product, i)

    results.maxBy(_._1)._2
  }
}

```
> 1 votes

# Answer
# Excel (ms365), 89 bytes

Formula in `G1`:

```
=LET(x,BYROW(A1:E1+MUNIT(5),LAMBDA(y,PRODUCT(SORT(y,,,1)^{2,3,4,5,6}))),XMATCH(MAX(x),x))

```
> 1 votes

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


title: Multiplicative persistence

text:
# Question
Title: Multiplicative persistence
## Multiplicative Persistence

1. Multiply all the digits in a number
2. Repeat until you have a single digit left

As explained by *Numberphile*:

### Example

1. 277777788888899 → 2x7x7x7x7x7x7x8x8x8x8x8x8x9x9 = 4996238671872
2. 4996238671872 → 4x9x9x6x2x3x8x6x7x1x8x7x2 = 438939648
3. 438939648 → 4x3x8x9x3x9x6x4x8 = 4478976
4. 4478976 → 4x4x7x8x9x7x6 = 338688
5. 338688 → 3x3x8x6x8x8 = 27648
6. 27648 → 2x7x6x4x8 = 2688
7. 2688 → 2x6x8x8 = 768
8. 768 → 7x6x8 = 336
9. 336 → 3x3x6 = 54
10. 54 → 5x4 = 20
11. 20 → 2x0 = 0

This is the current record, by the way: the smallest number with the largest number of steps.

## Golf

A program that takes any whole number as input and then outputs the result of each step, starting with the input itself, until we hit a single digit. For 277777788888899 the output should be

```
277777788888899
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0

```

(Counting the number of steps is left as an exercise to the user).

### More Examples

From A003001:

```
25
10
0

```

From A003001 as well:

```
68889
27648
2688
768
336
54
20
0

```

From the *Numberphile* video, showing that the single digit doesn't have to be 0:

```
327
42
8

```

---

*So there has been a question about Additive Persistence, but this is Multiplicative Persistence. Also, that question asks for the number of steps as output, while I'm interested in seeing the intermediate results.*

# Answer
# Jelly, 4 bytes

```
DP$Ƭ

```

Try it online!

### Explanation

```
D    | convert to decimal digits
 P   | take the product
  $  | previous two links as a monad
   Ƭ | loop until no change, collecting all intermediate results

```

As a bonus, here's a TIO which will find the numbers with the largest number of steps for a given range of numbers of digits. It scales well even on TIO.
> 9 votes

# Answer
# TI-BASIC (TI-84), ~~30~~ ~~32~~ 31 bytes

*-1 byte thanks to @SolomonUcko!*

```
While Ans>9:Disp Ans:prod(int(10fPart(Ans10^(seq(-X-1,X,0,log(Ans:End:Ans

```

Input is in `Ans`.
Output is displayed as the challenge requests. The trailing `Ans` is needed to print the last step.

I will admit, I did not think of this formula myself, rather I found it here and modified it to better fit the challenge.

**EDIT:** Upon rereading the challenge, I realized that the program must terminate if the product is one digit. Hence, **2 bytes** were to be added to account for this.

**Example:**

```
24456756
        24456756
prgmCDGF8
        24456756
          201600
               0
11112
           11112
prgmCDGF8
           11112
               2

```

**Explanation:**

```
While Ans>9               ;loop until the product is one digit
Disp Ans                  ;display the current product
prod(                     ;get the product of...
 int(                     ; the integer part of...
  10fPart(                ; ten times the fractional part of...
  Ans                     ; each element in the following list times the
                          ;  current product
  10^(                    ; multiplied by the list generated by using each
                          ;  element of the following list as an exponent
                          ;  for 10^n
   seq(-X-1),X,0,log(Ans  ; generate a list of exponents from -1 to -L where
                          ;  L = the length of the current product
End
Ans                       ;leave the final product in "Ans" and implicitly
                          ; print it

```

**Visual Model:**
`Ans` starts off as `125673`.
This model only covers the logic behind multiplying the digits; everything else is easier to understand.

```
seq(-X-1,X,0,log(Ans  =>  seq(-X-1,X,0,5.0992
   {-1 -2 -3 -4 -5 -6}
10^(...
   {.1 .01 .001 1E-4 1E-5 1E-6}
Ans...
   {12567.3 1256.73 125.673 12.5673 1.25673 .125673}
fPart(...
   {.3 .73 .673 .5673 .25673 .125673}
10...
   {3 7.3 6.73 5.673 2.5673 1.25673}
int(...
   {3 7 6 5 2 1}
   (the digits of the number, reversed)
prod(...
   1260
   (process is repeated again)

seq(-X-1,X,0,log(Ans  =>  seq(-X-1,X,0,3.1004
   {-1 -2 -3 -4}
10^(...
   {.1 .01 .001 1E-4}
Ans...
   {126 12.6 1.26 .126}
fPart(...
   {0 .6 .26 .126}
10...
   {0 6 2.6 1.26}
int(...
   {0 6 2 1}
prod(...
   0
   (product is less than 10.  loop ends)

```

---

**Notes:**

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

`10^(` is this one-byte token.

This program will not provide the correct sequence of products with integers greater than 14 digits long due to the limitations of decimal precision on the TI calculators.
> 15 votes

# Answer
# K (ngn/k), 9 bytes

```
{*/.'$x}\

```

Try it online!

`{` `}\` keep applying the function in curly braces until the sequence converges

`$x` format the argument as a string (list of characters)

`.'` evaluate each (other dialects of k require a colon, `.:'`)

`*/` times over, i.e. product
> 11 votes

# Answer
# , ~~59~~ 57 bytes

```
n=scan();while(print(n)>9)n=prod(n%/%10^(0:log10(n))%%10)

```

Try it online!

Since `print` `invisibly` returns its input, we can use `print(n)` inside the `while` loop to simulate a `do-while` loop. This is inspired by one of my tips for golfing in R.

The header helps prevent large numbers from being printed in scientific notation.
> 10 votes

# Answer
# 05AB1E, ~~7~~ 4 bytes

```
Δ=SP

```

Try it online or verify all test cases.

**Explanation:**

```
Δ     # Loop until the number no longer changes:
 =    #  Print the number with trailing newline (without popping the number itself)
      #  (which will be the implicit input in the first iteration)
  SP  #  Convert the number to a list of digits, and calculate its product

```
> 8 votes

# Answer
# dzaima/APL, ~~14~~ 11 bytes

```
∪{×/⍎¨⍕⍵}⍡≡

```

Try it online!
> 8 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
Most@FixedPointList[Times@@IntegerDigits@#&,#]&

```

Try it online!
> 7 votes

# Answer
# Wolfram Language (Mathematica), 39 bytes

```
0Print@#+#>9&&#0@@Times@@@RealDigits@#&

```

Try it online!

-6 bytes from @att
> 7 votes

# Answer
# Perl 6, 23 bytes

```
{$_,{[*] .comb}…10>*}

```

Try it online!
> 7 votes

# Answer
# Python 2,  ~~46~~  43 bytes

-3 thanks to xnor (chained comparison)

```
def f(n):print n;n>9>f(eval('*'.join(`n`)))

```

**Try it online!**
> 7 votes

# Answer
# Julia 0.7, ~~36~~ 33 bytes

```
f(n)=n>9?[n;f(prod(digits(n)))]:n

```

Try it online!

Thanks to H.PWiz for -3 bytes.
> 6 votes

# Answer
# V (vim), 29 bytes

```
qqlYp:s/./&*/g
C<C-r>=<C-r>"<BS>
<esc>|@qq@q

```

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), 45 bytes

Returns an array of integers.

```
f=n=>[n,...n>9?f(eval([...n+''].join`*`)):[]]

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~38~~ ~~35~~ 34 bytes

```
f=->n{p(n)>9&&f[eval n.digits*?*]}

```

Try it online!

1 byte saved by by G B.
> 5 votes

# Answer
# MathGolf, ~~9~~ 10 bytes

```
h(ôo▒ε*h(→

```

Try it online!

Now it correctly handles inputs that are single digits. Not perfect, but at least it is correct.

## Explanation

```
h(            check length of input number and decrease by 1
  ö       →   while true with pop using the next 6 operators
   p          print with newline
    ▒         split to list of chars/digits
     ε*       reduce list by multiplication
       h(     length of TOS without popping, subtracted by 1 (exits when len(TOS) == 1)

```
> 5 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~79~~ ~~74~~ 68 bytes

```
void f(int a){Print(a);if(a>9)f((a+"").Aggregate(1,(j,k)=>k%48*j));}

```

I try to stay away from recursion in C# due to how long the method declaration is, but in this case it saves compared to a loop.

Try it online!
> 5 votes

# Answer
# Python 2, ~~61~~ ~~62~~ 59 bytes

```
def f(n):print n;n>9and f(reduce(int.__mul__,map(int,`n`)))

```

Try it online!

-3 bytes, thanks to Jonathan Allan
> 5 votes

# Answer
# PowerShell, 54 bytes

```
for($a=$args;$a-gt9){$a;$a=("$a"|% t*y)-join"*"|iex}$a

```

Try it online!

---

Iterative method that first writes the input argument, then converts it into a string and pipes it into a character array. This array is joined by a single asterisks, and executed as a command with the invoke expression alias. Since this writes Starting number down to the last number greater than 0, (20, in the given test scenario), I add a final `$a` to the end to output.
> 5 votes

# Answer
# PHP, 63 bytes

```
<?=$n=$argn;while($n>9)echo"
",$n=array_product(str_split($n));

```

Iterative version, call with `php -nF` input from `STDIN`.

Try it online!

# PHP, ~~72~~ 71 bytes

```
function h($n){echo"$n
",($n=array_product(str_split($n)))>9?h($n):$n;}

```

Try it online!

Recursive version, as function.

Input: 277777788888899

```
277777788888899
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0

```

Input: 23

```
23
6

```
> 5 votes

# Answer
# perl 5 (`-n` `-M5.01`), ~~32~~ ~~30~~ 25 bytes

```
say$_=eval;s/\B/*/g&&redo

```

25 bytes

30 bytes

32 bytes
> 5 votes

# Answer
# PowerShell, 51 bytes

```
filter f{$_
if($_-gt9){("$_"|% t*y)-join'*'|iex|f}}

```

Try it online!
> 5 votes

# Answer
# , 16 bytes

```
([:*/,.&.":)^:a:

```

Try it online!
> 5 votes

# Answer
# APL(NARS), 19 chars, 38 bytes

```
{⍵≤9:⍵⋄∇×/⍎¨⍕⍵⊣⎕←⍵}

```

test:

```
   f←{⍵≤9:⍵⋄∇×/⍎¨⍕⍵⊣⎕←⍵}
   f 23
23
6
   f 27648
27648
2688
768
336
54
20
0

```
> 4 votes

# Answer
## Haskell, 45 bytes

```
f n=n:[x|n>9,x<-f$product$read.pure<$>show n]

```

Try it online!
> 4 votes

# Answer
# Japt `-R`, 9 bytes

Horribly inefficient - don't even *try* to run the first test case!

```
_ì ×}hN â

```

Try it

```
_ì ×}hN â     :Implicit input of integer U
      N       :Starting with the array of inputs (i.e., [U])
     h        :Do the following U times, pushing the result to N each time
_             :Take the last element in N and pass it through the following function
 ì            :  Convert to digit array
   ×          :  Reduce by multiplication
    }         :End function
        â     :Deduplicate N
              :Implicitly join with newlines and output

```
> 4 votes

# Answer
# Chevron, 100 bytes

```
>^__>>^n
->+11?^n<10
>^n
^d<<1
^i<<1
^m<^i>^n
->+4??^m=^__
^d<<^d*^m
^i<<^i+1
->-4
^n<<^d
->-10
><^n

```

This is a fairly new language of my own creation - prototype interpreter, documentation, and example programs can be found at https://github.com/superloach/chevron.

## Explanation:

* `>^__>>^n` \- take the input as a NUM, with empty prompt
* `->+11?^n<10` \- if the number is under 10 (1 digit), skip to the end
* `>^n` \- output the current number
* `^d<<1` \- initialise the product to 1
* `^i<<1` \- initialise the character index to 1
* `^m<^i>^n` \- get i'th character of the number
* `->+4??^m=^__` \- jump out of loop if no character is found
* `^d<<^d*^m` \- multiply character into product
* `^i<<^i+1` \- increment character index
* `->-4` \- hop back to continue getting characters
* `^n<<^d` \- once loop is done, assign product as new number
* `->-10` \- hop all the way to the beginning for the next iteration
* `><^n` \- exit, printing the final number
> 4 votes

# Answer
# JavaScript (Babel Node), 46 bytes

```
f=a=>a>9?[a,...f(eval([...a+''].join`*`))]:[a]

```

Try it online!

---

# JavaScript (Babel Node), 44 bytes

*If the input can be taken as String*

```
f=a=>a>9?[a,...f(''+eval([...a].join`*`))]:a

```

Try it online!
> 3 votes

# Answer
# Brachylog, 7 bytes

```
ẉ?Ḋ|ẹ×↰

```

Try it online!

### Explanation

```
ẉ          Write the input followed by a linebreak
 ?Ḋ        If the input is a single digit, then it's over
   |       Otherwise
    ẹ      Split the input into a list of digits
     ×     Multiply them together
      ↰    Recursive call with the result of the multiplication as input

```
> 3 votes

# Answer
# PowerShell, ~~64~~ 59 bytes

```
for($a="$args";9-lt$a){$a;$a="$(($a|% t*y)-join'*'|iex)"}$a

```

Try it online!

Iterative method. Takes input and stores it into `$a`, then enters a `for` loop so long as the length of `$a` is two or more (i.e., it's bigger than `9`). Inside the loop we output `$a` and then recalculate it by converting it `t`oCharArra`y`, `join`ing it together with `*`, and then `iex` (short for `Invoke-Expression` and similar to `eval`). Once we're out of the loop, we have a single digit left to print, so we place `$a` onto the pipeline again.

*-5 bytes thanks to KGlasier.*
> 3 votes

# Answer
# Charcoal, 13 bytes

```
θＷ⊖Ｌθ«≔ＩΠθθ⸿θ

```

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

```
θ

```

Print the input for the first time.

```
Ｗ⊖Ｌθ«

```

Repeat while the length of the input is not 1.

```
≔ＩΠθθ

```

Replace the input with its digital product cast to string.

```
⸿θ

```

Print the input on a new line.
> 3 votes

# Answer
# Retina, 24 bytes

```
.+~(\`

.
$&$*
^
.+¶$$.(

```

Try it online! Explanation:

```
.+~(\`

```

Print the current value on its own line at the start of every loop until it stops changing and don't print the unchanged value twice. Evaluate the current value at the end of each loop.

```
.
$&$*

```

Add a `*` after each digit.

```
^
.+¶$$.(

```

Finish turning the input into an expression that evaluates to the digital product.

Just for the record, Retina can do this in one line (25 bytes):

```
.+"¶"<~[".+¶$.("|'*]'*L`.

```
> 3 votes

# Answer
# Java, ~~112~~ 106 bytes

*"Lossy conversion"* thanks Java for the extra ~15 bytes
-6 bytes thanks to @Kevin Cruijssen
Obligatory stream abuse answer

```
n->{for(long t=10;t>9;n=(n+"").chars().mapToLong(i->i).reduce(1,(x,y)->x*(y-48)))System.out.println(t=n);}

```

Try it online
> 3 votes

# Answer
# C (gcc), 58 bytes

```
f(n,t){for(;n=printf("%d\n",t=n)>2;)for(;n*=t%10,t/=10;);}

```

Try it online!

Iterative approach turns out to be 1 byte shorter.

```
f(n,t){
    for(;n=printf("%d\n",t=n)   //print and update current number
            >2;)                //until only one digit is printed
        for(;n*=t%10,t/=10;);   //n*= product of digits of t (step)
}

```

---

## C (gcc), ~~61~~ 59 bytes (recursive)

```
f(n){printf("%d\n",n)>2&&f(p(n));}p(n){n=n?n%10*p(n/10):1;}

```

Try it online!

~~Recursion seems to be shorter than iteration for both print and step...~~
> 3 votes

# Answer
# V (vim), ~~43 30~~ 29 bytes

```
qqhYp:s/./*&/g
x0C<C-r>=<C-r>"
<esc>@qq@q

```

Try it online!

-13 bytes from DJMcMayhem. Go upvote their answer!

-1 byte from user41805.

Takes advantage of the fact that this only stops on single digit numbers.

## Explanation

```
qqhYp:s/./*&/g
qq                  create a macro @q:
  l                  move one char right
                     this is the break condition, since you cant
                     move to the right from a single digit
   Yp                duplicate the current line
     :s/./*&/g       add "*" before each digit

x0C<C-r>=<C-r>"
x                    delete first char
 0C                  cut the current line and store in " register
   <C-r>=            evaluate the following string:
         <C-r>"      the value in " register
                     and paste in current line

@qq@q
@q                   recursively call macro
  q                 close macro
   @q               call macro q

```
> 3 votes

# Answer
**Swift, 115 bytes**

```
func m(a:Int){
print("\(a)")
var b=1,c=a
while c>0{
b*=c%10
c/=10}
b>9 ? m(a:b):print("\(b)")}
m(a:277777788888899)

```

Try it online!
> 2 votes

# Answer
# PicoLisp, ~~73~~ 72 bytes

```
(de f(x)(if(> 10 x)(list x)(cons x(f(apply *(mapcar format(chop x)))))))

```

Try it online!
> 2 votes

# Answer
# Japt, 15 bytes

I got some help from Shaggy on this one.

```
@pUÌì × Ì>9}f U

```

Run it online
> 2 votes

# Answer
# Stax, 4 bytes

```
▒σ╛g

```

Run and debug it

Unpacked, it's pretty simple.

```
gu  use the rest of the program to generate values until a duplicate is encountered
    output implicitly
E:* calculate product of digits

```
> 2 votes

# Answer
# Perl 6, 23 bytes

```
{$_,{[*] .comb}...10>*}

```

Try it online!
> 2 votes

# Answer
# Husk, 5 bytes

```
U¡oΠd

```

Try it online!

## Explanation

```
U¡oΠd
 ¡    iterate infinitely, collecting results of each iteration
  o   combination of 2 functions
    d get digits
   Π  multiply all of them
U     cut at first duplicate value

```
> 2 votes

# Answer
# , ~~59~~ 55 bytes

*Edit: -2 bytes thanks to Giuseppe, quickly superseded by -4 bytes (a different way) thanks to Robin Ryder*

```
n=scan();while(print(n)>9)n=prod(utf8ToInt(c(n,""))-48)

```

Try it online!

A different method to Giuseppe's answer for the same number of bytes, here as a full recursive function instead of the (often-shorter) approach of taking input from the console using `scan`.
> 2 votes

# Answer
# POSIX Shell + Utilities, 59 bytes

```
echo $1
[ ${#1} = 1 ]||$0 $(echo $1|fold -w1|paste -sd*|bc)

```

```
$ cat cg; echo; wc -c cg
echo $1
[ ${#1} = 1 ]||$0 $(echo $1|fold -w1|paste -sd*|bc)
59 cg
$ ./cg 277777788888899
277777788888899
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0
$ ./cg 25
25
10
0
$ ./cg 327
327
42
8
$ ./cg 68889
68889
27648
2688
768
336
54
20
0

```
> 2 votes

# Answer
# Go, 87 bytes

```
import."fmt"
func f(n int){Println(n)
s:=1
if n<10{return}
for;n>0;n/=10{s*=n%10}
f(s)}

```

Attempt This Online!
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
,[1svy*}Ð,gΘ#

```

Try it online!

Explanation:

```
,            //Print input
[            //Begin infinite loop
    1s       //Set 1 to the item before the input in the stack
    v        //Loop over the input
        y*   //Add the current character to the stack and multiply
    }        //End loop
    Ð        //Triplicate result
    ,        //Print result
    gΘ       //Check if length == 1
#            //If so, end

```

Leaving out the two prints can save two bytes while still outputting the result, thanks to implicit output. Without that restriction this would be 11.
> 2 votes

# Answer
# java 8, ~~105~~ 104 bytes

-1 byte thanks to @Benjamin Urquhart, replacing `'0'` with `48`

```
i->{String s="";for(;(s+=i+"\n")!=""&i>9;){long m=1;for(byte c:(""+i).getBytes())m*=c-48;i=m;}return s;}

```

TIO
> 1 votes

# Answer
# Factor, ~~79~~ 72 bytes

```
: f ( x -- ) [ 10 >base [ 48 - ] map product dup dup . 9 > ] loop drop ;

```

Try it online!
> 1 votes

# Answer
# ink, 66 bytes

```
=p(n)
{n}{n<10:->->}
~temp v=1
-(a)~v=v*n%10
~n=n/10
{n:->a}->p(v)

```

Try it online!

# Explanation

```
=p(n)       // entry point - a stitch called p, with one parameter.
{n}         // print the value of n
{n<10:->->} // if n is a single digit, divert to wherever we entered from
~temp v=1   // declate a variable v, where we keep track of the product, and set it to 1
-(a)        // a labeled gather - we can jump here later
~v=v*n%10   // multiply v by (n mod 10) - the last digit in n
~n=n/10     // divide n by 10 - removing the last digit
{n:->a}     // if n is nonzero, go back to a
->p(v)      // if we reach this, divert to the top, this time with n set to the value of v

```

Doesn't feel very golfed, but I have no idea how you'd improve it.
> 1 votes

# Answer
# Python 2, 87 bytes

```
b=input()
while 1:
 a=str(b);print a;b=1
 if len(a)<2:break
 for d in list(a):b*=int(d)

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 100 bytes

```
	P =INPUT
O	OUTPUT =N =P	:(S)
S	P =GT(N,9) 1	:F(END)
D	N LEN(1) . D REM . N	:F(O)
	P =P * D	:(D)
END

```

Try it online!

A nice round 100 bytes!

```
	P =INPUT			;* Store input to P
O	OUTPUT =N =P	:(S)		;* print P and set N to P
S	P =GT(N,9) 1	:F(END)		;* if N > 9, set P (the digit product) to 1
D	N LEN(1) . D REM . N	:F(O)	;* take the first digit of N as D and set remaining digits to N
					;* if N is an empty string, goto label O
	P =P * D	:(D)		;* calculate the digit product, then return to D
END

```
> 1 votes

# Answer
# C, ~~138~~ 115 bytes

```
long atol(char*);main(c,v)char**v;{long z=1,n=atol(v[1]);for(;printf("%ld\n",n),n>9;n=z,z=1)for(;z*=n%10,n/=10;);}

```

Pass the number as a first command line argument.

Thanks to attinat for help with saving some bytes.

Ungolfed and prettyified:

```
long atol(char *);
main(c, v) char **v; {
    long z = 1,n = atol(v[1]);
    for(; printf("%ld\n", n), n > 9; n = z, z = 1)
        for(; z *= n % 10, n /= 10;);
}

```
> 1 votes

# Answer
# Pyth, 9 bytes

```
j.u*FsM`N

```

Try it here!

If we're allowed to output as an array, the `j` at the start is unnecessary, giving 8 bytes.
> 1 votes

# Answer
# Racket, 107 bytes

```
(define(f n)(if(> 10 n)(list n)(cons n(f(apply *(map(λ(x)(-(char->integer x)48))(string->list(~v n))))))))

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), ~~192 191~~ 180 bytes

```
using C=System.Console;class A{static void Main(string[] a){long i,k;var b=a[0];for(C.WriteLine(b);(k=b.Length)>1;C.WriteLine(b=i.ToString())){i=1;for(int j=0;j<k;)i*=b[j++]-48;}}}

```

Try it online!

Pretty much just naive looping. I feel like that's a bit of a silly way to do it but here we are. Had a weird issue early on where the input didn't match the output, because it was overflowing an `int`, so here we are with `long`s. I could upgrade it to `BigInteger` if I needed to, though that would cost a few bytes.

I swear I always end up with off by ones when I do loops here, and it annoys me to no end.

Ungolfed-ish version:

```
using C=System.Console;
class A{
    static void Main(string[] a){
        long i,k;
        var b=a[0];
        for(C.WriteLine(b);(k=b.Length)>1;C.WriteLine(b=i.ToString())){
            i=1;
            for(int j=0;j<k;)i*=b[j++]-48;
        }
    }
}

```

# Works for all integers less than int.MAX\_VALUE digits long, C# (.NET Core), 204 bytes

```
using C=System.Console;class A{static void Main(string[] a){System.Numerics.BigInteger i;int j,k;var b=a[0];for(C.WriteLine(b);(k=b.Length)>1;C.WriteLine(b=i.ToString())){i=1;for(j=0;j<k;)i*=b[j++]-48;}}}

```

Try it online!
> 1 votes

# Answer
# Attache, ~~28~~ 27 bytes

```
{If[_>9,_'$@Prod@List@_,_]}

```

Try it online!

Oddly enough, the recursive approach, rather than a tacit approach, seems to be shortest. (There is a bug in `NestListWhile` involving currying, but even with the bugfix it'd be 3 bytes longer.)

## Explanation

```
{
    If[ _ > 9 ,
        ?? if this is true, return a list
        [
            ?? with the current number
            _,
            ?? followed by this function called on the digital product
            ...$[ Prod[Digits[_]] ]
        ],
        ?? otherwise, return _
        _
    ]
}

```

## Alternative

**32 bytes:** `NestListWhile<~Prod@List,{_>9}~>`
> 1 votes

# Answer
## c++, lambda function, 72 bytes

```
[](auto n){while(cout<<n<<endl&&n>9){auto t=n;for(n=1;n*=t%10,t/=10;);}}

```

try it online
> 1 votes

# Answer
## Clojure, 73 bytes

```
#(loop[i %](prn i)(if(> i 9)(recur(apply *(for[c(str i)](-(int c)48))))))

```
> 1 votes

# Answer
# Scala, 83 bytes

```
def^(n:Long):Long={println(n);if(n>9)^((n+"").map(x=>(x-48).toLong).product)else n}

```

Try it online!
> 1 votes

# Answer
# Befunge-98 (FBBI), ~~43~~ 42 bytes

```
&;1\v>#;:.:9`!#@_;
>$$  ^
^#::< '*%ap25/a_

```

Try it online!

The first line takes input, prints the values and runs until a value `<=9` is reached. The third line computes the product of digits of an integer (26 bytes on its own).
> 1 votes

# Answer
# Pip, 9 bytes

```
W9<Pa$*:a

```

Try it online!

### Explanation

```
           a is command-line argument (implicit)
W          While...
   Pa      (print a's value)
 9<        ... a is greater than 9, i.e. more than one digit:
     $      Fold
        a   (the digits of) a
      *     on multiplication
       :    and assign back to a

```

Printing `a` in the loop header lets us output its value both before the loop and when the loop terminates.
> 1 votes

# Answer
# \>\<\>, ~~31~~ 29 bytes

Saved 2 bytes thanks to Jo King

```
:nao:a),1}\~
1:,a}*{%a:/!?:-%

```

Try it online!
> 1 votes

# Answer
# Factor \+ `math.unicode`, 40 bytes

```
[ [ .s >dec 48 v-n Π dup 9 > ] loop . ]

```

Try it online!

* `[ ... dup 9 > ] loop` loop while top of stack is greater than nine
* `.s` print stack non-destructively
* `>dec` convert number to string
* `48 v-n` convert string to list of digits
* `Π` product of a list of numbers
* `.` print the leftover number (which will be the final output)
> 1 votes

# Answer
# Python 3, 47 bytes

```
def f(n):print(n);n>9>f(eval('*'.join(str(n))))

```

First Python 3 answer here.

Try it online!
> 1 votes

# Answer
# FunStack alpha, 38 bytes

```
Product Minus 48 Show compose3 fixiter

```

Try it at Replit: pass the input number as a command-line argument and enter the program on stdin.

### Explanation

The `fixiter` modifier iterates a function until it reaches a fixed value, returning the full list of intermediate values. This is exactly what we want; there is a slight complication because the builtin `ToBase` function, which returns a list of digits, converts zero to an empty list rather than a list containing `0`. So instead, we convert the number to a string and then convert each character to the corresponding digit.

```
                      compose3          Compose these three functions:
                 Show                     Convert number to string
        Minus 48                          Subtract 48 from each character
Product                                   Take the product of the character codes
                               fixiter  Iterate that function, stopping when a fixed point
                                        is reached, and return a list of intermediate values

```
> 1 votes

# Answer
# Vyxal 3, 2 bytes

```
ᵘΠ

```

Try it Online!

2 bytes with a new modifier. Come try Vyxal 3!
> 1 votes

# Answer
# Vyxal, `j`, 3 bytes

```
⁽Π↔

```

Try it Online!

Very nice little 3 byter here. Uses the same method as the 05ab1e answer.

## Explained

```
⁽Π↔
⁽Π  # lambda x: product(x) // treats numbers as a list of digits
 ↔ # repeat the above function until the result doesn't change, collecting intermediate results.

```
> 0 votes

# Answer
# Pyt, 6 bytes

```
Đ`ҎĐłŕ

```

Try it online!

```
Đ         Implicit input; duplicate top of stack
 `  ł     do while top of stack is not 0 (consumes top of stack when checking)
  Ҏ       digit product of top of stack
   Đ      duplicate top of stack
     ŕ    remove top of stack (duplicate 0); implicit print

```
> 0 votes

# Answer
it's not efficient but gets the job done

```
echo 777777777777777777777777777777777779999999999999999999933333333333  |

gawk -M 'function __(_){return _*_==_?+$_:$_*__(--_)}($_=__(NF*=!/0/))_' FS=

```

> ```
> 815859530632739726716133814001433680647636177446909421
>
> ```
> 0 votes

---
Tags: code-golf, math, arithmetic, repeated-transformation
---