title: Display a clock face

text:
# Question
Title: Display a clock face
Display the 12 numbers on a clock face exactly like this:

```
           12
     11           1

 10                   2

9                       3

  8                   4

      7           5
            6

```

To better see the grid, here's one with dots:

```
...........12............
.....11...........1......
.........................
.10...................2..
.........................
.........................
9.......................3
.........................
.........................
..8...................4..
.........................
......7...........5......
............6............

```

Note that the grid is stretched in width by a factor of two to make it look more square.

Also note that two-digit numbers are aligned with their ones digit in place. The 9 digit should be flush against the left.

Return or print the result as a multiline string (not a list of lines). Any trailing spaces are optional. The final newline also optional.

# Answer
> 26 votes
# Charcoal, 40 bytes

```
Ｆ¹²«Ｍ⁻↔⁻¹⁴⊗÷×⁴ι³¦⁸⁻⁴↔⁻⁷÷×⁴﹪⁺³ι¹²¦³Ｐ←⮌Ｉ⊕ι

```

Try it online! Link is to verbose version of code. Explanation: Computes the offsets between each digit mathematically. Charcoal is 0-indexed (thus the  to output \\$ 1 \ldots 12 \\$), so the formulae for the horizontal and vertical offsets are as follows:

$$ \begin{align} \delta x &= \left \lvert 14 - 2 \left \lfloor \frac {4i} 3 \right \rfloor \right \rvert - 8 \\ \delta y &= 4 - \left \lvert 7 - \left \lfloor \frac {4i'} 3 \right \rfloor \right \rvert \end{align} $$

where \\$ i' = i + 3 \pmod {12} \\$.

# Answer
> 23 votes
# JavaScript (Node.js), 91 bytes

Not a very clever approach, but I've failed to find anything shorter at the moment.

```
_=>`K12
E11K1

A10S2

9W3

B8S4

F7K5
L6`.replace(/[A-Z]/g,c=>''.padEnd(Buffer(c)[0]&31))

```

Try it online!

# Answer
> 15 votes
# 05AB1E, ~~39~~ ~~33~~ 31 bytes

Thanks to *Magic Octopus Urn* for saving 6 bytes!

### Code

```
6xsG12N-N•°£•NèØú«тR∞Nè¶×]\6».c

```

Some 33 byte alternatives:

```
711ćŸā•Σ°w•₂вú‚øJƵt3в¶×‚ø»6xŠ».c¦
6xsŸ5L•Σ°w•₂вúõ¸ì‚ζJï2ÝÂ«Ć¶×)ø».c
6xsG¶12N-N•Θ{©•₂вNèú«ƵB∞Nè¶×]6J.c
6xsG12N-N•Θ{©•₂вNèú«тR∞Nè¶×]6s».c

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 10 votes
# 6502 machine code (C64), 82 76 73 bytes

```
00 C0 A2 0E BD 38 C0 29 03 A8 A9 0D 20 25 C0 BD 38 C0 4A 4A A8 A9 20 20 25 C0
BD 29 C0 20 D2 FF CA 10 E1 60 20 D2 FF 88 10 FA 60 36 35 37 34 38 33 39 32 30
31 31 31 31 32 31 31 2C 1A 4C 0B 5C 03 4C 00 06 2C 00 15 00 2C

```
* -6 bytes, thanks to Arnauld for the clever idea :)
* another -3 bytes after Arnauld's idea not to treat leading `1` digits specially

The idea here is to only store the digits of all the numbers in the order they are needed. Additional info required is the number of newlines to prepend and the number of spaces in front.

The maximum number of newlines is `3`, so we need 2 bits for this, and the maximum number of spaces is `23`, therefore 5 bits are enough. Therefore, for each digit to print, we can squeeze this info in a single "control byte".

So, the data for this solution takes exactly 30 bytes: 15 single digits and 15 associated "control bytes".

### Online demo

Usage: `SYS49152` to start.

**Commented disassembly**:

```
         00 C0                          ; load address
.C:c000  A2 0E       LDX #$0E           ; table index, start from back (14)
.C:c002   .mainloop:
.C:c002  BD 38 C0    LDA .control,X     ; load control byte
.C:c005  29 03       AND #$03           ; lowest 3 bits are number of newlines
.C:c007  A8          TAY                ; to Y register for counting
.C:c008  A9 0D       LDA #$0D           ; load newline character
.C:c00a  20 25 C0    JSR .output        ; repeated output subroutine
.C:c00d  BD 38 C0    LDA .control,X     ; load control byte
.C:c010  4A          LSR A              ; and shift by two positions for ...
.C:c011  4A          LSR A              ; ... number of spaces
.C:c012  A8          TAY                ; to Y register for counting
.C:c013  A9 20       LDA #$20           ; load space character
.C:c015  20 25 C0    JSR .output        ; repeated output subroutine
.C:c018  BD 29 C0    LDA .digits,X      ; load current digit
.C:c01b  20 D2 FF    JSR $FFD2          ; output
.C:c01e  CA          DEX                ; decrement table index
.C:c01f  10 E1       BPL .mainloop      ; still positive -> repeat
.C:c021  60          RTS                ; and done.
.C:c022   .outputloop:
.C:c022  20 D2 FF    JSR $FFD2          ; output a character
.C:c025   .output:
.C:c025  88          DEY                ; decrement counting register
.C:c026  10 FA       BPL .outputloop    ; still positive -> branch to output
.C:c028  60          RTS                ; leave subroutine
.C:c029   .digits:
.C:c029  36 35 37 34 .BYTE "6574"
.C:c02d  38 33 39 32 .BYTE "8392"
.C:c031  30 31 31 31 .BYTE "0111"
.C:c035  31 32 31    .BYTE "121"
.C:c038   .control:
.C:c038  31 2C 1A 4C .BYTE $31,$2C,$1A,$4C
.C:c03c  0B 5C 03 4C .BYTE $0B,$5C,$03,$4C
.C:c040  00 06 2C 00 .BYTE $00,$06,$2C,$00
.C:c044  15 00 2C    .BYTE $15,$00,$2C

```

# Answer
> 7 votes
# Perl 6, ~~76 74~~ 70 bytes

```
"K12
E11K1

A10S2

9W3

B8S4

F7K5
L6"~~say S:g{<:Lu>}=" "x$/.ord-64

```

Try it online!

Port of Arnauld's answer until I can come up with something shorter.

# Answer
> 6 votes
# Java ~~8~~ 11, ~~141~~ 138 bytes

```
v->{for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())System.out.print(x<59?" ".repeat(x-48):(char)(x>76?10:x-17));}

```

Try it online (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)

Explanation is similar as below, but it uses `" ".repeat(x-48)` for the spaces instead of format with `"%"+(x-48)+"s"`.

---

# Java 8, 141 bytes

```
v->{for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())System.out.printf("%"+(x>58?"c":x-48+"s"),x>76?10:x>58?x-17:"");}

```

Try it online.

**Explanation:**

```
v->{                        // Method with empty unused parameter and no return-type
  for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())
                            //  Loop over the bytes of the above String:
    System.out.printf("%"+  //   Print with format:
     (x>58?                 //    If the character is a letter / not a digit:
       "c"                  //     Use "%c" as format
      :                     //    Else:
       x-48+"s"),           //     Use "%#s" as format, where '#' is the value of the digit
     x>76?                  //    If the byte is 'N':
      10                    //     Use 10 as value (newline)
     :x>58?                 //    Else-if the byte is not a digit:
      x-17                  //     Use 48-58 as value (the 0-9 numbers of the clock)
     :                      //    Else:
      "");}                 //     Use nothing, because the "%#s" already takes care of the spaces

```

**Further explanation `92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G`:**

* All the digits will be replaced with that amount of spaces. (For 11 spaces it's therefore `92`.)
* All 'N' are new-lines
* All \['A','J'\] are clock digits (\[0,9\])

# Answer
> 6 votes
# HTML + JavaScript (Canvas), 13 + 161 = 174 bytes

Arbitrary canvas positioning uses 6 bytes.

```
with(C.getContext`2d`)with(Math)for(font='9px monospace',textAlign='end',f=x=>round(sin(x*PI/6)*6)*measureText(0).width*2,x=13;--x;)fillText(x,f(x)+80,f(9-x)+80)
```

```
<canvas id=C>
```

With grid for comparison:

```
with(C.getContext`2d`)with(Math){
    for(font='9px monospace',textAlign='end',f=x=>round(sin(x*PI/6)*6)*measureText(0).width*2,x=13;--x;)fillText(x,f(x)+80,f(9-x)+80)
    for(globalAlpha=0.2,y=-6;y<=6;y++)fillText('.'.repeat(25),6*measureText('.').width*2+80,y*measureText(0).width*2+80)
}
```

```
<canvas id=C>
```

---

## Explanation of Positioning Formula

See my JavaScript with SVG answer.

# Answer
> 6 votes
# , ~~75~~ 68 bytes

```
write("[<-"(rep("",312),utf8ToInt('*`®÷ĥĹĚä—M'),1:12),1,25)

```

Try it online!

Compressed the digits positions. Did this after spending lots of time trying to come up with a trigonometric answer (see history of edits).

Inspired by this other R answer buy J.Doe - upvote it !

Saved 7 bytes thanks to J.Doe.

# Answer
> 5 votes
# Python 2, 97 bytes

```
for i in range(7):w=abs(3-i);print'%*d'%(1-~w*w,12-i),'%*d'%(24-3**w-2*w,i)*(w<3),'\n'*min(i,5-i)

```

Try it online!

Computes all spacings and newlines in the loop

# Answer
> 5 votes
## Haskell, ~~88~~ 87 bytes

```
f=<<"k12{e11k1{{a10s2{{{9w3{{{b8s4{{f7k5{l6"
f c|c>'z'="\n"|c>'9'=' '<$['a'..c]|1<2=[c]

```

The encode-spaces-as-letters method (first seen in @Arnauld's answer) in Haskell. Using `{` and expanding it to `\n` is one byte shorter than using `\n` directly.

Try it online!

# Answer
> 5 votes
# R, ~~168~~ ~~159~~ 125 bytes

The naive solution of writing the numbers at the prescribed points in a text matrix. Points are stored as UTF-8 letters decoded via `utf8ToInt`

```
"!"=utf8ToInt
write("[<-"(matrix(" ",25,13),cbind(!"LMFGSBCWAYCWGSM",!"AABBBDDDGGJJLLM")-64,-64+!"ABAAAA@BICHDGEF"),1,25,,"")

```

Dropped 9 bytes with JayCe's suggestion to use `write` and avoid defining the matrix.

Dropped another 34 bytes with JayCe's storage suggestion.

# Answer
> 5 votes
# Jelly, 32 bytes

```
⁶ẋ“¿×¿ Œ4ç4Œ!¿Ø‘ż“øn0œ’Œ?D¤Fs25Y

```

A full program which prints the result.

**Try it online!**

### How?

(I have not yet thought of/found anything shorter than `“¿×¿ Œ4ç4Œ!¿Ø‘` which seems long to me for this part - bouncing / base-decompression / increments, nothing seems to save!)

```
⁶ẋ“¿×¿ Œ4ç4Œ!¿Ø‘ż“øn0œ’Œ?D¤Fs25Y - Main Link: no arguments
⁶                                - space character
  “¿×¿ Œ4ç4Œ!¿Ø‘                 - code-page indices list = [11,17,11,32,19,52,23,52,19,33,11,18]
 ẋ                               - repeat (vectorises) -> [' '*11, ' '*17, ...]
                          ¤      - nilad followed by link(s) as a nilad:
                 “øn0œ’          -   base 250 number = 475699781
                       Œ?        -   first natural number permutation which would be at
                                 -   index 475699781 if all permutations of those same
                                 -   natural numbers were sorted lexicographically
                                 -   = [12,11,1,10,2,9,3,8,4,7,5,6]
                         D       -   to decimal lists = [[1,2],[1,1],[1],[1,0],[2],[9],[3],[8],[4],[7],[5],[6]]
                ż                - zip together = [[' '*11, [1,2]], [' '*17, [1,1]], ...]
                           F     - flatten = [' ',' ',...,1,2,' ',' ',...,1,1,...]
                            s25  - split into chunks of 25 (trailing chunk is shorter)
                               Y - join with new line characters
                                 - implicit print

```

# Answer
> 5 votes
# Rust, 96 bytes

```
||format!(r"{:13}
     11{:12}

 10{:20}

9{:24}

  8{:20}

{:7}{:12}
{:13}",12,1,2,3,4,7,5,6)

```

Try it online!

# Answer
> 5 votes
# brainfuck, ~~240~~ 235 bytes

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

```

Try it online!

**Commented code**

```
++++++++++                              Put 10 in cell 0
[>++>+>+++>+++++>++>++[<]>-]            Loop 10 times incrementing to leave 0 20 10 30 50 20 20 in memory
>>>++                                   30 plus 2 = 32 (ascii space)
...........>-.+.                        print 11spaces followed by 12 (ascii 49 50)
<<.>.....>-..<...........>.             print 1newline 5spaces 11 11spaces 1
<<..>.>.-.>-[<<.>>-]<++.                print 2newlines 1space 10 19spaces 2
<<...>>+++++++.>>+++[<<<.>>>-]<<------. print 3newlines         9 23spaces 3
<<...>..>+++++.<<<-[>>.<<-]>>>----.     print 3newlines 2spaces 8 19spaces 4
<<..>......>+++.<...........>--.        print 2newlines 6spaces 7 11spaces 5
<<.>............>+.                     print 1newline  12spaces 6

```

A rare example where the text is repetitive enough that the brainfuck program is less than ~~twice~~ 1.6 times the length of the output!

2 bytes saved by suggestion from Jo King: `>>>>>>-` -\> `[<]>-`

3 bytes saved by moving the third 20-place downcounter from far right of the ascii codes `10 30 50` to immediately to the left of them. Saves `<<>>` when filling the gap between `8` and `4` but adds 1 byte to the line `>>>++` .

**Original version**

```
++++++++++                              Put 10 in cell 0
[>+>+++>+++++>++>++>++<<<<<<-]          Loop 10 times incrementing to leave 0 10 30 50 20 20 20 in memory
>>++                                    30 plus 2 = 32 (ascii space)
...........>-.+.                        print 11spaces followed by 12 (ascii 49 50)
<<.>.....>-..<...........>.             print 1newline 5spaces 11 11spaces 1
<<..>.>.-.>-[<<.>>-]<++.                print 2newlines 1space 10 19spaces 2
<<...>>+++++++.>>+++[<<<.>>>-]<<------. print 3newlines         9 23spaces 3
<<...>..>+++++.>>>-[<<<<.>>>>-]<<<----. print 3newlines 2spaces 8 19spaces 4
<<..>......>+++.<...........>--.        print 2newlines 6spaces 7 11spaces 5
<<.>............>+.                     print 1newline  12spaces 6

```

# Answer
> 4 votes
# C (gcc), 145 137 125 bytes

Only the tab positions are hard-coded: all the line spacings and clock values are generated in the loop.

Thanks again to ceilingcat for the suggestions.

```
i,j,k;f(char*t){for(i=7;i--;t=memset(t+sprintf(t,"%*d%*d"+3*!j,"NHDA"[j]-65,6+i,"AMUY"[j]-65,6-i),10,k=j+i/4)+k)j=i>3?6-i:i;}

```

Try it online!

# Answer
> 4 votes
# PHP, 97 bytes

```
<?=gzinflate(base64_decode(U1CAA0MjLghtqIAkyMWlYGiggAmMuLi4LBWwA2OgnIKCBRYZEy6IHQrmSIKmXMhKzAA));

```

Try it online!

This is a hard coded compressed string. I couldn't find a solution shorter than this!

# Answer
> 4 votes
# C (gcc), 125 109 105 bytes

```
x,*d=L"<;1:2938475640P`P05";main(i){for(;i=d[12];printf("%*d",i/4,*d++-48))for(x=i&3;x--;)puts("");}

```
* -16 bytes (-3 for better loop arrangement, -13 for directly including the non-printable chars) thanks to Jonathan Frech.
* -4 bytes by replacing a division for a shift and abusing the fact that on many systems (like the one hosting TIO), `sizeof(wchar_t) == sizeof(int)` -- won't work on windows :) Thanks ErikF for the idea.

Try it online!

This is a port of my general idea from the 6502 solution to C. It's a bit modified: Instead of having a flag for a leading `1`, the character is printed as a decimal by subtracting 48, so 10 - 12 are encoded as `:` to `<`.

# Answer
> 3 votes
# Powershell, ~~94~~ ~~88~~ 82 bytes

Direct Powershell format operator. `{i,w}` means a placeholder for a parameter with index `i`, width of the placeholder is `w` with right align.

```
"{11,13}
{10,7}{0,12}

 10{1,20}

9{2,24}

  8{3,20}

{6,7}{4,12}
{5,13}"-f1..12

```

# Powershell, 88 bytes

Port of Arnauld's Javascript answer

*-6 bytes thanks to @AdmBorkBork*

```
[RegEx]::Replace("K12
E11K1

A10S2

9W3

B8S4

F7K5
L6",'[A-Z]',{' '*("$args"[0]-64)})

```

To better see the grid, use `'.'` instead `' '`.

# Answer
> 3 votes
# Pyke, 37 bytes

```
3B 32 35 75 07 0d 13 0c 22 14 35 18 44 74 5F 74 2B 46 6F 68 32 C4 52 7D 74 2A 31 32 25 31 32 7C 60 52 2D 29 73

```

Try it here! (raw bytes)

```
;25Dt_t+Foh2.DR}t*12%12|`R-)s

```

Try it here! (Human readable)

```
                              - o = 0
;25                           - set line width to 25 characters
                              -      `[13, 19, 12, 34, 20, 53, 24]`
                              -       (In hex version, encoded in base 256, regular version in input field)
    t_t                       -     reversed(^[1:])[1:]
   D   +                      -    ^^ + ^
        Foh2.DR}t*12%12|`R-)  -   for i in ^:
         o                    -            o++
          h                   -           ^+1
           2.DR               -          divmod(^, 2)
               }t             -         (remainder*2)-1
                 *            -        quotient * ^
                  12%         -       ^ % 12
                     12|      -      ^ or 12 (12 if 0 else ^)
                        `     -     str(^)
                         R-   -    ^.rpad(i) (prepend spaces such that length i)
                            s -  sum(^)
                              - output ^ (with newlines added)

```

# Answer
> 3 votes
# brainfuck, ~~315~~ 313 bytes

*saved 2 bytes thanks to ovs!*

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

```

Try it online!

all in one code block:

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

```

# Answer
> 2 votes
# JavaScript with SVG, 188 bytes

Arbitrary line height of 120% uses 4 bytes.

```
with(Math)for(s='<pre><svg viewBox=-8-8+16+16 style=font-size:1;text-anchor:end>',f=x=>round(sin(x*PI/6)*6),x=13;--x;)s+=`<text x=${f(x)*2}ch y=${f(9-x)*1.2}>${x}</text>`
document.write(s)
```

With grid for comparison:

```
with(Math)for(s='<pre><svg viewBox=-8-8+16+16 style=font-size:1;text-anchor:end>',f=x=>round(sin(x*PI/6)*6),x=13;--x;)s+=`<text x=${f(x)*2}ch y=${f(9-x)*1.2}>${x}</text>`
for(y=-6;y<=6;y++)s+=`<text x=12ch y=${y*1.2} style=fill:#0002>${'.'.repeat(25)}</text>`
document.write(s)
```

---

## Explanation of Positioning Formula

Let `f(x) = round(sin(x * π/6) * 6)`.

Assuming the origin is the center of the clock, the grid coordinates of the right-most digit of any given clock number `x` is \[`f(x) * 2`, `f(9 - x)`\].

# Answer
> 2 votes
# Attache, 69 bytes

```
{ReplaceF["l12
f11l1

b10t2

9x3

c8t4

g7l5
m6",/"\\l",sp&`*@STN]}

```

Try it online!

This encodes each run of spaces as: `NTS[count of spaces]`; `NTS` is the "numeric to short" builtin, which allows numbers to be expressed as strings. E.g., `NTS[95] = $R1` and `NTS[170297] = $XQO`. `STN` is the inverse of this builtin.

This answer replaces (`ReplaceF`) all occurences of letters (`/\l/`) in the input with the result of the function `sp&`*@STN`, which firsts decodes the letter and then repeats `sp` (a space) that many times.

# Answer
> 2 votes
# Swift, ~~178~~ 165 bytes

~~`var b="";for c in"L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6"{let i=c.unicodeScalars.first!.value;if c=="n"{b+="\n"}else if i>64{for _ in 0..<(i-65){b+=" "}}else{b+="(c)"}};print(b)`~~

Based on what Downgoat posted, I've reduced this to 165 bytes:

`print("L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6".unicodeScalars.map{let x=Int($0.value);return x==110 ?"\n":(x>64 ?String(repeating:" ",count:x-65):"($0)")}.joined())`

Expanded out, with `$0` converted to a named variable:

`print("L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6".unicodeScalars.map { c in
 let x = Int(c.value)
 return x == 110 ? "\n" : (x>64 ? String(repeating:" ", count: x-65) : "(c)")
}.joined())`

The input string is encoded as follows: Uppercase letters (`A-Z`) represent blocks of spaces, offset by 65. So `A` means 0 spaces, `B` means 1 space, the first `L` means 11 spaces, etc. `n`s are converted to newlines. All other characters are printed as-is.

Run it online here (thanks, mbomb007)

# Answer
> 2 votes
# vim, 103 bytes

```
25a <ESC>r30r9O0i <C-v><ESC>15l2xA <C-v><ESC><ESC>0"aDddqbYp<C-x>e<C-a>q2@a@b4@a@b6@aggqbYP<C-a>e<C-x>q@axr 2hr2@b4@a@b6@ayyjpr lr yyj2p2j2p2jp

```

`<ESC>` is 0x1b, `<C-a>` is 0x01, `<C-x>` is 0x18, and `<C-v>` is 0x16.

This includes all trailing spaces because I didn't notice they were optional until I'd finished for the additional challenge.

## Annotated

```
25a <ESC>r30r9                            # create the 9...3 line
o0i <C-v><ESC>15l2xA <C-v><ESC><ESC>"a0D  # create macro a that moves 2 spaces from the middle to the ends
                                          # 15 is a magic number that lets the same macro work for the 6 and 12 lines
dd                                        # delete empty line
qb                                        # record macro b to...
  Yp                                      #    duplicate line (down)
  <C-x>e<C-a>                             #    adjust numbers
q
2@a                                       # adjust spacing for line 8..4
@b4@a                                     # create line 7..5
@b6@a                                     # create line 6
gg                                        # move cursor to first line
qb                                        # record macro b to...
  YP                                      #    duplicate line (up)
  <C-a>e<C-x>                             #    adjust numbers
q
@axr 2hr2                                 # adjust spacing for 2-digit numbers
@b4@a                                     # 11..1
@b6@a                                     # 12
yyjpr lr yy                               # add a line of all spaces below 12, and copy to default register
j2p2j2p2jp                                # add the rest of the blank lines

```

Try it online!

# Answer
> 1 votes
# Red, 151 bytes

```
foreach[a b c d][13 12 1""7 11 12 1 1""1""3 10 20 2 1""1"^/"0 9 24 3 1""1"^/"3 8 20 4 1""1""7 7 12 5 13 6 1""][print rejoin[pad/left b a pad/left d c]]

```

Try it online!

# Answer
> 1 votes
# T-SQL, 132 bytes

```
PRINT SPACE(11)+'12
     11           1

 10'+SPACE(20)+'2

9'+SPACE(23)+'3

  8'+SPACE(19)+'4

      7           5
            6'

```

Only 12 bytes shorter than the trivial solution (`PRINT` of the entire string as-is).

Found a variation I like that is much longer (~~235~~ 226 bytes), but much more SQL-like:

```
SELECT CONCAT(SPACE(PARSENAME(value,4)),PARSENAME(value,3),
              SPACE(PARSENAME(value,2)),PARSENAME(value,1))
FROM STRING_SPLIT('11.1..2,5.11.11.1,. .. ,1.10.20.2,. .. ,. .. ,.9.23.3,
                   . .. ,. .. ,2.8.19.4,. .. ,6.7.11.5,12.6.. ',',')

```

`STRING_SPLIT` breaks it into rows at the commas, and `PARSENAME` splits each row at the dots. The 1st and 3rd are used for how many spaces to print, the 2nd and 4th are used for what to display.

(line breaks in this one are just for readability)

# Answer
> 1 votes
# Python 3, ~~112~~ ~~88~~ 87 bytes

A solution using string interpolation.

```
print(f'''{12:13}
{11:7}{1:12}

 10{2:20}

9{3:24}

  8{4:20}

{7:7}{5:12}
{6:13}''')

```

**Try it online!**

*-25 bytes thanks to ovs and Herman L.*

# Answer
> 1 votes
# Pure Bash, 123

`printf` does the heavy-lifting here:

```
n=" 0 a 0 a"
printf -vo %*s%*s\\n 0 a 13 12 7 11 12 1 $n 3 10 20 2$n$n 1 9 24 3$n$n 3 8 20 4$n 7 7 12 5 13 6
echo "${o//a}"

```

Try it online!

# Answer
> 1 votes
# C (gcc), 135 123 110 bytes

This uses a simple encoding where any `c` between `'a'` and `'z'` represents `c-'a'+1` repeated spaces, `'`'` represents a newline, and all other characters are left unchanged.

<pre><code>f(i){char*s="k12`e11k1``a10s2```9w3```b8s4``f7k5`l6`";for(;i=*s;s++)i>96?printf("%*s",i-96,""):putchar(i%86);}
</code></pre>

Try it online!

# Answer
> 1 votes
# Perl 6, 116 bytes

```
my@a=["  "xx 13]xx 13;($_=pi/6*++$;@a[0+|6*(1.1-.cos);0+|6*(1.1+.sin)]=fmt ++$: "%2s")xx 12;@a>>.join>>.&{say S/.//}

```

Try it online!

(Ta @JoKing for saving 26 bytes)

# Perl 6, 142 bytes

```
my@a=[[[32,32]xx 13]xx 13];for 1..12 {$_=$^b*pi/6;@a[round 6*(1-.cos);round 6*(1+.sin)]=[" $b".ords.tail(2)]}
{say S/^.//}(.[*;*].chrs) for @a

```

Try it online!

I wanted to do something... different. So this one calculates the positions of all the digits, via pairs of characters, strips off the initial space and prints the lines.

Easily modifiable for different parameters, e.g. a 45 character wide version with 17 digits.

# Answer
> 1 votes
# Deadfish~, 290 bytes

```
{iii}ii{c}c{ii}dddcic{dddd}c{ii}iiccccc{ii}dddcc{dd}iii{c}c{ii}dddc{dddd}icc{ii}iic{ii}dddcdc{d}dddddd{c}ccccccccc{ii}ddc{dddd}ccc{iiiii}dddc{dd}ddddd{cc}ccc{ii}dc{dddd}dccc{ii}iicc{ii}iiiic{dd}dddd{c}ccccccccc{ii}c{dddd}ddcc{ii}iicccccc{ii}iiic{dd}ddd{c}c{ii}ic{dddd}dddc{ii}ii{c}cc{ii}iic

```

Try it online!

# Answer
> 1 votes
# Canvas, 49 bytes

```
12∙11∙1７«１╋¶10∙2‾⁶２╋¶¶9∙3‾⁹３╋¶¶8∙4‾⁵３╋¶7∙5‾¹２╋6）ｒ

```

Try it here!

# Answer
> 1 votes
# Vyxal `Cm`, 32 bytes

```
6d6(12n-»§⟩»niǎnS꘍J₁SṘmni⌊¶*)_6W

```

Try it Online!

# Bubblegum, 52 bytes

```
00000000: e000 9200 2c5d 0010 6c02 2323 71ec 327c  ....,]..l.##q.2|
00000010: cf28 700c 02f9 d7eb 5929 59a9 e1c8 62ab  .(p.....Y)Y...b.
00000020: 6d60 3fad 8aea 9fc7 e472 69f0 37f4 133e  m`?......ri.7..>
00000030: ff8e e100                                ....

```

Try it online!

# Answer
> 0 votes
# Perl 5, 73 bytes

Port of Arnauld's answer.

```
say"K12
E11K1

A10S2

9W3

B8S4

F7K5
L6"=~s,[A-Z]," "x(ord($&)-64),erg

```

Try it online!

As a one-liner:

```
perl -E'say"K12\nE11K1\n\nA10S2\n\n\n9W3\n\n\nB8S4\n\nF7K5\nL6"=~s,[A-Z]," "x(ord($&)-64),erg'

```

Another approach, but longer:

```
map$s.=$_%26?{12,12,32,11,44,1,80,10,100,2,157,9,181,3,237,8,257,4,293,7,
305,5,325,6}->{$_}||" ":"\n",1..338;
say$s

```

# Answer
> 0 votes
# Python, ~~99~~, 91

~~`print"%13d\n%7d%12d\n\n%3d%20d\n\n\n9%24d\n\n\n%3d%20d\n\n%7d%12d\n%13d"%(12,11,1,10,2,3,8,4,7,5,6)`~~

```
print"""%13d
%7d%12d

%3d%20d

9%24d

%3d%20d

%7d%12d
%13d"""%(12,11,1,10,2,3,8,4,7,5,6)

```

Thanks to Jo King

~~Spaces hardcoded in -- I'm sure its possible to golf the `\n`s down, by repeating but I don't know how...~~

# Answer
> 0 votes
# Javascript, 93 bytes

```
console.log((

_=>`F 12
A11F 1

 10FE2

9FCB3

  8FE4

B7F 5
AC6`.replace(/[A-F]/g,c=>''.padEnd('0x'+c-5))

)())
```

Port of Arnauld's answer to general JS

# Answer
> 0 votes
# 05AB1E, ~~47~~ 42 bytes

```
•1)âÝÈÝ‰ʒ%и&ñjÓU‰÷JêĆ+•₆B'X¶:AuðAuÇ31&×‡.c

```

Try it online!

```
•...•₆B'X¶:AuðAuÇ31&×‡.c  # trimmed program
•...•                     # push 1902039976984631753317213270923121051329258518010...
      B                   # in base...
     ₆                    # 36...
          :               # with all...
       'X                 # literal...
          :               # s replaced by...
         ¶                # newline...
          :               # s...
                     ‡    # with each...
           Au             # letter...
                     ‡    # replaced by the corresponding...
              Au          # letter...
                Ç         # 's codepoint...
                   &      # bitwise and...
                 31       # literal...
             ð            # " "...
                    ×     # s...
                      .c  # with each line centered more to the left
                          # implicit output

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Make the list Fibonacci-like

text:
# Question
Title: Make the list Fibonacci-like
Related, but not dupe.

## Challenge

A list of integers \\$a\_1, a\_2, a\_3, \dots, a\_n\\$ (\\$ n ≥ 1 \\$) is Fibonacci-like if \\$a\_i = a\_{i-1} + a\_{i-2}\\$ for every \\$i \> 2\\$. Note that every list that contains only 1 or 2 integers is Fibonacci-like.

For example, \\$\[1\]\\$, \\$\[6, 9\]\\$, \\$\[6, -4, 2, -2, 0, -2, -2, -4, -6, -10\]\\$, \\$\[7, -1, 6, 5, 11, 16, 27\]\\$ are Fibonacci-like lists.

Your task is, given a list, to determine the minimum amount of numbers that you have to remove from the list to make it Fibonacci-like.

For example, in \\$\[9, 7, -1, 6, 5, 2, 11, 16, 27\]\\$, you have to remove 2 numbers at minimum (\\$9\\$ and \\$2\\$) to transform the list into \\$\[7, -1, 6, 5, 11, 16, 27\]\\$, which is a Fibonacci-like list.

## Input/Output

Input/output can be taken in any reasonable format, taking a list of numbers and returning the minimum number to complete the task.

Testcases:

```
[1, 2] -> 0
[5, 4, 9, 2] -> 1
[9, 7, -1, 6, 5, 2, 11, 16, 27] -> 2
[9, 9, 9, 9, 7, 9, 9, 9, 9, -1, 6, 5, 2, 11, 16, 27] -> 9

```

This is , so shortest answer (in bytes) wins!

# Answer
# JavaScript (ES6), 63 bytes

```
f=([v,...a],x,y)=>1/v?Math.min(v-x-y?1/0:f(a,y,v),1+f(a,x,y)):0

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  [v,             //   v = next value from the input array
      ...a],      //   a[] = all remaining values
  x,              //   x = penultimate value, initially undefined
  y               //   y = previous value, initially undefined
) =>              //
1 / v ?           // if v is defined:
  Math.min(       //   return the minimum of:
    v - x - y ?   //     1) if both x and y are defined and v is not
                  //        equal to x + y:
      1 / 0       //          force this one to fail by using +infinity
    :             //        else:
      f(a, y, v), //          do a recursive call where v is used
    1 +           //     2) increment the final result
    f(a, x, y)    //        and do a recursive call where v is removed
  )               //   end of Math.min()
:                 // else:
  0               //   stop the recursion

```
> 6 votes

# Answer
# , ~~90~~ 88 bytes

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

```
\(v)max(which(sapply(sum(v|1):1,\(i)all(combn(v,i,\(x)any(diff(x)[-1]-head(x,-2)))))),0)
```

Attempt This Online!

Checking Fibonacci-likeness borrowed from @Dominic van Essen's answer to related challenge.
> 3 votes

# Answer
# Pip, 36 bytes

```
#g-MX#*:S H@>_-_=H H_FIFL*CP:GMZgMlg

```

Try It Online! -6 thanks to DLosc.

```
#g                                   # Length of input
  -                                  # Minus
   MX                                # Maximum of
     #*:                             # Map length over
                       FL*           # Flatten each of...
                          CP:        # Cartesian product of...
                              MZ     # Map over zipped
                                gMl  # Input filled with empty lists
                                   g # And input...
                             G       # Get all arguments (i.e. both)
                     FI              # Filter by...
        S H                          # Remove first and last items from
              -                      # Differences of
           @>_ _                     # Shifted value and value
                =                    # Equal to...
                 H H_                # Remove last two items from value?

```
> 3 votes

# Answer
# Vyxal, 19 bytes

```
ẏṗ'?ẏ⊍?$İ₌ÞS¯Ḣc;ÞgL

```

Try it Online!

Long, clunky, and likely to be outgolfed, but it's 1:01am so whatever lol.

Gets all lists of indices where removing the items at those positions gives a Fibonacci list and then gets the length of the smallest indice list.
> 2 votes

# Answer
# APL(Dyalog Unicode), ~~31~~ 30 bytes SBCS

```
≢⌊.-∘∊2(≢⍤⊢×∘⊃↓⍷+/∘,)¨¨(⊢,,¨)\

```

Try it on APLgolf!

`(⊢,,¨)\` gets all non-empty subsequences of the input (taken from Bubbler's tip).

`2(≢⍤⊢×∘⊃↓⍷+/∘,)x` If x is Fibonacci-like, this returns the length of x, otherwise 0.

`≢⌊.-∘∊x` computes the minimum value of `length of input - some number in x`.
> 2 votes

# Answer
# Jelly, 14 bytes

```
ŒP+⁼ƭ3\Ạ$ƇṪLạL

```

A monadic Link that accepts the list of integers and yields the count of elements to remove.

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

### How?

```
ŒP+⁼ƭ3\Ạ$ƇṪLạL - Link: list of integers, A
ŒP             - powerset of A -> all subsequences (Note: shortest to longest)
         Ƈ     - filter keep those for which:
        $      -   last two links as a monad:
     3\        -     three-wise overlapping reduction by:
    ƭ          -       alternate between these two links:
  +            -         add -> first plus second element of the three-slice
   ⁼           -         equals -> does that result equal the third element?
       Ạ       -       all truthy?
          Ṫ    - tail -> (one of) the longest one(s)
           L   - length
             L - length of A
            ạ  - absolute difference

```
> 2 votes

# Answer
# Burlesque, 51 bytes

```
saJ2.-{jR@f{L[2.>}f{J2CO)++~]j[-[-==}[~L[.-}{0it}IE

```

Try it online!

```
sa     # Non-destructive length
J      # Dup
2.-    # Longer than 2
{
 j     # Reorder stack
 R@    # All subsequences
 f{    # Filter
  L[   # Length
  2.>  # >2
 }
 f{
  J    # Dup
  2CO  # Pairwise 2s
  )++  # Map sum
  ~]   # Drop last
  j    # Reorder stack
  [-[- # Drop first twice
  ==   # Are equal
 }
 [~    # Last
 L[    # Length
 .-    # Difference with original
}
{
 0it   # Return 0
}IE    # If else

```
> 2 votes

# Answer
# 05AB1E, ~~14~~ 13 bytes

```
æʒD¥¦Å?}ζ‚€gÆ

```

-1 byte thanks to *@ovs*

Try it online or verify all test cases.

**Explanation:**

```
æ             # Get the powerset of the (implicit) input-list
 ʒ            # Filter to check if it's Fibonacci-like:
  D           #  Duplicate the current list
   ¥          #  Pop one and get its forward differences
    ¦         #  Remove the first item
     Å?       #  Check if the original list starts with this as sublist
       }ζ     # After the filter: zip/transpose; swapping rows/columns, with " "
              # as implicit default filler for unequal length lists
         ‚    # Pair the (implicit) input-list with this matrix
          €g  # Get the length of both
            Æ # Reduce by subtracting
              # (which is output implicitly as result)

```

Because we only care about the length, the zip/transpose with filler is used to our advantage to get the length of the longest truthy result of the filter (thanks to *@ovs*).
> 2 votes

# Answer
# Stax, 14 bytes

```
ü∞♀ÇjäεîVÖ₧"╥←

```

Run and debug it
> 2 votes

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

```
{(#x)-|/{(#x)**/(-2_x)=2_-':x}'(,()){x,x,'y}/x}

```

Try it online!

Wow this is a long one. I tried to emulate APL's `(⊢,,¨)\` with `(,()){x,x,'y}/`. Actually the whole code is almost a port of ovs's answer into ngn/k.
> 2 votes

# Answer
# Factor \+ `math.combinatorics`, 81 bytes

```
[ dup all-subsets [ dup differences rest head? ] find-last nip [ length ] bi@ - ]

```

Try it online!
> 1 votes

---
Tags: code-golf, fibonacci, subsequence
---


title: Only one from each set

text:
# Question
Title: Only one from each set
Your input is a non-empty set of non-empty sets of positive integers. For example:

```
{{1}, {2, 3}, {2,4}, {1,4}}

```

Your task is to output the maximal number of elements that can be picked from the sets with the following conditions:

* You can only pick at most 1 element from a set
* You can't pick the same element from 2 different sets

In this example you can pick `1` from the first set, `3` from the second set, `2` from the third set and `4` from the last set, for a total of 4 elements.

Io is flexible. You can take a list, instead of sets, etc.

There are no gaps in the numbers (eg. `{{2,3},{3,4}}` is not a valid input). Or in other words, the input flattened must contain all numbers `[1,n]` where n is the largest number in the input.

This is , so shortest code wins.

# Examples

```
{{1}}
-> 1

{{1}, {2, 3}, {2,4}, {1,4}}
-> 4

{{1}, {2}, {1,2,3,4}}
-> 3

{{1}, {2}, {2,3}}
-> 3

{{1, 2, 3}, {2, 4, 5, 6}, {3, 5, 6, 7}, {1, 2}, {2, 3}, {1, 3}}
-> 5

{{1,2,3,4,5}, {1,2}, {2,3}, {1,3}}
-> 4

{{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{5,6,7,8,9,10}}
-> 5

{{1,4}, {2,3}, {1,3}, {1,2,3}}
-> 4

```

# Background

Recently @AnishSharma posted this question on Stack Overflow. This is a slightly modified version of that question

# Answer
> 7 votes
# Python 3, 66 bytes

```
lambda x:max(map(len,map(set,product(*x))))
from itertools import*

```

Try it online!

# Answer
> 6 votes
# Jelly, 6 bytes

```
ŒpQ€ẈṀ

```

Try It Online!

```
ŒpQ€ẈṀ    Main Link
Œp        Cartesian Product; get all possible selections
  Q€      Uniquify each
    Ẉ     Length of each
     Ṁ    Maximum result

```

# Answer
> 5 votes
# Python 3, 63 bytes

```
f=lambda s,*v:s and max(f(s[1:],x,*v)for x in s[0])or len({*v})

```

Try it online!

# Answer
> 3 votes
# Haskell + hgl, 10 bytes

```
xMl<nb<<sQ

```

Works as of commit 4a9f6d27. Older version below.

## Explanation

The functions involved are:

* `sQ` can do many things but on lists it performs the cartesian product.
* `nb` removes all duplicate lements from a list.
* `xMl` gets the length of the longest list in a list of lists

So we get the Cartesian product, nub the results and then get the maximum of their lengths.

# Haskell + hgl, 13 bytes

```
mx<l.^nb.^sQ

```

This no longer works in recent versions of hgl since `(.^)` was renamed to `(<<)`. To test it run:

```
mx<l<<nb<<sQ

```

## Explanation

This works the same as the new implementation above except we have to get all the lengths and then get the maximum separately. The new functions are:

* `l` gets the length of a list
* `mx` gets the maximum of a list.

So we get the Cartesian product, nub the results and then get the maximum of their lengths.

## Reflections

* First things first we don't have a set type. This is unfortunate and needs to be fixed at some point.
* `l<nb` seems like something that would be useful to have a builtin for.
* It would be nice to have some sort fold and sequence or fold and traverse combined function.
* ~~I could have used a "maxmap". If we wanted to get the actual choices we could have done, `xB l<nb.^sQ` to save two bytes. But `xB` returns the original list not the modified version.~~ This has been fixed in newer versions with the function is called `xM`, but `xMl` was also added which saves another byte.

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

Expects an array of arrays.

```
f=([b,...a],s)=>b?Math.max(...b.map(v=>f(a,new Set(s).add(v)))):s.size

```

Try it online!

### Commented

```
f = (              // f is a recursive function taking:
  [b,              //   b[] = next list
      ...a],       //   a[] = all remaining lists
  s                //   s = current set, initially undefined
) =>               //
b ?                // if b[] is defined:
  Math.max(        //   return the maximum of ...
    ...b.map(v =>  //     for each value v in b[]:
      f(           //       do a recursive call:
        a,         //         pass a[]
        new Set(s) //         create a new set from s
                   //         (an empty set if s is undefined)
        .add(v)    //         add v to it
      )            //       end of recursive call
    )              //     end of map()
  )                //   end of Math.max()
:                  // else:
  s.size           //   return the size of s

```

# Answer
> 3 votes
# , ~~55~~ 54 bytes

*Edit: -1 byte thanks to pajonk*

```
function(x)max(lengths(apply(expand.grid(x),1,table)))

```

Try it online!

Test setup stolen from pajonk's R answer.
48 bytes using  ≥ 4.1 by exchanging `function` for `\`.

# Answer
> 2 votes
# Factor, 42 bytes

```
[ [ members ] product-map longest length ]

```

Try it online!

Uniqueify the elements of the product sequence of the input, then find the longest length.

# Answer
> 2 votes
# , 60 bytes

Or **\>=4.1, 53 bytes** by replacing the word `function` with a `\`.

```
function(x)max(sapply(apply(expand.grid(x),1,table),length))

```

Try it online!

---

Solution shorter in \>=4.1:

### , 66 bytes

Or **\>=4.1, 52 bytes** by replacing two `function` occurrences with `\`s.

```
function(x)max(apply(expand.grid(x),1,function(a)sum(table(a)|1)))

```

Try it online!

# Answer
> 2 votes
# Vyxal, 6 bytes

```
Πv‡ULG

```

Try it Online!

```
Π      # Cartesian product - get all possibilties
 v     # Over each...
  ‡--  # Do the next two elements
   U   # Uniquify
    L  # Get length
     G # Maximum

```

# Answer
> 1 votes
# Charcoal, 32 bytes

```
Ｉ⌈ＥＥΠＥθＬιＥθ§λ÷ι∨ΠＥ…θμＬν¹ＬΦι⁼μ⌕ιλ

```

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

```
      θ                             Input array
     Ｅ                              Map over lists
        ι                           Current list
       Ｌ                            Take the length
    Π                               Take the product
   Ｅ                                Map over implicit range
          θ                         Input array
         Ｅ                          Map over lists
            λ                       Current list
           §                        Cyclically indexed by
              ι                     Outer value
             ÷                      Integer divided by
                   θ                Input array
                  …                 Truncated to length
                    μ               Inner index
                 Ｅ                  Map over array
                      ν             Innermost list
                     Ｌ              Take the length
                Π                   Take the product
               ∨                    Logical Or
                       ¹            Literal integer `1`
  Ｅ                                 Map over lists
                          ι         Current list
                         Φ          Filtered where
                            μ       Inner index
                           ⁼        Equal to
                             ⌕      Index of
                               λ    Inner value
                              ι     In current list
                        Ｌ           Take the length
 ⌈                                  Take the maximum
Ｉ                                   Cast to string
                                    Implicitly print

```

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
.»âε¸˜Ùg}à

```

Try it online or verify all test cases.

**Explanation:**

```
.»     # (Left-)reduce the (implicit) input-list by:
  â    #  Cartesian product
ε      # Then map over each inner list:
 ¸     #  Wrap it into a list (workaround for input [[1]])
  ˜    #  Flatten it
   Ù   #  Uniquify it
    g  #  Pop and push the length
}à     # After the map: pop and push the maximum
       # (which is output implicitly as result)

```

# Answer
> 0 votes
# Julia, 55

```
J(l)=maximum(length.(Set.(Iterators.product(l...))[:]))

```

ATO

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


title: Fizzbuzz in any base

text:
# Question
Title: Fizzbuzz in any base
# Challenge

**Input:**

An integer \\$b\\$ between 2 and 62 (inclusive).

**Output:**

Count from \\$1\\$ to the equivalent of \\$5000\_{10}\\$ in base \\$b\\$, using any reasonable representation for the digits.

However:

* If the number is divisible by \\$\lfloor b÷2+1\rfloor\\$ (rounded down, e.g base 7 would be 7/2=3.5, 3.5+1=4.5, rounded to **4**), then output 'Fizz' instead of the number.
* If the number is divisible by \\$\lceil b÷3+3\rceil\\$ (rounded up, e.g 11/3=3.666, 3.666+3=6.666, rounded to **7**), then output 'Buzz'.
* As you can probably guess, if your number is divisible by both, output 'Fizzbuzz'.

# Examples

*Using **\[0-9\]**, **\[A-Z\]** and **\[a-z\]** as the digits*

*(I've only included the first 10 values to keep the examples short - normally there'd by 4990 more items in each sequence)*

**Input:** 10 (so 'Fizz' = 6 and 'Buzz' = 7)

**Output:** 1, 2, 3, 4, 5, Fizz, Buzz, 8, 9, 10

**Input:** 2 (so 'Fizz' = 2 and 'Buzz' = 4)

**Output:** 1, Fizz, 11, Fizzbuzz, 101, Fizz, 111, Fizzbuzz, 1001, Fizz

*(I've included the first 50 values of the following to better show how they work)*

**Input:** 55 (so 'Fizz' = \\$28\_{10}\\$ = \\$s\_{55}\\$ and 'Buzz' = \\$22\_{10}\\$ = \\$m\_{55}\\$)

**Output:** 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, g, h, i, j, k, l, Buzz, n, o, p, q, r, Fizz, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N

# Rules

* Standard loopholes are forbidden
* This is Code Golf, so shortest answer in bytes wins
* Input and output can be through console, or function arguments/returns
* Leading/trailing white space is fine, as are empty lines
* Spaces between 'Fizz' and 'Buzz' are disallowed
* Any capitalization variant of 'Fizz'/'Buzz'/'Fizzbuzz' is fine.
* Outputs should be separated by newlines.
* If you return a array of base 10 'digits' instead of representing them with characters, then they have to be in the correct order!

# Answer
> 3 votes
# Jelly,  ~~42 38 34 33 29~~  32 bytes

+3 to adhere to strict formatting rules

```
5ȷɓ;8Ä:2,3‘ḍȧ"“Ƈ×“=%»ḟ0Fȯb@K¥ð€Y

```

A full program which prints 5000 lines of text, each line containing a series of integers (the digits) or one of `fizz`, `buzz`, or `fizzbuzz` (works fine beyond base 62).

**Try it online!**

### How?

Note that
\\$\lfloor b÷2+1\rfloor\ = \lfloor b÷2\rfloor+1\\$
...and
\\$\lceil b÷3+3\rceil = \lceil b÷3+2\rceil+1 = \lceil (b+6)÷3\rceil+1 = \lfloor (b+8)÷3\rfloor+1\\$

***updating...***

```
5ȷɓ;8Ä:2,3‘ḍȧ"“Ƈ×“=%»ḟ0Fȯb@ð€ - Link: integer, b
5ȷ                            - 5*10³ = 5000
  ɓ                        ð€ - for €ach n in [1,2,...,5000] get this f(b,n):
    8                         -   eight
   ;                          -   concatenate      -> [b,8]
     Ä                        -   cumulative sums  -> [b,b+8]
       2,3                    -   pair literal        [2,3]
      :                       -   integer division -> [b//2, (b+8)//3]
          ‘                   -   increment        -> [b//2+1, (b+8)//3+1]
           ḍ                  -   divides n?       -> [n is fizzy?, n is buzzy?]
              “Ƈ×“=%»         -   list of dictionary strings = ['fizz','buzz']
             "                -   zip with:
            ȧ                 -     logical AND    -> [0,0], ['fizz',0], [0,'buzz'],
                              -                       or ['fizz','buzz']
                      0       -   zero
                     ḟ        -   filter discard   -> [], ['fizz'], ['buzz'],
                              -                       or ['fizz','buzz']
                       F      -   flatten          -> [], ['fizz'], ['buzz'],
                              -                       or ['fizzbuzz']
                          @   -   using swapped arguments:
                         b    -     (n) to a list of digits in base (b)  (say, [nb])
                        ȯ     -   logical OR       -> [nb], ['fizz'], ['buzz'],
                              -                       or ['fizzbuzz']

```

# Answer
> 3 votes
# Charcoal, 40 bytes

```
ＮθＥ…·¹×⁵φ∨⁺⎇﹪ι⊕÷θ²ωFizz⎇﹪ι÷⁺¹¹θ³ωBuzz⍘ιθ

```

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

```
Ｎθ                                      Input `b` into variable `q`
   ¹                                    Literal 1
 …·                                     Inclusive range to
      φ                                 Predefined variable 1000
    ×                                   Multiplied by
     ⁵                                  Literal 5
Ｅ                                       Map to
           ι                            Current value
          ﹪                             Modulo
              θ                         Input value
             ÷                          Floor divide
               ²                        Literal 2
            ⊕                           Incremented
         ⎇                              If nonzero
                ω                       Then predefined empty string
                 Fizz                   Otherwise literal `Fizz`
        ⁺                               Concatenated with
                       ι                Current value
                      ﹪                 Modulo
                            θ           Input value
                         ⁺              Plus
                          ¹¹            Literal 11
                        ÷               Integer divided by
                             ³          Literal 3
                     ⎇                  If nonzero
                              ω         Then predefined empty string
                               Buzz     Otherwise literal `Buzz`
       ∨                                Logical Or
                                    ι   Current value
                                   ⍘    Converted to base
                                     θ  Input value
                                        Implicitly print each result on its own line

```

# Answer
> 3 votes
# , ~~163~~ 131 bytes

```
b=scan();for(d in 1:5e3)cat(list(d%/%b^rev(0:log(d,b))%%b,'fizz','buzz','fizzbuzz')[[1+(!d%%((b+2)%/%2))+2*!d%%((b+11)%/%3)]],'\n')

```

Try it online!

Thanks to @digEmAll for saving 23 bytes. I then further golfed @digEmAll’s efforts to save a further 9.

# Answer
> 2 votes
# JavaScript (ES6),  ~~117~~  116 bytes

Outputs comma-delimited digits, each digit being expressed as a decimal quantity (e.g. \\$19\_{20}\\$ is \\$19\\$ and \\$21\_{20}\\$ is \\$1,1\\$).

```
b=>(g=n=>n>1?g(n-1)+`
`+((s=n%(b+2>>1)?'':'Fizz',n%(b/3+3.9|0)?s:s+'Buzz')||(g=n=>n?[...g(n/b|0),n%b]:s)(n)):1)(5e3)

```

Try it online!

(limited to 100 so that TIO's output does not blow up)

# Answer
> 2 votes
# Python 2, 116 bytes

```
b=input()
i=0
exec"a=i=i+1;d=[]\nwhile a:d=[a%b]+d;a/=b\nprint'Fizz'*(i%(b/2+1)<1)+'Buzz'*(i%(~-b/3+4)<1)or d;"*5000

```

Try it online!

Or with `0-9a-zA-Z` output:

# Python 2, 143 bytes

```
b=input()
i=0
exec"a=i=i+1;d=''\nwhile a:d=chr(a%b+48+(a%b>9)*39-a%b/36*58)+d;a/=b\nprint'Fizz'*(i%(b/2+1)<1)+'Buzz'*(i%(~-b/3+4)<1)or d;"*5000

```

Try it online!

# Answer
> 2 votes
# Julia, 108

```
h(b,N)=join((n->[string(n,base=b),"Buzz","Fizz","FizzBuzz"][1+(1>n%(b÷2+1))*2+(1>n%((b+11)÷3))]).(1:N),"\n")

```

### ATOable

# Answer
> 2 votes
# Vyxal, 26 bytes

```
₁²½ƛ?8"¦23f/›ḊkF½*∑n?τ$∨;⁋

```

Try it Online!

# Answer
> 1 votes
# Perl 6, 91 bytes

```
{$!=0;('Fizz'x++$!%%($_/2+|0+1)~'Buzz'x$!%%(($_+8)/3+|0+1)||[R,] $!.polymod($_ xx*))xx}

```

Try it online!

Anonymous code block that returns a list of either strings of `Fizz/Buzz/FizzBuzz` or a ~~reversed~~ list of integers in the base.

# Answer
> 1 votes
# 05AB1E, ~~39~~ ~~37~~ 36 bytes

```
8+‚U5₄*LεX23S÷>Ö”FizzÒÖ”#×JDõQiyIв]»

```

-2 bytes by creating a port of *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases (but as list-output and with the first 100 instead of 5000).

**Explanation:**

```
8+               # Add 8 to the (implicit) input
  ‚              # Pair it with the (implicit) input
   U             # Pop and store it in variable `X`
5₄*L             # Create a list in the range [1,5000]
    ε            # Map each value `y` to:
     X23S÷       #  Integer-divide the input by 2, and the input+8 by 3
          >      #  Increase both by 1
           Ö     #  Check for both if they divide value `y` evenly (1 if truthy; 0 if falsey)
     ”FizzÒÖ”    #  Push dictionary string "Fizz Buzz"
             #   #  Split on spaces
              ×  #  Repeat the strings the result amount of times (0 or 1)
               J #  Join both strings together to a single string
     DõQi        #  If this string is empty:
         yIв     #   Push value `y` in Base-input (as list) instead
    ]            # Close the if-statement and map
     »           # Join the list by new-lines (and inner lists by spaces implicitly)
                 # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”FizzÒÖ”` is `"Fizz Buzz"`.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), ~~180~~ ~~171~~ 168 bytes

```
n=>{for(int i=1,p;i<5001;){var j=new Stack<int>();for(p=i;p>0;p/=n)j.Push(p%n);var s=i%~(n/2)<1?"Fizz":"";Print(i++%((n+11)/3)<1?s+"Buzz":s==""?string.Join("-",j):s);}}

```

Outputs like Arnauld's answer. Thanks to digEmAll for the idea of using a stack to reverse the output.

Saved 3 bytes thanks to ceilingcat

Try it online!

# Answer
> 0 votes
# , 138 bytes

```
function(b,`*`=rep)Map(function(i)"if"((s=paste0("","Fizz"*!i%%(b%/%2+1),"Buzz"*!i%%((b+11)%/%3)))>0,s,i%/%b^((log(i,b)%/%1):0)%%b),1:5e3)

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 34 bytes

Uses Jonathan's mathematical insight that `ceil(n/3+3)` = `floor((n+8)//3)+1`

```
ŽJćG8+‚2L>÷>NsÖ…™Ázz'ÒÖ‚×JNIв‚õKн,

```

Try it online!

**Explanation**

```
ŽJćG                                # for N in [1 ...5001)
    8+‚2L>÷>                        # push [input//2+1, (input+8)//3+1]
            NsÖ                     # check each if N is divisible by it
               …™Ázz                # push "fizz"
                    'ÒÖ             # push "buzz"
                       ‚            # pair
                        ×           # repeat a number of times corresponding to the result of the
                                    # divisibility test
                         J          # join to string
                          NIв‚      # pair with N converted to base <input>
                              õK    # remove empty string
                                н,  # print head of the remaining list

```

---
Tags: code-golf, math, binary, fizzbuzz
---


title: Solve an Inglenook Sidings Puzzle

text:
# Question
Title: Solve an Inglenook Sidings Puzzle
# Solve an Inglenook Sidings Puzzle

## Background

The Inglenook Sidings Puzzle is a shunting/switching yard puzzle by Alan Wright for model railroading. The rules for the puzzle are as follows: (Source)

* Form a departing train consisting of 5 out of the 8 wagons sitting in the sidings.
* The 5 wagons are selected at random.
* The train must be made up of the 5 wagons in the order in which they are selected.

You have 4 sidings:

* The "main line", which is 5 cars long (labeled `B`)
* Two spurs coming off the main line, each of which is 3 cars long (`C` and `D`)
* A yard lead, which is 3 cars long. (`A`)

<sup>(Source: http://www.wymann.info/ShuntingPuzzles/Inglenook/inglenook-trackplan.html)</sup>

## The Challenge

Given the ordered list of cars in the train, generate the movements of the cars needed to form the train. *These moves need not be the shortest solution.*

### The sidings

* Each siding can be considered to be an ordered list of cars.
* Each car can be represented by one of eight unique symbols, with an additional symbol the engine.
* Cars can only be pulled and pushed as if it were coupled to an engine on the `A`-direction (i.e. you cannot access a car from the middle of a siding without needing to remove the head/tail ends first.)
* For this challenge, the starting state will be the same for all cases (where `E` is the engine, and digits are the 8 cars):

```
A E[ ] -- 12345 B
        \-- 678 C
         \- [ ] D

```
* **The puzzle is considered solved if all five cars in the `B`-siding are in the same order as the input car list.**

### Input

Input is an ordered list of five car tags representing the requested train. The car tags should be a subset of any 8 unique elements, e.g. `{a b c d e f g h}` and `{1 two 3 4 five six 7 eight}` are allowed sets of car tags, but `{a b 3 3 e f g h}` is not allowed because not all elements are unique.

### Output

Output is a list of moves for the cars. Examples of a single move can be:

```
B123A // source cars destination
BA123 // source destination cars
"Move from siding B cars 123 to siding A."

```

Among other formats. **The source, destination, and cars moved should be explicit, and explained in whatever move format you choose.**

If it is unambiguous that a cut of cars (a set of cars grouped together) moves unchanged from one siding to another, you can omit a step to the intermediate track, e.g. `1ba 1ad 2ba 2ad => 1bd 2bd`, e.g. `123ba 123ad 67ca 67ab 8ca 8ab => 123bd 67cb 8cb`, e.g. `5db 5ba => 5da`. All of these cases can be compacted due to a matching source-destination track, and the cut of cars moved doesn't change order. The test cases will use this compacted notation.

### Movement Rules

The cars move similarly to real-life railroad cars: you usually can only access one end of the cut at a time. So, the following moves are **illegal** (assuming a starting state similar to the one described above):

```
1ba 2ba 1ad     // trying to access car 1 but car 2 is blocking access, since the last car on the cut is now 2: E12
12ba 21ad       // swapping the order of cars without any intermediate steps to swap them
12345ba 12345ad // trying to fit too many cars into a siding (5 > 3 for sidings A and D)

```

### Additional Rules

### Test Cases

The moves in these testcases will be in the form `cars source destination`, separated by spaces. These are some possible solutions, and *not necessarily the shortest.*

```
Train -> Moves // comment
--------------
12345 ->  // empty string, no moves needed
21345 -> 1bd 2bd 21db
14385 -> 123bd 67cb 8cb 867ba 67ac 4bc 8ab 123da 3ab 2ad 4ca 14ab
43521 -> 123ba 3ad 4ba 24ad 1ab 2db 215ba 5ad 21ab 5db 43db
86317 -> 67ca 7ad 8cd 6ac 8dc 1bd 23ba 3ad 45ba 5ac 3db 5cb 1db 4ac 7da 1bd 5bd 3bd 7ab 35db 1da 3bd 5bd 1ab 53da 3ab 25ad 4cd 86cb

```

### Tips

* All Inglenook Sidings Puzzles are solvable if and only if the inequality \\$(h-1)+m\_1+m\_2+m\_3\ge w+M\\$ is true, where \\$h\\$ is the capacity of the yard lead, \\$m\_1, m\_2, m\_3\\$ are the capacities of the sidings, \\$w\\$ is the number of wagons, and \\$M = \max(h-1, m\_1, m\_2, m\_3)\\$. For the initial state for the challenge, this is \\$w = 8, h=m\_1=m\_2=3, m\_3=5\\$. (https://arxiv.org/abs/1810.07970)
* You can only take and give cars from the end of the cut facing the switches, similarly to a stack.
* A program to test your program output, input format is `final_state -> [cars_moved][source][destination]`.

# Answer
# Charcoal, 120 bytes

```
⊞υ⪪”←‴⧴ν↘pＧ8¡¶”¶Ｗ¬⊙υ№κθ«≔υη≔⟦⟧υＦηＦ⁴Ｆ…·¹Ｌ⁻§κλ Ｆ⎇λ¹…¹¦⁴¿¬‹№§κν μ⊞υ⊞ＯＥκ⎇⁼πλ◨✂ξμχ¹Ｌξ⎇⁼πν⁺⮌…§κλμ✂ξ⁰±μ¹ξ⁺⁺…§κλμ§βλ§βν»✂⊟Φυ№ιθ⁴

```

Try it online! Link is to verbose version of code. Very brute force (spends most of its time shuffling the first wagon between sidings `a` and `b`) so can only solve simple cases on TIO. All moves are always between siding `a` and another siding. Moves list the wagons in the order that they enter the other siding, which for wagons leaving siding `a` is the reverse of what you might expect. Explanation:

```
⊞υ⪪”←‴⧴ν↘pＧ8¡¶”¶

```

Start with the initial position.

```
Ｗ¬⊙υ№κθ«

```

Repeat until a sequence of moves resulting in the desired position is found. (The code actually checks all sidings but only siding `b` can actually have that position of course.)

```
≔υη

```

Save the previously found positions.

```
≔⟦⟧υ

```

Start a new list of found positions.

```
Ｆη

```

Loop over the previously found positions.

```
Ｆ⁴

```

Consider each possible source siding.

```
Ｆ…·¹Ｌ⁻§κλ

```

Consider all of the wagons in that siding.

```
Ｆ⎇λ¹…¹¦⁴

```

For siding `a`, consider the other three sidings as a possible destination, otherwise consider siding `a` as a possible destination.

```
¿¬‹№§κν μ

```

Check whether the destination has enough room for the number of wagons being moved.

```
⊞υ⊞ＯＥκ⎇⁼πλ◨✂ξμχ¹Ｌξ⎇⁼πν⁺⮌…§κλμ✂ξ⁰±μ¹ξ⁺⁺…§κλμ§βλ§βν

```

Create an updated position with the wagons moved to the other siding, plus append the current move, and save that to the list of positions.

```
»✂⊟Φυ№ιθ⁴

```

Output the moves required to reach the desired position.

I've written a version which is somewhat faster but still only manages to solve `43521` because it cheats and ignores siding `c` if the input contains no digit above `5`. (The above version is so slow that even this optimisation doesn't help it.)

```
⊞υ⪪”←‴Fa×ι|”¶≔⮌υηＷ¬⊙η№κθ«≔ηζ≔⟦⟧ηＦζＦ⁴¿∧λ∨⁻λ²›⌈θ5«≔⁺§κ⁰§κλεＦ…·⌈⟦⁰⁻Ｌε⎇⊖λ³¦⁵⟧⌊⟦³Ｌε⟧«≔⊞ＯＥκ⎇⁼ξλ✂εμχ¹⎇ξν✂ε⁰μ¹⁺μ§βλδ¿¬№υ…δ⁴«⊞υ…δ⁴⊞ηδ»»»»✂⊟Φη№ιθ⁴

```

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

The output of this version is not currently in a standard format, so I'll explain it here. Each line consists of a digit and a letter. The letter represents the other siding from or to which wagons are shunted to or from siding `a`. The digit represents the number of wagons that end up in siding `a`. Example:

```
    /12345/678/ Initial position
3b: 123/45/678/ Fill a with 3 wagons from b
0d: /45/678/123 Move all wagons from a to d
2b: 45//678/123 Fill a with 2 wagons from b
3d: 451//678/23 Fill a with 1 wagon from d
2b: 45/1/678/23 Move 1 wagon from a to b
3d: 452/1/678/3 Fill a with 1 wagon from d
1b: 4/521/678/3 Move 2 wagons from a to b
2d: 43/521/678/ Fill a with 1 wagon from d
0b: /43521/678/ Move 2 wagons from a to b

```
> 4 votes

# Answer
# Python3, 1447 bytes:

```
R=range
E=enumerate
F=lambda s,e,m:s+''.join(map(str,m))+e
U=lambda x:eval(str(x))
def C(w,m,o,c,e):
 if[]==c:yield w,m;return
 for x in o:
  for i,y in E(c):
   if len(w[x][1])<w[x][0]:W=U(w);M=U(m);W[x][1]=([y if x!=1 else(y,)]+W[x][1]if x else W[x][1]+[y]);M+=[F(W[e][2],W[x][2],[y])];yield from C(W,M,o,c[:i]+c[i+1:],e)
def V(w,m,t,c):
 if w[1][1][:len(j:=[i for i in w[1][1]if type(i)==tuple])]==j:
  B=0
  for W,M in C(w,m,{0,2,3}-{c},[i for[i]in j],1):
   B=1
   W,M=U(W),U(M);W[1][1]=W[1][1][len(j):];W[c][1]=(W[c][1][1:]if c else W[c][1][:-1]);M+=[F(W[c][2],'B',[t])];W[1][1]=[t]+W[1][1];yield W,M,1
  if not B:
   w[c][1].remove(t)
   for W,M in C(w,m,{0,2,3}-{c},[t],c):yield W,M,0
def f(t):
 w,m=[{0:3,1:[],2:'A'},{0:5,1:[*R(1,6)],2:'B'},{0:3,1:[6,7,8],2:'C'},{0:3,1:[],2:'D'}],[]
 if w[1][1]==t:return m
 T=t[:(r:=max(e)+1 if(e:=[i for i in R(5)if t[i]!=w[1][1][i]])else 5)]or t;W=w[1][1][:r]
 w[1][1]=w[1][1][r:]
 if(M:=W[:3][::-1]):w[3][1]+=M;m+=[F('B','D',M[::-1])]
 if(M:=W[3:]):w[0][1]+=M;m+=[F('B','A',M[::-1])]
 q=[(U(w),U(m),T)]
 while q:
  W,M,T=q.pop(0)
  if[]==T:return M
  if(O:=[i for i in[0,2,3]if W[i][1]and W[i][1][(0 if i else -1)]==T[-1]]):
   for W,M,I in V(W,M,T[-1],O[0]):q+=[(W,M,T[:-1]if I else T)]
  else:
   if(O:=[i for i in [0,2,3]if T[-1]in W[i][1]]):
    [c]=O;S=(W[c][1][:1]if c else W[c][1][-1:]);W[c][1]=(W[c][1][1:]if c else W[c][1][:-1])
    for W,M in C(W,M,{0,1,2,3}-{c},S,c):q+=[(W,M,T)]
 return m

```

Not the shortest solution, and can be golfed further, but produces output moves for all the test cases in 0.2 seconds. For input, it takes a list of the desired car order, and the output is a list with all the moves.

Move notation:

```
<source siding>[cars moved]<destination siding>

```

For example, `'B123D'` means "move cars 1, 2, and 3 from siding B to siding D.

Try it online!
> 2 votes

---
Tags: code-golf, game, puzzle-solver
---


title: Landau logarithm

text:
# Question
Title: Landau logarithm
Related: Landau's function (OEIS A000793)

## Background

Landau's function \\$g(n)\\$ is defined as the largest order of permutation of \\$n\\$ elements, which is equal to \\$\max(\operatorname{lcm}(a\_1,a\_2,\cdots,a\_i))\\$ where \\$a\_1,a\_2,\cdots,a\_i\\$ is an integer partition of \\$n\\$.

We can extend this to define "iterations" of Landau's function: let's define \\$g\_0(n) = 1\\$, and \\$g\_{k+1}(n) = \max(\operatorname{lcm}(g\_{k}(n), a\_1,a\_2,\cdots,a\_i))\\$ for \\$k \ge 0\\$. This eventually converges to \\$\operatorname{lcm}(1,2,\cdots,n)\\$, so we can define "Landau logarithm" to be the smallest value of \\$k\\$ such that \\$g\_k(n)=\operatorname{lcm}(1,2,\cdots,n)\\$, or equivalently \\$g\_k(n)=g\_{k+1}(n)\\$.

The resulting sequence is OEIS A225633.

## Illustration

### n = 5

To make it clear, let's list up all the integer partitions of 5, which are:

```
(5)
(4, 1)
(3, 2)
(3, 1, 1)
(2, 2, 1)
(2, 1, 1, 1)
(1, 1, 1, 1, 1)

```

By definition, \\$g\_0(5) = 1\\$. \\$g\_1(5)\\$ is defined by whatever partition gives the largest LCM, which is \\$\operatorname{lcm}(2,3) = 6\\$ (which is the same as the plain Landau function). \\$g\_2(5)\\$ is the largest LCM of any partition *when combined with 6*. We need to find the partition which can give the largest additional factor. Such partition is plain 5, so \\$g\_2(5) = \operatorname{lcm}(6,5) = 30\\$. In the next step, the only partition that boosts the LCM further is (4,1), giving \\$g\_3(5) = \operatorname{lcm}(30, 4, 1) = 60\\$, which is the same as \\$\operatorname{lcm}(1, 2, 3, 4, 5)\\$. Therefore, the Landau logarithm of 5 is 3.

### n = 10

* \\$g\_0(10) = 1\\$
* \\$g\_1(10) = \operatorname{lcm}(2,3,5) = 30\\$
* \\$g\_2(10) = \operatorname{lcm}(30,7,3) = 210\\$
* \\$g\_3(10) = \operatorname{lcm}(210,8,2) = 840\\$
* \\$g\_4(10) = \operatorname{lcm}(840,9,1) = 2520 = \operatorname{lcm}(1,2,\cdots,10)\\$

Therefore the Landau logarithm of 10 is 4.

## Challenge

Given a positive integer \\$n\\$, compute its Landau logarithm.

The shortest code in bytes wins.

## Test cases

The first 20 terms (starting at `n=1`, up to `n=20` inclusive) are:

```
0, 1, 2, 2, 3, 3, 3, 3, 4, 4,
5, 5, 6, 5, 5, 5, 6, 6, 7, 6

```

# Answer
# Jelly, ~~15~~ ~~14~~ 13 bytes

```
:ælƒ€@Ṁ¥ƬŒṗL’

```

Try it online!

## Explanation (older version)

```
:;Ɱæl/€ṀɗƬŒṗL’   Main monadic link
:                Divide the input by itself to get 1
         Ƭ       Repeat until reaching fixed point, collecting intermediate results
        ɗ        (
 ;Ɱ       Œṗ       Prepend to each integer partition of the input
      €            For each
     /             fold over
   æl              the lowest common multiple
       Ṁ           Maximum
        ɗ        )
            L    Length
             ’   Decrement

```
> 7 votes

# Answer
# Haskell, 72 bytes

```
(1%)
k%n|k?n==k=0|1>0=1+k?n%n
k?0=k
k?n=maximum[lcm x$k?(n-x)|x<-[1..n]]

```

Try it online!

The helper function `k?n` compute a the Landau function `g(n)` except `k` is also in the list of numbers. Then, `k%n` counts how many iterations of replacing `x` with `x?n` starting with `k` we need to reach a fixed point.
> 7 votes

# Answer
# Haskell, 69 bytes

A small improvement to xnor's answer.

```
(1%)
k%n|k?n==k=0|1>0=1+k?n%n
k?n=maximum$k:[lcm x$k?(n-x)|x<-[1..n]]

```

Try it online!

Compared to the original solution I have simplified the definition of `k?n`, which calculates one iteration of the Landau function.
For \\$n=0\\$ the function returns \\$k\\$ and for positive \\$n\\$ it always returns the \\$\mathop{lcm}\\$ of \\$k\\$ and some positive integers, which is greater than or equal to \\$k\\$.
Since `[1..n]` is empty for \\$n=0\\$, we can get rid of an explicit base case by prepending \\$k\\$ to the list of possible results.
> 7 votes

# Answer
# 05AB1E, ~~27~~ ~~21~~ 15 bytes

```
1.ΓIÅœsδª€.¿à}g

```

-6 bytes by porting *@xigoi*'s Jelly answer, so make sure to upvote him!

Try it online or verify all test cases.

**Original ~~27~~ 21 bytes approach:**

```
1[DIL.¿QD–#IÅœsδª€.¿à

```

-6 bytes thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
1             # Push 1
 .Γ           # Loop until it no longer changes, collecting intermediate results:
   I          #  Push the input-integer
    Åœ        #  Pop and push all lists of positive integers that sum to this input
       δ      #  Map over each of these lists:
      s ª     #   And add the current value as trailing item to each
         €    #  Then map over each of these lists again:
          .¿  #   And calculate its least common multiple
            à #  Pop this list of lcm's, and only leave the maximum
 }g           # After the loop: pop and push its length
              # (after which it is output implicitly as result)

1             # Push 1
 [            # Start an infinite loop:
  D           #  Duplicate the current value on the stack
   IL         #  Push a list in the range [1,input]
     .¿       #  Pop and get the least common multiple of this list
   Q          #  If this is equal to the current value we've duplicated:
     –        #   Print the (0-based) loop-index
    D #       #   And stop the infinite loop/program
   IÅœsδª€.¿à #  Same as above

```
> 6 votes

# Answer
# JavaScript (ES6),  ~~145~~  116 bytes

```
n=>~(G=(a,b)=>b?G(b,a%b):a,P=(p,n,i=1)=>m=n?i>n||Math.max(P(p*i/G(p,i),n-i,i),P(p,n,i+1)):p,h=p=>P(p,n)-p&&h(m)-1)``

```

Try it online!

### Commented

The helper function \\$G\\$ computes \\$\gcd(a,b)\\$.

```
G = (a, b) => b ? G(b, a % b) : a

```

The helper function \\$P(p,n)\\$ recursively computes all integer partitions of \\$n\\$ while keeping track of the maximum \\$\operatorname{lcm}\\$ of the union of the partition and \\$p\\$. This maximum is eventually saved in \\$m\\$ and returned.

```
P = (                               // P is a recursive function taking:
  p,                                //   p = previous maximum
  n,                                //   n = input of the main function
  i = 1                             //   i = counter for the current partition
) =>                                //
m =                                 // save the final result in m
  n ?                               // if n is not equal to 0:
    i > n ||                        //   return 1 if i is greater than n
    Math.max(                       //   otherwise return the maximum of:
      P(p * i / G(p, i), n - i, i), //     a recursive call with p = lcm(p, i)
                                    //     and n = n - i
      P(p, n, i + 1)                //     a recursive call with i + 1
    )                               //   end of Math.max()
  :                                 // else:
    p                               //   stop the recursion and return p

```

The helper function \\$h\\$ updates the maximum \\$m\\$ until a fixed point is reached and keeps track of the total number of iterations (as a negative value).

```
h = p => P(p, n) - p && h(m) - 1

```

The main wrapper function just processes the initial call to \\$h\\$ with \\$p\\$ zero'ish and bitwise-inverts the result.

```
n => ~h``

```
> 4 votes

# Answer
# Haskell (Lambdabot), 127 bytes

```
l=foldl1 lcm
p 0=[[]]
p n=[1..n]>>= \x->(x:)<$>p(n-x)
n#v=maximum$fmap(l.(v:))$p n
s n=fromJust$elemIndex(l[1..n])$iterate(n#)1

```

`s` is the "main" function. Requires `Data.List` and `Data.Maybe` from lambdabot to run.

Ungolfed:

```
-- LCM of a list; it saves a few bytes to define a shortcut to it.
l = foldl1 lcm

-- Given an integer n, this function gives us all partitions of n.
-- The list monad is excellent for "enumeration" sorts of problems
-- like this.
p 0 = [[]]
p n = [1..n] >>= \x -> (x: ) <$> p (n - x)

-- Given an integer n and a previous Landau value v, this function
-- (whose name is the infix operator (#)) produces the "next" Landau
-- iteration value.
n # v = maximum $ fmap (l . (v :)) $ p n

-- Given an integer n, we iterate the (#) function until we find the
-- number `l [1..n]' (the lcm of 1 up to n) and then we return the index
-- of that number. Unfortunately, elemIndex returns `Maybe Int' so we need
-- the rather lengthy fromJust to get rid of that.
s n = fromJust $ elemIndex (l [1..n]) $ iterate (n #) 1

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
((i=1)//.n_:>Max[i--;n~LCM~##&@@@IntegerPartitions@#];-i)&

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~68~~ 67 bytes

```
k%n=sum[1+k?n%n|k?n>k]
k?n=maximum$k:[lcm x$k?(n-x)|x<-[1..n]]

```

```
(1%)

```

Try it online!

Golfs 2 bytes off of ovs' answer which itself golfed 3 bytes off xnor's answer.
> 3 votes

# Answer
# K (ngn/k), ~~84~~ 78 bytes

-4 thanks to @Bubbler

```
{#1_(|/(x/'{$[x;,/i,''(x-i)o'y&i:1+!x&y;,!0]}/2#y)x')\1}{_x*y%*|(*:)(|!\)/x,y}

```

Try it online!

```
/ungolfed
p:{$[x;,/i,''(x-i)o'y&i:1+!x&y;,!0]} /partitions
g:*|(*:)(|!\)/                       /gcd
l:{_x*y%g x,y}                       /lcm
f:{#1_(|/(l/'p/2#x)l')\1}            /landau log

```
> 2 votes

# Answer
# Charcoal, 100 bytes

```
≔⟦⟦Ｎ¹⟧⟧θＦθ«≔⊟ιη≔⌊ιζ≔⊟ιε¿εＦ…·¹ζ⊞θ⁺ι⟦κ⁻εκ÷×ηκ⌈Φ⊕κ∧λ¬∨﹪κλ﹪ηλ⟧⊞υη»≔⟦¹⟧θＷ⁻Ｅυ÷×⌈θκ⌈Φ⊕κ∧μ¬∨﹪κμ﹪⌈θμθ⊞θ⌈ιＩ⊖Ｌθ

```

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

```
≔⟦⟦Ｎ¹⟧⟧θＦθ«

```

Start a breadth-first search for integer partitions of \\$ n \\$. Each partition is represented by a list of terms \\$ a\_1, a\_2, ..., a\_i, r, l \\$ where the residue \\$ r = n - \sum a\_k \\$ and the LCM \\$ l = \operatorname{lcm}(a\_1, a\_2, ..., a\_i) \\$ , so as the initial partition has no terms yet, the residue is just \\$ n \\$ and the lcm is \\$ 1 \\$.

```
≔⊟ιη≔⌊ιζ≔⊟ιε

```

Extract \\$ l, r, \\$ and \\$ \operatorname{min}(a\_1, a\_2, ..., a\_i, r) \\$ (which is the maximum possible next term of the partition).

```
¿εＦ…·¹ζ

```

If \\$ r \\$ is non-zero, then looping over each valid next term...

```
⊞θ⁺ι⟦κ⁻εκ÷×ηκ⌈Φ⊕κ∧λ¬∨﹪κλ﹪ηλ⟧

```

... concatenate the previous terms with the current term, the new residue, and the new LCM (calculated manually by dividing the product by the maximum of all common factors).

```
⊞υη

```

Otherwise this is a complete partition so save the LCM to the predefined empty list.

```
»≔⟦¹⟧θ

```

Now start building up the terms of \\$ g \\$ starting with \\$ g\_0(n) = 1 \\$.

```
Ｗ⁻Ｅυ÷×⌈θκ⌈Φ⊕κ∧μ¬∨﹪κμ﹪⌈θμθ

```

Take the LCM of each of the partition LCMs with the maximum \\$ g \\$ value (i.e. the latest \\$ g\_i \\$), but remove those whose LCM was still that value. Repeat while LCMs still remain.

```
⊞θ⌈ι

```

Add the highest LCM to the \\$ g \\$ list.

```
Ｉ⊖Ｌθ

```

Print the index of the last term.
> 2 votes

# Answer
# Scala, ~~226~~ 185 bytes

```
n=>Stream.iterate(1){z=>1.to(n).toSet.subsets.filter(_.sum<=n).map(?(_,z)).max}indexWhere?(1.to(n).toSet,1).==
val? =(_:Set[Int])./:(_:Int)((a,b)=>Stream.from(a).find(x=>x%a+x%b<1).get)

```

Try it online!

This is embarrassingly long and inefficient. Instead of finding integer partitions of n, this finds all subsets of the range \[1..n\] where the sum does not exceed n.

`?` is a helper function that finds the lcm of its second argument (a number) and all the elements in its first argument (a list). It does this by folding over the first argument with the second as the initial accumulator.

```
n =>
Stream.iterate(1){z=>  //Make infinite list by repeatedly apply this function to 1
  1.to(n).toSet.subsets //All subsets of range 1..n
    .filter(_.sum <= n) //Keep the ones whose sum is not greater than n
    .map(?(_,z))        //lcm of each (including g_{k-1}(n))
    .max                //Max
} indexWhere            //Find the index k where
  ?(1.to(n).toSet,1)    //The lcm of 1..n
    .==                 //equals g_k(n)

```
> 1 votes

# Answer
# Python 3, 266 bytes

```
from math import*
p=lambda n:{(n,)}|{tuple(sorted((i,)+m))for i in range(1,n)for m in p(n-i)}
c=lambda l,r=1:l and c(l,r*l[-1]//gcd(r,l.pop()))or r
g=lambda i,n:i and max(c([g(i-1,n)]+[*e])for e in p(n))or 1
l=lambda n,p=0,i=0:p-g(i,n)and l(n,g(i,n),i+1) or i and~-i

```

Try it online!

*Quite* verbose! With main function \\$l\\$ and its helper functions \\$g\\$ (which is the same \\$g\\$ as in the OP), \\$c\\$ (aka \\$lcm\\$), and \\$p\\$ (which returns the partitions of \\$n\\$).
> 1 votes

# Answer
# Python 3, ~~128~~ 123 bytes

Apparently this uses a very similar approach as xnor's Haskell answer.

```
from math import*
f=lambda n,d=1:d-g(n,d)and-~f(n,g(n,d))
g=lambda n,d:max([g(n-k,k*d//gcd(k,d))for k in range(1,n+1)]+[d])

```

Try it online!
> 1 votes

# Answer
# Stax, 24 bytes

```
╘J∙╢☼♥DÉ♀→⌂NP¶▐↓╚∞J¼╣øCû

```

Run and debug it

Algorithm borrowed from Kevin Cruijssen's answer, can probably be optimized further.
> 0 votes

---
Tags: code-golf, math, number-theory, integer-partitions
---


title: Parenthetical Names

text:
# Question
Title: Parenthetical Names
# Parenthetical names

Your challenge is to build a program that puts parentheses around the 'title' part of names. For example, `Sonic the Hedgehog` is converted to `Sonic (the Hedgehog)`.

### Rules:

* **Around every `the` that passes the following rules, an opening parentheses will be added *before* the `the` and a corresponding closing parentheses will be added at the end of the string.**
* Inputs will only contain words (uppercase/lowercase letters and spaces).
* Trailing `the`s are ignored.
* With more than one `the`s in a row, every other `the` is parenthesized. (So `pig the the the hog hog hog` turns into `pig (the the (the hog hog hog))`.)
* Remaining `the`s are skipped unless surrounded by spaces. For example, the `the` in `their` would not be parenthesized.

#### I know this may seem lacking in detail. However, it's hard to get one set of really specific guidelines working- just follow the above rules and you're good.

Inspired by this xkcd comic: https://xkcd.com/2252/

This is `code-golf`, so least number of bytes wins.

# Answer
> 4 votes
# QuadR, 27 bytes

```
\b(the )+
 (the .*)
&
 (\1)

```

Try it online!

`\b(the )+` replace multiple `the`s with:
`&` themselves

`(the .*)` replace a space followed by `the` and everything until the end with:
`(\1)` a space followed by the parenthesised text

# Answer
> 3 votes
# Retina 0.8.2, 27 bytes

```
+`(?<!\bthe) (the .+)
 ($1)

```

Try it online! Link includes test cases. Explanation: Parenthesises from all  `the` s to the end of the line, unless the  `the`  follows a previous `the`.

# Answer
> 2 votes
# Charcoal, 40 bytes

```
≔⪪Ｓ θ≔⌕Ａθtheη≔⁻η⁺⊕η⟦⁰⊖Ｌθ⟧η⪫Ｅθ⁺×№ηκ(ι ⭆η)

```

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

```
≔⪪Ｓ θ

```

Split the input on spaces.

```
≔⌕Ａθtheη

```

Find all the indices of `the`.

```
≔⁻η⁺⊕η⟦⁰⊖Ｌθ⟧η

```

Remove any index that's `1` more than another index, and `0` and the last index (because those `the`s weren't surrounded by spaces).

```
⪫Ｅθ⁺×№ηκ(ι

```

Prefix `(` to the remaining indices and join with spaces.

```
⭆η)

```

Output the matching `)`s at the end.

A port of @Steffan's Python answer is also 40 bytes:

```
⪫⪪⪫⪪Ｓ the ¦ (the ¦the (the¦the the×)№ＫＡ(

```

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

```
⪫⪪⪫⪪Ｓ the ¦ (the ¦the (the¦the the

```

Substitute  `the`  with  `(the`  and `the (the` with `the the`.

```
×)№ＫＡ(

```

Output enough `)`s to match the number of `(`s.

# Answer
> 1 votes
# Python, 93 bytes

```
lambda s,t='the',r=' (',w=' ':(p:=s.replace(w+t+w,r+t+w).replace(t+r+t,t+w+t))+p.count(r)*')'
```

Attempt This Online!

# Vyxal, 31 bytes

```
⌈D‛λλÞIf$L‹o:›Fꜝλ\(p;VṄ:\(O\)*J

```

Try it Online!

Port of Charcoal answer.

# Answer
> 1 votes
# 05AB1E, 31 bytes

```
„ €€ÀDć'(©«ì:…€€ (8∍D®K:D®¢')×«

```

Port of *@Steffan*'s Python answer.

Try it online or verify all test cases.

**Explanation:**

```
            :  # Replace all
„ €€À          # " the ":
„ €€           #  Push dictionary string "  the"
    À          #  Rotate it once towards the right: " the "
     Dć'(©«ì  '# with " (the ":
     D         #  Duplicate the " the "
      ć        #  Extract the head
       '(     '#  Push "("
         ©     #  Store it in variable `®` (without popping)
          «    #  Append it to the extracted space
           ì   #  Merge it in front of the remaining string: " (the "

          :    # Then replace all
…€€ (8∍        # "the (the":
…€€ (          #  Push dictionary string "the ("
     8∍        #  Extend it to size 8: "the (the"
       D®K     # with "the the":
       D       #  Duplicate the "the (the"
        ®K     #  Remove the `®` ("("): "the the"

D              # Duplicate the resulting string
 ®¢            # Pop the copy, and count the amount of `®` ("(") in it
   ')×        '# Pop and push a string with that many ")"
      «        # Append it at the end of the string
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„ €€` is `" the"` and `…€€ (` is `"the ("`.

# Answer
> 0 votes
# Python3, 116 bytes:

```
import re
f=lambda x,c=0:re.sub(f'(?<{"!="[c]}e) the {["","[^t]"][c]}[\w\W]+',lambda x:f' ({f(x.group()[1:],1)})',x)

```

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


title: Straighten my corners... diagonally

text:
# Question
Title: Straighten my corners... diagonally
We can arrange the positive integers like this:

```
1_| 2 | 5 | 10
4___3_| 6 | 11
9___8___7_| 12
16  15  14  13

```

That is, in L-shaped brackets expanding down and right infinitely.

Then, we can read it off with the antidiagonals:

```
1 2 5  10
 / /  /
4 3  6  11
 /  /  /
9  8  7  12
  /  /  /
16 15 14  13

```

For the above, we read `1`, then `2, 4`, then `5, 3, 9`, then `10, 6, 8, 16`, and so on.

Your challenge is to output this sequence. Standard rules apply. This is A060736.

This is , shortest wins!

# Answer
> 10 votes
# x86-64 machine code, ~~25~~ 23 bytes

```
31 C0 48 01 C1 7F FB 29 C8 29 C1 7F 03 01 C8 48 01 C1 F7 E8 01 C8 C3

```

Try it online!

Following the `fastcall` calling convention, this takes a number *n* in ECX and returns the 1-indexed *n*th entry in EAX.

This works by first determining x and y coordinates in the grid. Then, letting m = min(x,y), the result is m2+m+1+y-x.

```
 │ 0 1 2
─┼─┴─┴─┴x
0┤ 1 2 5
1┤ 4 3 6
2┤ 9 8 7
 y

```

In assembly:

```
f:  xor eax, eax    # Set EAX to 0.
r:  dec eax         # Subtract 1 from EAX.
                    # This will be the negative length of the current diagonal.
    add ecx, eax    # Add EAX to ECX.
    jg r            # Jump back if the result is positive --
                    #   if the index given has not been reached.
                    # When the loop ends, ECX will hold the negative 0-indexed reverse
                    #   position of the given index within its diagonal, equal to -x.
                    # EAX will hold the negative length of the diagonal, -x-y-1.
    sub eax, ecx    # Subtract ECX from EAX; EAX now holds -y-1.
    sub ecx, eax    # Subtract EAX from ECX, making ECX y-x+1.
    jg s            # Jump if that's positive.
    add eax, ecx    # (Otherwise: y<x) Add ECX to EAX, making EAX -x.
    dec eax         # Subtract 1 from EAX, making -x-1.
                    # Either way, EAX ends up as -m-1.
s:  add ecx, eax    # Add EAX to ECX, making ECX y-x-m.
    imul eax        # Multiply EAX by itself, making (-m-1)² = m²+2m+1.
    add eax, ecx    # Add ECX to EAX, making m²+m+1+y-x.
    ret             # Return.

```

# Answer
> 7 votes
# JavaScript (ES7), 49 bytes

Returns the \\$n\\$-th term, 1-indexed.

```
n=>(t=(2*n)**.5+.5|0,t-=n-=t*~-t/2)<n?n*n-t:t*t+n

```

Try it online!

### How?

This is a revamped version of the 2nd formula given on OEIS.

We define the 1-based index \\$t\\$ of the diagonal to which the \\$n\\$-th entry belongs (this is A002024):

$$t=\left\lfloor\sqrt{2n}+\frac{1}{2}\right\rfloor$$

We define the 1-based index \\$N\\$ representing the position of the entry in the diagonal (from top-right to bottom-left):

$$N=n-\frac{t(t-1)}{2}$$

We turn it into an index \\$T\\$ going from \\$t-1\\$ to \\$0\\$:

$$T=t-N$$

The figures below represent \\$n\\$, \\$t\\$, \\$N\\$ and \\$T\\$ respectively:

$$\begin{bmatrix} \color{red}1&2&\color{red}4&7\\ 3&\color{red}5&8\\ \color{red}6&9\\ 10 \end{bmatrix} \begin{bmatrix} \color{red}1&2&\color{red}3&4\\ 2&\color{red}3&4\\ \color{red}3&4\\ 4 \end{bmatrix} \begin{bmatrix} \color{red}1&1&\color{red}1&1\\ 2&\color{red}2&2\\ \color{red}3&3\\ 4 \end{bmatrix} \begin{bmatrix} \color{red}0&1&\color{red}2&3\\ 0&\color{red}1&2\\ \color{red}0&1\\ 0 \end{bmatrix}$$

The final result is given by:

$$\cases{N^2-T,&\text{if $T\<N$}\\T^2+N,&\text{if $T\ge N$}}$$

Leading to:

$$\begin{bmatrix} \color{red}1&2&\color{red}5&10\\ 4&\color{red}3&6\\ \color{red}9&8\\ 16 \end{bmatrix}$$

# Answer
> 6 votes
# Haskell, 40 bytes

```
[k^2+k-n*min(2*k-n)1|n<-[1..],k<-[1..n]]
```

Attempt This Online!

-2 bytes thanks to @ovs.

Based on the Mathematica code on OEIS.

# Answer
> 5 votes
# , 44 39 bytes

```
{.&;[:</.@(*+/\"1@,._1+<:/*2*]"0/)~1+i.

```

Try it online!

The formula might have been shorter, but I wanted to construct the matrix and use J's `/.` adverb to get the diagonals, because when you have a primitive to get diagonals you cannot not use it.

To construct the matrix, note that the successive deltas have an easy to describe pattern that looks like this:

```
 1  3  5  7  9 11 13
_1  3  5  7  9 11 13
_1 _1  5  7  9 11 13
_1 _1 _1  7  9 11 13
_1 _1 _1 _1  9 11 13
_1 _1 _1 _1 _1 11 13
_1 _1 _1 _1 _1 _1 13

```

and that the first column are the squares. So we just zip them together:

```
 1  1  3  5  7  9 11 13
 4 _1  3  5  7  9 11 13
 9 _1 _1  5  7  9 11 13
16 _1 _1 _1  7  9 11 13
25 _1 _1 _1 _1  9 11 13
36 _1 _1 _1 _1 _1 11 13
49 _1 _1 _1 _1 _1 _1 13

```

and then scan sum each row to reproduce the matrix:

```
 1  2  5 10 17 26 37 50
 4  3  6 11 18 27 38 51
 9  8  7 12 19 28 39 52
16 15 14 13 20 29 40 53
25 24 23 22 21 30 41 54
36 35 34 33 32 31 42 55
49 48 47 46 45 44 43 56

```

# Answer
> 5 votes
# Python, 67 bytes

```
n=0
while n:=n+1:[print(k*k+k-n*min(2*k-n,1))for k in range(1,n+1)]
```

Attempt This Online!

Port of Haskell. Outputs infinitely.

Old answer:

## Python, 77 bytes

```
n=0
while n:=n+1:[print(n<2*k-1and-~k*k-n or(n-k)**2+k)for k in range(1,n+1)]
```

Attempt This Online!

# Answer
> 4 votes
# C (gcc), ~~86~~ \\$\cdots\\$ ~~60~~ 55 bytes

```
t;f(n){t=sqrt(2*n)+.5;n=(t-=n-=t*~-t/2)<n?n*n-t:t*t+n;}

```

Try it online!

*Saved a whopping 13 bytes thanks to ceilingcat!!!*
*Saved yet another a whopping ~~13~~ 18 bytes thanks to the man himself Arnauld!!!*

Returns the \\$n^\text{th}\\$ term.
Uses the formula from A060736.

# Answer
> 3 votes
# Factor, ~~86~~ 83 bytes

```
0 [ 1 + 3 dupn [1,b] [ 3 dupn sq + -rot 2 * over - 1 min * - . ] with each t ] loop

```

Attempt This Online!

Outputs the sequence indefinitely. Loosely based on alephalpha's Haskell answer.

# Answer
> 3 votes
# Retina, 83 bytes

```
.+
*
(^_|\1_)*(_+)
$.2*$2$2,$.1*$($1___)__-$.2*2*$($1_);$1_
,|(_+)-\1_*

(_+);\1

_

```

Try it online! Link includes test cases. Outputs the `n`th term. Explanation: Loosely based on @alephalpha's formula.

```
.+
*

```

Convert `n` to unary.

```
(^_|\1_)*(_+)

```

Decompose `n` into a triangular number `t-1` and a residue `k` in the range `1..t`.

```
$.2*$2$2,$.1*$($1___)__-$.2*2*$($1_);$1_

```

Calculate `k*k+k`, `t*t+t`, `2*k*t` and `t`.

```
,|(_+)-\1_*

```

Subtract `2*k*t` from `t*t+t`, clamping the result at `0`, and add on `k*k+k`.

```
(_+);\1

```

Subtract `t` from the previous result.

```
_

```

Convert to decimal.

# Answer
> 3 votes
# 05AB1E, 19 bytes

```
[¼¾ENnN+¾N·¾-1‚ß*-,

```

Port of *@alephalpha*'s Haskell answer.

Outputs indefinitely.

Try it online.

**Explanation:**

```
[                   # Loop indefinitely:
 ¼                  #  Increase variable `c` by 1 (0 by default)
  ¾E                #  Inner loop `N` in the range [1,`c`]:
                  , #   Pop and output:
    NnN+¾N·¾-1‚ß*-  #    N²+N-c*min(2N-c,1)
    Nn              #    N²
      N+            #      +N
                 -  #        -
        ¾       *   #         c*
             1‚ß    #           min(    ,1)
         N·         #               2N
           ¾-       #                 -c

```

# Answer
> 3 votes
# Vyxal, ~~28~~ 27 bytes

```
⇧Þ□λ÷N^›WDṘ²+^∑1<i;ÞZÞḋIRfi

```

Try it Online!

Based on @Arnauld's Javascript answer.

–1 per @emanresu A.

## How?

```
λ÷N^›WDṘ²+^∑1<i; # find the (i, j)th entry of the matrix
λ              ; # lambda           STACK (top ->)
 ÷               # unwrap           i j
  N              # negate           i -j
   ^             # reverse stack    -j i
    ›            # increment        -j i+1
     W           # wrap             [i+1,-j]
                 #                = [N,-T] (using Arnaud's notation)
      D          # triplicate       [N,-T] [N,-T] [N,-T]
       Ṙ         # reverse          [N,-T] [N,-T] [-T,N]
        ²        # square           [N,-T] [N,-T] [T^2,N^2]
         +       # sum              [N,-T] [T^2+N,N^2-T]
          ^      # reverse stack    [T^2+N,N^2-T] [N,-T]
           ∑     # sum              [T^2+N,N^2-T] N-T
            1<   # is < 1?          [T^2+N,N^2-T] (1 if N-T<1 else 0)
                 #                = [T^2+N,N^2-T] (1 if T>=N else 0)
              i  # index            N^2-T if T>=N else T^2+N

⇧Þ□λ÷N^›WDṘ²+^∑1<i;ÞZ # make the matrix
⇧                     # double increment, pushing N+2
 Þ□                   # (Nx2)x(Nx2) identity matrix
   λ÷N^›WDṘ²+^∑1<i;   # (above function)
                   ÞZ # fill by coordinates, i.e. replace each entry
                      # of the matrix with the result of calling the
                      # function on the entry's list of coordinates

ÞḋIRfi # output              example (3x3 matrix)
Þḋ     # antidiagonals       [[5,3,9],[2,4],[1],[7],[6,8]]
  I    # into two pieces     [ [[5,3,9],[2,4],[1]] , [[7],[6,8]] ]
   R   # vectorized reverse  [ [[1],[2,4],[5,3,9]] , [[6,8],[7]] ]
    f  # flatten             [1,2,4,5,3,9,6,8,7]
     i # index by input

```

# Answer
> 2 votes
# Python 3.8, 72 bytes

*-18 bytes thanks to the formula of `Arnauld` and -10 bytes thanks to `Kevin Cruijssen`.*

```
lambda n:(t:=int((2*n)**.5+.5),(n:=n-t*~-t/2)*n-(t:=t-n),t*t+n)[2-(t<n)]

```

Attempt this online

# Answer
> 2 votes
# APL+WIN, 22 bytes

Prompts for input matrix. Index origin = 0

```
(,m)[⍋+⌿(⍴m)⊤(⍳⍴,m←⎕)]

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# Charcoal, 32 bytes

```
ＮθＦθＦ⊕ι⊞υ⁻×⊕κ⁺²κ×⊕ι⊕⌊⟦⁰⁻⊗κι⟧Ｉ…υθ

```

Try it online! Link is to verbose version of code. Outputs the first `n` terms. Explanation: Based on @alephalpha's Haskell answer.

```
Ｎθ

```

Input `n`.

```
Ｆθ

```

Generate `n` antidiagonals, to avoid having to do square roots to find out how many antidiagonals are actually needed.

```
Ｆ⊕ι⊞υ⁻×⊕κ⁺²κ×⊕ι⊕⌊⟦⁰⁻⊗κι⟧

```

Compute the values on each antidiagonal.

```
Ｉ…υθ

```

Output the first `n` terms.

---
Tags: code-golf, sequence, grid
---