title: Print my clock's alarm sound

text:
# Question
Title: Print my clock's alarm sound
Write the shortest program that prints the sound my alarm clock makes, and stops after an inputted number of `beep`s.

For reference, here is the sound my alarm makes:

```
beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep

```

Basically `beep`, `beepbeep`, `beepbeepbeep`, and `beepbeepbeepbeep` repeated 5 times each with spaces in between, followed by a `beepbeep...beep` which is 25 `beep`s long with no spaces in between (does `beep` still sound like a word to you?).

Your program should take a number as input (assume it's between 0 and 75), and stop printing after that many `beep`s.

**Note:** Your program should stop after that many beeps, not after that many groups of beeps. For example, `7` will return `beep beep beep beep beep beepbeep`.

Whitespace in between `beep`s must follow the exact pattern above, although any trailing whitespace or unsuppressable output from your compiler or interpreter is allowed.

Test cases:

```
3   beep beep beep
0
1   beep
7   beep beep beep beep beep beepbeep
8   beep beep beep beep beep beepbeep beep
55  beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeep
67  beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep

```

This is code golf, so the shortest answer in bytes, per language, wins.

# Answer
> 29 votes
# JavaScript (ES7),  ~~55~~  54 bytes

```
f=n=>n?f(n-1)+'beep'+[" "[n>50|n%~~(n**=.4)^52%~n]]:''

```

Try it online!

### How?

Given \\$1\le n\< 50\\$, we want to know the number of consecutive beeps that are expected in this part of the sequence. The exact value is given by:

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

which is a slightly modified version of A002024.

But in practice, we only need an exact value on the boundaries of the runs of beeps and we can deal with a few off-by-one errors. That's why we instead compute the following approximation:

$$k=\left\lfloor n^{2/5}\right\rfloor$$

We need to insert a space whenever one of the following conditions is satisfied:

* \\$k=1\\$ and \\$n\bmod 1=0\\$ (the 2nd part being always true)
* \\$k=2\\$ and \\$n\bmod 2=1\\$
* \\$k=3\\$ and \\$n\bmod 3=0\\$
* \\$k=4\\$ and \\$n\bmod 4=2\\$

All the above conditions can be merged into:

$$(n \bmod k) = (52 \bmod (k+1))$$

\\$52\\$ being the smallest integer \\$x\>0\\$ such that \\$x\bmod 3=1\\$, \\$x\bmod 4=0\\$ and \\$x\bmod 5=2\\$.

We need an additional test for \\$n\ge50\\$, where all remaining beeps are concatenated together. Otherwise, unwanted spaces would be inserted, starting at \\$n=54\\$.

Hence the final JS expression:

```
n > 50 | n % ~~(n **= 0.4) ^ 52 % ~n

```

which evaluates to `0` when a space must be inserted.

---

# JavaScript (ES7), 55 bytes

A simpler approach using a lookup bit mask.

```
f=n=>n?f(--n)+'beep'+(0x222222492555F/2**n&1?' ':''):''

```

Try it online!

# Answer
> 17 votes
# x86-16 machine code, IBM PC DOS, ~~58~~ ~~54~~ 53 bytes

Binary:

```
00000000: a182 0086 e02d 3030 d50a 7423 95b8 2009  .....-00..t#.. .
00000010: b305 b101 8bf1 ba30 01cd 2183 fe05 740c  .......0..!...t.
00000020: e20a 4b75 03b3 0546 8bce cd29 4d75 eac3  ..Ku...F...)Mu..
00000030: 6265 6570 24                             beep$

```

Listing:

```
A1 0082         MOV  AX, WORD PTR [82H] ; command line AL = first char, AH = second char
86 E0           XCHG AH, AL             ; endian convert
2D 3030         SUB  AX, '00'           ; ASCII convert
D5 0A           AAD                     ; BCD to binary convert
74 23           JZ   EXIT               ; handle 0 input case
95              XCHG AX, BP             ; Beeps Counter (BP) = user input
B8 0920         MOV  AX, 0920H          ; AH = 9, AL = ' '
B3 05           MOV  BL, 5              ; Space Counter (SC) = 5
B1 01           MOV  CL, 1              ; Beeps per Space Counter (BpSC) = 1
8B F1           MOV  SI, CX             ; Beeps per Space (BpS) = 1
BA 0130         MOV  DX, OFFSET BEEP    ; DX pointer to 'beep' string
            BEEP_LOOP:
CD 21           INT  21H                ; display beep
83 FE 05        CMP  SI, 5              ; exceeded 50 beeps?
74 0C           JZ   NO_SPACE           ; if so, don't display space
E2 0A           LOOP NO_SPACE           ; if BpSC not zero, don't display space
4B              DEC  BX                 ; decrement Space Counter (SC)
75 03           JNZ  DO_SPACE           ; if SC is zero, restart it and increment BpS
B3 05           MOV  BL, 5              ; reset SC to 5
46              INC  SI                 ; increment BpS
            DO_SPACE:
8B CE           MOV  CX, SI             ; reset Beeps per Space Counter (BpSC)
CD 29           INT  29H                ; display space
            NO_SPACE:
4D              DEC  BP                 ; decrement Beeps Counter (BP)
75 EA           JNZ  BEEP_LOOP
            EXIT:
C3              RET                     ; return to DOS

        BEEP    DB   'beep$'

```

Someone in the comments described this challenge as "evil". I wouldn't go that far... but definitely lacking empathy.

Arbitrary modulos can be pesky in x86 when registers are tight. This is the inelegant counter/countdown approach (seemed only appropriate for an alarm clock challenge), basically just jockeying these three counters:

* `SI` = *Beeps per Space (`BpS`)*: Start at `1`. Increment every `5` spaces displayed. Once `5` is reached, no more spaces are displayed.
* `BX` = *Space counter (`SC`)*: Start at `5`. Decrement every space displayed. At `0`, increment `BpS` and reset to `5`.
* `CX` = *Beeps per Space Counter (`BpSC`)*: Start at `1`. Decrement every `'beep'` displayed. At `0`, display a space and reset to current `BpS`.

A standalone PC DOS executable, input is via command line.

**Props: -1 byte thx to @gastropner!**

# Answer
> 11 votes
# Python 3, ~~134~~ ~~124~~ 118 bytes

```
def f(n):
 b=[*'beep']*n
 for i in b'\4\t\16\23\30!*3<ER_ly\x86\x97\xa8\xb9\xca\xdb':b.insert(i,' ')
 return''.join(b)

```

Try it online!

Explanation: Simply works by inserting a blank space at the required indices of the string.

*Thanks to pxeger for -6 bytes*

# Answer
> 9 votes
# , 95 bytes

```
substr(s<-Reduce(paste,strrep("beep",c(rep(1:4,e=5),25))),1,c(el(gregexpr("b",s))[scan()]+3,0))

```

Try it online!

Thanks to @Dingus for pointing out a bug which made my code longer (and also wrong). Thanks to madlaina for suggesting a better regex.

Outgolfed handily by Dominic van Essen.

```
nreps <- c(rep(1:4,e=5),	# repeat the beeps 1,2,3,4 each 5 times
		25)		# and 25 times
beep <- strrep("beep",nreps)	# build a list of the repeated "beep"s
s <- Reduce(paste,beep)		# combine into one string, separated by spaces
i <- el(gregexpr("b",s))	# find the start index of each occurrence of a "beep"
e <- i[scan()]+3		# find the end index: the starting point of the n'th beep + 3
substr(s,1,c(e,0))		# and substring into s from 1 to e (or 0 if e is empty)

```

# Answer
> 8 votes
# dotcomma (old), 96577 bytes

Dotcomma is a language I created. I don't think I have any documentation or interpreter to link to yet, so it's not really competing at the moment. Takes input based on the number of inputs. Because it's so long, and very repetitive, here's the two blocks it's made up of:

**For every `beep` without a space:**

```
[[,.],[[[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,]]]

```

**For every `beep` with a space:**

```
[[,.],[[[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,]]]

```

There's probably a way to golf down those constants. Anyway, I'll post an explanation when I have time.

**Update:** Dotcomma now has documentation and an interpreter. Because I added so many important new features since I posted this, it's practically a different language. If anyone else wants to post a different dotcomma answer that uses the full extent of the language's features, go ahead!

# Answer
> 8 votes
# , ~~89~~ ~~87~~ ~~73~~ 69 bytes

*Edit: -20 (yes, 20) bytes thanks to Giuseppe*

```
x=scan();cat(strrep("beep",c(b<-(a=5:24%/%5)[cumsum(a)<x],x-sum(b))))

```

Try it online!

The guts of this are stolen from Giuseppe's R answer, so please upvote that one... Edit: especially after he's now massively golfed-down this one!

However, I wanted to see whether a simpler, non-regex approach of constructing the correct number of 'beep'-repetitions (instead of making a very long one and then cutting it down) could be shorter.

So far it is...

# Answer
> 8 votes
# Python 2, 59 bytes

```
f=lambda n:n*"?"and f(n-1)+"beep "[:4|0x444444924aabe>>n&1]

```

Try it online!

Uses a hardcoded lookup table to decide whether to put a space after each beep. I attempted to make formulas instead but didn't find something shorter.

# Answer
> 7 votes
# Husk, ~~16~~ 15 bytes

```
wmΣC:Ṙ5ḣ4¹R¨⁸ep

```

Try it online!

## Explanation

```
¨⁸ep    Compressed string literal "beep"
R       Repeat n times, n is input:
          ["beep","beep",..,"beep"]

C:Ṙ5ḣ4¹    Cut the above into pieces.
    ḣ4     Range to 4: [1,2,3,4]
  Ṙ5       Replicate 5 times:
             [1,1,1,1,1,2,2,2,2,2,..,4]
 :    ¹    Append n:
             [1,1,1,1,1,2,2,2,2,2,..,4,n]
C          Cut the beep list to these lengths:
             [["beep"],["beep"],..,[..,"beep","beep"]]
           C stops when it runs out of elements, possibly cutting the last list short.
           In this case it has to, since the beep list has length n.

mΣ    Concatenate each:
        ["beep","beep",..,"beepbeep...beep"]
w     Join by spaces, implicitly print.

```

# Answer
> 7 votes
# Poetic, 853 bytes

```
anything i did was futile
o,a clock i set definitely failed
i know i,at one A.M,crave a rest
i notice,o!the alarm!it beeps
it provides no break to get a dream
its six A.M
aaggh,i got up
should i get sleep at six A.M while in bed?nope,never
i need to snooze now,but couldnt
im tired
ill get cereal:a bowl,milk,flakes
o no,the milk spills
dammit,i shout,getting kleenex and old unclean napkins
next,the pouch of frosted flakes
finally,i make a toast
i look,o no!eight A.M
must i hustle,so i begin at ten?i needed to rush,i am tardy
so i change:i get a jacket,i get a shirt
aw hell,o no,found no pair o pants
ill clearly suffer in a pair o boxers
i see,o no!eleven A.M
its a shame,o,too late
really,ill wear a blouse
so now i hurry
o,here now
i sit
time flies
i see,o my!three P.M
now i earned a rest
i badly ne-ee-ee-ee-eeeded a nap
i topple,and then i do

```

Try it online!

This was a tough program to write. I wrote the poem about an alarm that wakes me up way too early.

# Answer
> 6 votes
# 05AB1E, ~~22~~ ~~21~~ ~~20~~ 19 bytes

```
F’¼®b’4L5и{¦.¥NåúRJ

```

-1 byte by porting the approach used in multiple other answers.

Try it online or verify all test cases.

---

Original approach:

# 05AB1E (legacy), ~~22~~ 21 bytes

```
'¬ž4L₂¸«×5иé»Z¡I£'p«J

```

Output is joined by newlines. If this has to be spaces instead, 1 byte has to be added by replacing the `»` with `ðý`.

Try it online or verify all test cases.

I wanted to use the legacy version of 05AB1E, since the maximum builtin `Z` works on strings (getting the character with the largest codepoint), which isn't the case in the new version of 05AB1E. This would have saved a byte over `'r`. Unfortunately, the legacy version lacks the append\_to\_list builtin `ª`, so we'll have to use `¸«` instead.

**So here is a regular 05AB1E version as well with the same ~~22~~ 21 bytes:**

```
'¬ž4L₂ª×5иé»'r¡I£'p«J

```

Try it online or verify all test cases.

**Explanation:**

```
F                       # Loop `N` in the range [0, (implicit) input-integer):
 ’¼®b’                  #  Push dictionary string "peeb"
 4L                     #  Push list [1,2,3,4]
   5и                   #  Repeat it 5 times: [1,2,3,4,1,2,3,4,...]
     {                  #  Sort it: [1,1,1,1,1,2,2,2,2,2,...]
      ¦                 #  Remove the first value
       .¥               #  Undelta this list (with implicit leading 0):
                        #   [0,1,2,3,4,6,8,10,12,14,17,20,23,26,29,33,37,41,45,49]
         Nå             #  Check if `N` is in this list (1 if truthy; 0 if falsey)
           ú            #  Pad "peeb" with that many leading spaces
            R           #  Reverse it to "beep" or "beep "
             J          #  Join all strings on the stack together
                        # (after the loop, the result is output implicitly)

'¬ž                    '# Push dictionary string "beer"
   4L                   # Push a list [1,2,3,4]
     ₂                  # Push 26
      ª                 # New version: Append it as trailing item to the list
      ¸«                # Legacy version: Wrap into a list; merge the lists together
                        #  [1,2,3,4,26]
        ×               # Repeat each string that many times:
                        #  ["beer","beerbeer","beerbeerbeer","beerbeerbeerbeer",...]
         5и             # Repeat this list five times
           é            # Sort it based on length
            »           # Join all strings in the list by newlines
             'r        '# New version: Push "r"
             Z          # Legacy version: Push the maximum character (without popping),
                        # which is "r"
               ¡        # Split the string on "r"
                I£      # Leave the first input amount of substrings
                  'p«  '# Append a "p" to each string in the list
                     J  # And join it all together again
                        # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `’¼®b’` is `"peeb"` and `'¬ž` is `"beer"`.

# Answer
> 6 votes
# Jelly,  ~~17~~  16 bytes

```
4Rx5Ä‘œṖȧ€“&?»$K

```

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

**Try it online!**

### How?

```
4Rx5Ä‘œṖȧ€“&?»$K - Link: integer, n     e.g. 8
4                - four                      4
 R               - range                     [1,2,3,4]
   5             - five                      5
  x              - times                     [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4]
    Ä            - accumulate                [1,2,3,4,5,7,9,11,13,15,18,21,24,27,30,34,38,42,46,50]
     ‘           - increment                 [2,3,4,5,6,8,10,12,14,16,19,22,25,28,31,35,39,43,47,51]
              $  - last two links as a monad - i.e. f(n):
          “&?»   -   compressed string       "beep"
        ȧ€       -   (n) AND each ("beep")   ["beep","beep","beep","beep","beep","beep","beep","beep"]
      œṖ         - split before indices      [["beep"],["beep"],["beep"],["beep"],["beep"],["beep","beep"],["beep"]]
               K - join with spaces          "beep beep beep beep beep beepbeep beep"

```

# Answer
> 5 votes
# Python 3, ~~108 120 118~~ 110 bytes

*+12 because I forgot to include the import statement which I had to put in the TIO header, not body*

*-2 by replacing \x00 with \0 - thanks to @ovs*

*-8 by filtering instead of replacing, and switching from `.` to `!`*

```
import zlib;lambda x:filter(33 .__ne__,zlib.decompress(b'x\x9cKJM-PH\xc2A(\x92\xc7\xa26\x97nb4!\0hm{7')[:x*5])

```

Try it online!

### How It Works

Sorry. I couldn't be bothered to come up with a clever algorithm.

`zlib` compressed string: `beep beep beep beep beep beep!beep beep!beep beep!beep beep!beep beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep`

which is indexed into upto `n*5`th character, and then we filter for the bytes which don't equal 33 (exclamation mark). I chose `!` using a brute-force to find the the shortest compressed output from `zlib`.

# Answer
> 5 votes
# Io, ~~81~~ ~~78~~ 75 bytes

Shamelessly ported from Arnauld's answer.

```
f :=method(i,if(i>0,f(i-1).."beep".." "repeated(1200959982447294>>i&1),""))

```

Try it online!

# Io, ~~152~~ 113 bytes

Port of Manish Kundu's answer.

```
method(x,O :=("beep"repeated(x)asList);"	!*3<ER_ly†—¨¹ÊÛ"foreach(i,if(i<x*4,O atInsert(i," ")));O join)

```

Try it online!

## Explanation

```
method(x,    // Input x
    O :=("beep"repeated(x)asList)            // "beep" repeated x times
    "	!*3<ER_ly†—"foreach(i,           // For every codepoint in this string:
        if(i<x*4,                            //     If doing this doesn't cause an error:
             O atInsert(i," ")));            //          Insert at this position
    O join)                                  // Join O without a separator

```

# Answer
> 5 votes
# , 50 46 bytes

```
;@({.<@,&' '@;/.[$<@'beep')&((##\)25,~1+5#i.4)

```

Try it online!

## how

`25,~1+5#i.4` produces:

```
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25

```

`(##\)` pairs that with an integer list of the same length:

```
1 1 1 1 1 2 2 2 2  2  3  3  3  3  3  4  4  4  4  4 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

```

and duplicates the bottom list according to the corresponding element of the top list:

```
1 2 3 4 5 6 6 7 7 8 8 9 9 10 10 11 11 11 12 12 12 13 13 13 14 14 14 15 15 15 16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 20 20 20 20 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21

```

Call this our "key". We're going to use it to group our "beep"s together.

Our key becomes the right argument to `;@({.<@,&' '@;/.[$<@'beep')`.

`[$<@'beep'` first duplicates "beep" according to the input. Say, for an input of 8 we get:

```
┌────┬────┬────┬────┬────┬────┬────┬────┐
│beep│beep│beep│beep│beep│beep│beep│beep│
└────┴────┴────┴────┴────┴────┴────┴────┘

```

`{.` takes the first 8 elements of our key, creating a new key:

```
1 2 3 4 5 6 6 7

```

The key adverb `/.` applies the verb `<@,&' '@;` to each group defined by the new key. It unboxes, appends a space, and reboxes:

```
┌─────┬─────┬─────┬─────┬─────┬─────────┬─────┐
│beep │beep │beep │beep │beep │beepbeep │beep │
└─────┴─────┴─────┴─────┴─────┴─────────┴─────┘

```

`;@` unboxes again, giving the result:

```
beep beep beep beep beep beepbeep beep

```

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

```
If[#==0,"",c=#;T@v_:=v~Table~5;w=Accumulate[z=Flatten@{T/@Range@4,25}];StringRiffle[""<>#&/@Join[1~Table~#&/@z[[;;Max@Position[w,m=Max@Select[w,#<=c&]]]],{Table[1,c~Mod~m]}]/. 1->"beep"]]&

```

Try it online!

# Answer
> 4 votes
# Python 3 , 164 Bytes

Try it online

This is my recursive approach. Somehow it's worse than I imagined it in my head.

Explanation: *n* is the input number

The *g* function generates the beep sequence, where *x* controls the numbers of "beep"s . Every 4th call *x* is incremented by 1, and with the 16th call it's set to 25. In the next call it's reset to 1 . *g* generates *n* groups of "beep"s the string is stored in *v*

*f* cuts *v* to the corrext number by searching for the next "b" in *v* until *n* is reached.

```
g=lambda s,x,m:s if m>n else g(s+"beep"*x+" ",([25,1]+[x+(m%4<1)]*14)[(m+1)%16],m+1)
v=g("",1,1)
f=lambda m,i:v[:i] if m>n else f(m+1,v.find("b",i+1))
print(f(1,1))

```

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

```
∊' ',⍨¨(⎕↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep'

```

Try it online!

With significant golfing input from ngn.

### Explanation

The code inside the parens builds a boolean array describing the grouping pattern, which we'll come back to below; quad () prompts for the quantity of beeps and the pattern is cut to that number. To the right of the parens the word `'beep'` is enclosed (monadic ) to make it a single thing (instead of an array of 4 characters), and that is partition-enclosed (dyadic ) by the pattern which groups the beep and implicitly repeats it to match the cut pattern length. To the left of the parens, the `beep`s get one space (`' '`) appended (`,⍨`) to each (`¨`) group of them, then get flattened () into the result string.

Building the group pattern follows this progression:

```
      5/⍳4           ⍝ five-replicate the first four numbers

1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4

      25,⍨5/⍳4       ⍝ append 25 for the long run

1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25

      ↑⍨¨25,⍨5/⍳4    ⍝ turn each (¨) of the numbers into
                     ⍝ a group that long, padded with zeros.
                     ⍝ using take selfie (↑⍨).
                     ⍝ e.g. Take first 3 items out of "3", get 3 0 0.
┌→┐ ┌→┐ ┌→┐ ┌→┐ ┌→┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→─────────────────────────────────────────────────┐
│1│ │1│ │1│ │1│ │1│ │2 0│ │2 0│ │2 0│ │2 0│ │2 0│ │3 0 0│ │3 0 0│ │3 0 0│ │3 0 0│ │3 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0│
└~┘ └~┘ └~┘ └~┘ └~┘ └~──┘ └~──┘ └~──┘ └~──┘ └~──┘ └~────┘ └~────┘ └~────┘ └~────┘ └~────┘ └~──────┘ └~──────┘ └~──────┘ └~──────┘ └~──────┘ └~─────────────────────────────────────────────────┘

      ∊↑⍨¨25,⍨5/⍳4    ⍝ flatten (∊) the nesting

1 1 1 1 1 2 0 2 0 2 0 2 0 2 0 3 0 0 3 0 0 3 0 0 3 0 0 3 0 0 4 0 0 0 4 0 0 0 4 0 0 0 4 0 0 0 4 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

      ×∊↑⍨¨25,⍨5/⍳4    ⍝ use direction (×) to turn all non-zero into 1
                       ⍝ 1 marks the start of each group, 0 pads their length.
                       ⍝ A boolean group-array for the full beep pattern

1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

      20↑×∊↑⍨¨25,⍨5/⍳4    ⍝ take (↑) 20 beeps. (⎕ number beeps)
                          ⍝ This is how it cuts in the middle of a
                          ⍝ run of beepbeepbeep, by cutting the pattern.

1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0

      (20↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep'    ⍝ p-enclose of 'beep' shows the grouping,
                                    ⍝ and the cutoff group at the end.

┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→─────────────────────┐ ┌→──────────────┐
│ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │
│ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │beep│ │ │ │beep│ │beep│ │
│ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ └────┘ │ │ └────┘ └────┘ │
└∊───────┘ └∊───────┘ └∊───────┘ └∊───────┘ └∊───────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊─────────────────────┘ └∊──────────────┘

      ∊' ',⍨¨(20↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep'    ⍝ append one space in each group
                                           ⍝ and flatten.

beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeep

```

# Answer
> 3 votes
# Rust, 76 ~~127~~ bytes

```
|n|(0..n).fold("".into(),|a,i|a+"beep"+&" "[..0x222222492555F>>i.min(63)&1])

```

Try it online!

Shamelessly ported from Arnauld's JS solution

The binary constant has a bit set wherever the "beep" should be followed by a space.

## Old solution

```
|n|[1,2,3,4,25].iter().fold(format!(""),|a,&i|a+&("beep".repeat(i)+" ").repeat(5)).rsplitn(176-n,'b').last().map(str::to_owned)

```

Try it online!

### Explanation:

We first construct the string `beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep...` with the last 25 successive `beep`s also being repeated 5 times. This string contains 175 `beep`s, so we trim from the right to and including the `176-n`th `b` and take the sub string left of there.

# Answer
> 3 votes
# C (gcc), ~~72~~ \\$\cdots\\$ ~~66~~ 60 bytes

Saved 10 bytes thanks to the man himself Arnauld!!!

```
f(n){n&&printf(" beep"-~-(0x888889249557c>>n&n<55),f(n-1));}

```

Try it online!

Recursively calls itself \\$n\\$ times evaluating a bitwise expression (where the \\$1\\$ bits of a hard coded integer indicate if a space is needed) to determine whether or not to prefix the current `beep` with a space. This is done by adding \\$0\\$ or \\$1\\$ to a string literal (`char*` pointer) to offset it by one or not.

# Answer
> 3 votes
# APL+WIN, 50 bytes

Prompts for input of n:

```
(4×(p/m),¯1↑-(p←n≤0)/n←(+\m←(5/⍳4),25)-⎕)⍴¨⊂'beep'

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 3 votes
# Charcoal, 23 bytes

```
ＦＮ«beep¿＆⍘(XsB!,zOγＸ²ι→

```

Try it online! Link is to verbose version of code. Uses the popular bitmask approach. Explanation:

```
ＦＮ«

```

Loop the given number of times.

```
beep

```

Print a beep.

```
¿＆⍘(XsB!,zOγＸ²ι→

```

If the appropriate bit in the constant is set, then move right one character. The constant is probably the same as everyone else's but here I'm effectively encoding it using base 95.

# Answer
> 3 votes
# PowerShell, 68 bytes

```
(0.."$args"|%{' '*((0x444444924AABE-shr$_)%2)*($_-lt52)})-join'beep'

```

Try it online!

The script:

1. generates an array of whitspace and empty strings
2. joins array elements with 'beep'

The script can add a trailing whitespace that is allowed by the author. See the test cases in the TIO link.

The Powershell works with 64 bitmasks only, so I had to add a condition `($_-lt52)`

# Answer
> 3 votes
# Vyxal, 20 bytes

```
4ɾƛS5*fvI;?Jf«⟇½⁰«*Ṅ

```

Try it Online!

# Answer
> 2 votes
# Lua, 105 bytes

```
function b(n)t={}for i=5,24 do t[(i-1)*(i-2)//10]=' 'end for i=1,n do io.write('beep'..(t[i]or''))end end

```

Ungolfed code and test program:

```
function b(n)
    t={}
    for i=5, 24 do
        t[(i-1)*(i-2)//10] = ' '
    end
    for i=1, n do
        io.write('beep' .. (t[i] or ''))
    end
end

for k, v in ipairs({ 3, 0, 1, 7, 8, 55, 67, 75 }) do
    io.write(v .. '\t') b(v) print()
end

```

Output:

```
3   beep beep beep
0
1   beep
7   beep beep beep beep beep beepbeep
8   beep beep beep beep beep beepbeep beep
55  beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeep
67  beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep
75  beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep

```

Try it online

Edit 1: Thank you for your suggestions :) It greatly helped to compress the sequence that was used.

Edit 2: 99 Bytes solution provided by Arnault, getting rid of the (-1) and using a partial and clever one's complement to decrease a number:

```
function b(n)t={}for i=4,23 do t[i*~-i//10]=' 'end for i=1,n do io.write('beep'..(t[i]or''))end end

```

Try it online

# Answer
> 2 votes
# PowerShell 5.1, 227 bytes

```
$n=10;function f($x){$r.Length-in$x};$c=0;$r="";$t=0;while($c-lt$n){$s=-1;switch($true){{f(0..24)}{$s=1}{f(25..69)}{$s=2}{f(70..134)}{$s=3}{f(135..219)}{$s=4}};$r+="beep";$t++;if($t-ne$s){$c++;continue};$r+=" ";$t=0;$c++};$r

```

Explanation: $n is the input number. I tried to write this without doing it via arrays because I felt like it would be cheating, as I had already read this answer. I used the length of the string to determine how many "beeps" were needed before I placed a space. If the length of the string is between 0 and 24, 1 space. If the length of the string is between 25 and 69, 2 spaces. etc.

Here's the "cleaner" version

```
$n = 9
function bl ($x) {$beepString.Length -in $x}
$count = 0
$beepString = ""
$beepsThisTime = 0
while($count -lt $n)
{
    $neededBeepsBeforeSpace = -1
    switch($true)
    {
        {bl(0..24)}{$neededBeepsBeforeSpace = 1}
        {bl(25..69)}{$neededBeepsBeforeSpace = 2}
        {bl(70..134)}{$neededBeepsBeforeSpace = 3}
        {bl(135..219)}{$neededBeepsBeforeSpace = 4}
    }

    $beepString += "beep"
    $beepsThisTime++
    if($beepsThisTime -ne $neededBeepsBeforeSpace){$count++;continue}
    $beepString+=" "
    $beepsThisTime = 0
    $count++
}
$beepString

```

# Answer
> 2 votes
## Setanta, ~~146~~ ~~144~~ ~~140~~ ~~124~~ 123 bytes

*-16 bytes by using a cheaper check for the first beep.*
*-1 byte by discovering that braces could be left out in one place.*

```
gniomh(n){s:=""le i idir(0,n){a:=(i&freamh@mata((i-1)//5*8+1)+1)//2d:=(i-5*(a*a-a)/2)%a ma!d&i<51 s+=" "s+="beep"}toradh s}

```

Try it here!

# Answer
> 2 votes
# dotcomma, ~~617~~ 569 bytes

```
[,].[[[,.][[[[[.][.][.][.].,][,.].,][,.].,][[,][[[,][,.].,][,][,].,].,][,][[[,.][.][.].,][.][.][.].,][,][[[,.][[[,.][[,]].,][],].,],].[,][.,][[.][.][.][.][.].,].[.[.[[[,.][[].[],].,][[,][[,][[[[,][[[,],]].,],]].,][],][.[.[,].][,][,]].][,][[,][[,][,][,]].,][.[.[,].]][[,.][[].[],].,],.[[[,][[,.]].,][.[.[,].][,]]],.[.[.[,].][,[.][.][.][.][.].,][,]][,],.][.[.[,].][,]][[[,.][[].[],].,][,.].,].[.[,].][,][,],.][,][.[.[,].]][,[,[,[,[,[,[,[,.]]]]]]]]].,].[[.[.[,].]][[,.][[].[],].,][.[[,],]][.[.[,].][,][,]][.[,]][,.][.[.[,].][,][,.]][.[[,][,.],.]].][.[.[,.].]][,.]],.[[,.]]
```

-48 bytes by rearranging the last counter loop and thereby avoiding duplicate code.

Phew, I need to rearrange my brain again... Bracket chaos ^^

This is first try with this language. It's quite fun. The changes made to the old version seem to be very effective when I can shrink the program size to less than 1% of the old version. Are there plans to put this language on tio.run? What about plumber? I think that's interesing, too.

Use the following snippet on your own risk (especially when changing the dotcomma code. I had several freezes because I unintetionally created endless loops)

```
<script src="https://combinatronics.com/Radvylf/dotcomma/master/interpreter.js"></script><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script><script>$(document).ready(function () {$("#btnInterpret").click(function () {$("#txtResult").text(interpret($("#txtCode").val(), parseInt($("#txtInput").val()), $("#lstOutputAs").children("option:selected").val()));});});</script><style>.textBox {background-color: white;border: 1px solid black;font-family: Courier New, Courier, monospace;width: 100%;}</style>Code: <textarea id="txtCode" type="text" class="textBox" style="height: 200px">[,].[[[,.][[[[[.][.][.][.].,][,.].,][,.].,][[,][[[,][,.].,][,][,].,].,][,][[[,.][.][.].,][.][.][.].,][,][[[,.][[[,.][[,]].,][],].,],].[,][.,][[.][.][.][.][.].,].[.[.[[[,.][[].[],].,][[,][[,][[[[,][[[,],]].,],]].,][],][.[.[,].][,][,]].][,][[,][[,][,][,]].,][.[.[,].]][[,.][[].[],].,],.[[[,][[,.]].,][.[.[,].][,]]],.[.[.[,].][,[.][.][.][.][.].,][,]][,],.][.[.[,].][,]][[[,.][[].[],].,][,.].,].[.[,].][,][,],.][,][.[.[,].]][,[,[,[,[,[,[,[,.]]]]]]]]].,].[[.[.[,].]][[,.][[].[],].,][.[[,],]][.[.[,].][,][,]][.[,]][,.][.[.[,].][,][,.]][.[[,][,.],.]].][.[.[,.].]][,.]],.[[,.]]</textarea><br />Input: <textarea id="txtInput" type="text" class="textBox">25</textarea><br /><input id="btnInterpret" type="button" value="Run" />Output as: <select id="lstOutputAs"><option value="true">String</option><option value="">Number array</option></select><br />Result:<br /><div id="txtResult" class="textBox" style="overflow-wrap: break-word"></div>
```

**Code:**

(sorry for the missing interpunctuation. This way I was able to run the commented code directly in the interpreter)

```
[,].[                           if input > 0
  [[,.][                        save input on recursion stack
    [
      [                         ### Build ASCII values for "b" "e" "p" and space " "
        [[.][.][.][.].,]        4
      [,.].,]                   8
    [,.].,]                     16

    [[,]                        put 16 on recursion stack and save copy in queue
      [
        [[,][,.].,]             32
      [,][,].,]                 96
    .,]                         112 ("p")
                                in queue: 32 96 112
    [,]                         roll left (queue: "@p ")
    [[[,.][.][.].,][.][.][.].,] "b" "e"
    [,]                         roll left (queue: " bep")
    [[[,.][                     save " " on recursion stack
      [[,.][[,]].,]             reverse letters ("peb")
      [],                       insert 0 (start of queue)
    ].,],]                      save two copies of 32 (one for space character and one for counting beeps)

                                ### Build list of "beep"s in reverse - each separated by a null char

                                Since the maximum input is 75 the 25 consecutive beeps at the end
                                will be limited by the input - so I can safely put a few more
                                beeps into the list because I just have a 32 handy

                                sc: spaces counter
                                pc: pattern counter
                                bc: beep counter

                                target queue: 0 0 sc pc bc " peb"
                                current queue: "peb" 0 bc(32) " "

                                I will refer to the two consecutive 0s at the start of the variable
                                section as "start of queue" or just "start"

                                pc: |           1           |                   2                       |
                                sc: | 1 |  2 |  3 |  4 |  5 |    1   |    2   |    3   |    4   |    5  |
                                bc: | 1 |  1 |  1 |  1 |  1 |  1 | 2 |  1 | 2 |  1 | 2 |  1 | 2 | 1 | 2 |
                                    beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep

    .[,]                        roll to start
    [.,]                        insert 1 for spaces counter (since I append new beeps to the start of the
                                queue we are only one space away from the next pattern)
    [[.][.][.][.][.].,]         insert 5 for pattern counter
                                queue: pc(5) bc(32) " bep" 0 sc(1)

    .[                          while pattern counter > 0 ### Attention: current position is beep counter!
      .[                        while spaces counter > 0 ### Attention: current position is beep counter!
        .[                      while beep counter > 0
          [[,.][[].[],].,]      save beep counter -1 on queue (also hold it in recursion stack)

          [                     # put a copy of "beep" on the queue
            [,]                 roll over " "
            [[,][[              put "p" on recursion stack
              [[,][[            put "e" on recursion stack
                [,]             put "b" on recursion stack
                ,]]             put "b" on queue
              .,],]]            put "ee" on queue
            .,]                 put "p" on queue
            [],                 put 0 on queue
          ]
          [
            .[.[,].]            roll to start (roll until two consecutive 0s are found)
            [,][,]              go to beep counter
          ]
        .]                      return value for loop (end of beep counter loop)

                                # insert space
        [,]                     roll over beep counter
        [[,][[,][,][,]].,]      copy and insert space

                                # if spaces counter - 1 > 0: copy pattern counter to beep count
                                (the pattern counter contains the number of consecutive beeps
                                that should be separated by a space)

        [.[.[,].]]              roll to spaces counter
        [[,.][[].[],].,]        decrement spaces counter
        ,.[                     if spaces counter > 0
          [[,][[,.]].,]         replace beep counter with copy of pattern counter
          [.[.[,].][,]]         roll to pattern counter (if the spaces loop repeats we need to be at
                                the beep counter; I will read the next value to determine if the loop
                                should repeat; Thats's why I stop one value before beep counter)
        ],.[                    else
          .[.[,].]              roll to spaces count
          [,[.][.][.][.][.].,]  set it 5 for next round
          [,]                   roll to beep count
        ]
        [,],.                   get return value for loop (pattern counter for repeating
                                or beep counter(0) for stopping)
      ]                         end of spaces loop

      [.[.[,].][,]]             roll to pattern counter
      [
        [[,.][[].[],].,]        decrement pattern counter
        [,.].,                  set new beep counter = pattern counter
      ]
      .[.[,].][,]               roll to pattern counter
      [,],.                     repeat if > 0
    ]                           end of pattern loop
    [,][.[.[,].]]               roll to start
    [,[,[,[,[,[,[,[,.]]]]]]]]   delete variables constants and excess space in front of first beep
  ].,]                          put input back into queue

                                ### Count beeps
                                The idea is to delete all 0s between the beeps until we match the input
                                then deleting everything behind it
                                I thought it would be easy to delete single 0s - What I didn't consider was
                                that I can end a loop only after a 0 has been processed so I needed a trick
                                What I do is: duplicate every character until I reach a 0 (which will also
                                be duplicated)
                                Then find the first 0 (reassigning it to the end of the queue) and delete
                                the second 0
                                After that I can delete the duplicated characters including the 0

  .[                            while input counter > 0
    [.[.[,].]]                  roll to start
    [[,.][[].[],].,]            decrement input counter
    [.[[,],]]                   duplicate until first 0
    [.[.[,].][,][,]]            roll to start + 2
    [.[,]]                      roll to first 0
    [,.]                        delete second 0
    [.[.[,].][,][,.]]           roll to start + 2 (deleting the second character)
    [.[[,][,.],.]]              delete every 2nd character until 0 found
  .]                            end of loop                     end of loop

  [.[.[,.].]]                   delete everything up to start
  [,.]                          delete input counter

],.[                            else (if input is 0)
  [,.]                          delete input and output nothing
]

```

# Answer
> 2 votes
# Zsh, 64 bytes

```
repeat $1 z+=beep.
repeat 4 repeat x+=5,5 z[t+=x]=\
<<<${z//./}

```

Try it online!

Because of a bug that's not fixed in the Zsh version available on TIO, the `x+=5,5` needs to be single-quoted for +2 bytes.

Works by constructing a string of `beep.`, replacing some `.`s with spaces, and then removing the `.`s. The differences in the indeces at which to remove the `.`s are `5, 5, 5, 5, 5, 10, 10, ... 15, 15, 20, 20, 20, 20, 20`, so we cumulatively sum these as we go.

* `repeat $1`: do this {input} times:
    + `z+=beep.`: append `beep.` to the variable `$z` (which implicitly starts empty)
* `repeat 4`:
    + `repeat x+=5,5`: do this 5 times, but also increment `$x` by `5` (it starts at `0` implicitly) before the loop starts:
        - `t+=x`: increment `$t` (the cumulative sum) by `$x` (again, `$t` starts at `0` implicitly)
        - `z[]=\` : set the `$t`th character (1-indexed) of `$z` to a space
* `${z//./}`: take `$z`, with dots `.` replaced by {empty string}
* `<<<`: print

# Answer
> 2 votes
# Haskell, 58 bytes

```
f n=do i<-[1..n];[' '|odd$div 0x888889249557c$2^i]++"beep"

```

Try it online!

# Answer
> 1 votes
# Perl 5, 54 bytes

```
$_=" beep"x$_;s/ /0x444444924aabe>>$x&$x++<51?$&:""/ge

```

Try it online!

Ungolfed a bit:

```
$_=" beep"x$_;           # create string of space+beep the input number of times
s/ /                     # remove spaces unless it's space number
0x444444924aabe          # 1 2 3 4 5 7 9 11 13 15 18 21 24 27 30
                         # 34 38 42 46 or 50 (counting from zero)
                         # 0x444444924aabe in binary have 1's on
                         # those positions
>>$x                     # keep space if 1-bit and space number <= 50
&$x++<51?$&:""/ge        # remove space if not

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 68 bytes

```
If[Accumulate@⌈Range@20/5⌉~FreeQ~#,"beep","beep "]&~Array~#<>""&

```

Try it online!

# Answer
> 1 votes
# Haskell, 99 bytes

```
f n=foldr(\i a->take i a++" "++(drop i a))(take(n*4)$cycle"beep")$scanl(+)4[(x`div`5)*4|x<-[6..19]]

```

Try it online!

`foldr(\i a->take i a++" "++(drop i a))` \- we fold accumulator inserting spaces at index from list.

`(take(n*4)$cycle"beep")` \- accumulator = string of n "beep"s

`$scanl(+)4[(x`div`5)*4|x<-[6..19]]` \- generates list of indexes where spaces should be inserted

# Answer
> 1 votes
# Pip, 33 bytes

```
(1Xa^@:{i+:a}M_X5MJ\,4)R1"beep"Js

```

Attempt This Online!

---
Tags: code-golf
---


title: Count the ways to transform (2)

text:
# Question
Title: Count the ways to transform (2)
Your input is a matrix (2d array) of positive integers. For example:

\begin{matrix} 1 & 1 & 4 & 7\\ 1 & 3 & 5 & 6\\ 2 & 1 & 4 & 5 \\ \end{matrix}

A semi-continuous transformation of this matrix is a rearranging of elements that preserves immediate neighbors. For example, we can swap the \\$2\\$ in the bottom left, and the \\$1\\$ in the top left corner.

\begin{matrix} 2 & 1 & 4 & 7\\ 1 & 3 & 5 & 6\\ 1 & 1 & 4 & 5 \\ \end{matrix}

This is fine, because every number has the same neighborhood counts. That is, we can make a sorted list of numbers and their neighbors, and verify the they are the same:

\begin{matrix} \text{Number} & \text{Neighbors} \\ 1 & 1,1 \\ 1 & 1,2,3 \\ 1 & 1,3,4 \\ 1 & 2,3,4 \\ 2 & 1,1 \\ 3 & 1,1,1,5 \\ 4 & 1,5,7 \\ 4 & 1,5,5 \\ 5 & 3,4,4,6 \\ 6 & 5,5,7 \\ 7 & 4,6 \end{matrix}

Here is another example.

\begin{matrix} 2 & 1 & 1\\ 1 & 3 & 1\\ 1 & 1 & 4\\ \end{matrix}

Let's make a neighbor list. Note that we are gonna have duplicate entries (which is fine)

\begin{matrix} \text{Number} & \text{Neighbors} \\ 1 & 1,1 \\ 1 & 1,1 \\ 1 & 1,2,3 \\ 1 & 1,2,3 \\ 1 & 1,3,4 \\ 1 & 1,3,4 \\ 2 & 1,1 \\ 3 & 1,1,1,1 \\ 4 & 1,1 \\ \end{matrix}

Now, can we swap the top left \\$2\\$ and the bottom left \\$1\\$? It may look fine at first glance, but we must be careful! By swapping those two elements we would create a \\$1\\$ which has neighbors \\$2,3,4\\$, which didn't exist in the first input.

Just to demonstrate, here is the matrix after this non-semi-continuous transformation:

\begin{matrix} 1 & 1 & 1\\ 1 & 3 & 1\\ 2 & 1 & 4\\ \end{matrix}

And here is the neighbor list:

\begin{matrix} \text{Number} & \text{Neighbors} \\ 1 & 1,1 \\ 1 & 1,1 \\ 1 & 1,1,3 \\ 1 & 1,2,3 \\ 1 & 1,3,4 \\ 1 & 2,3,4 \\ 2 & 1,1 \\ 3 & 1,1,1,1 \\ 4 & 1,1 \\ \end{matrix}

Which is has changed after the transformation, ergo the transformation is non-semi-continuous (on this input).

To clarify, semi-continuity is a property of a transformation on some specific matrix.

Your code will take a matrix as input and output the number of (unique) semi-continuous transformations. Two transformations are different if the output is different. So for example swapping two identical numbers is the same as the identity transform (doing nothing).

Or in other words: Your code will take a matrix and return the number of matrices with those dimensions that have the same neighbor-list.

You can assume that the matrix has positive width and height, and also that if m is the maximum number in the matrix, then the matrix contains all numbers 1 to m inclusive. Or alternatively you can assume that if m is the maximum number, then the matrix contains all numbers from 0 to m inclusive.

# Examples

```
[[1]] -> 1
[[1, 1], [1, 1]] -> 1
[[2, 1], [1, 2]] -> 2
[[2, 2], [1, 2]] -> 4
[[2, 1, 1], [1, 2, 1], [1, 1, 2]] -> 2
[[1, 1, 2, 1, 1, 1, 1]] -> 3
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 8
[[1, 1, 4, 7], [1, 3, 5, 6], [2, 1, 4, 5]] -> 8
[[2, 1, 1], [1, 3, 1], [1, 1, 4]] -> 4

```

# Answer
> 2 votes
# JavaScript, 205 bytes

```
m=>(a=m.flat(w=m[o=[c=0]].length),s=a=>0+[...a].sort(),g=a=>s(a.map((v,i)=>[v,s([a[i-w],a[i+w],i%w&&a[i-1],++i%w&&a[i]])])),h=b=>b[a.length-1]?o[s(b)==s(a)&g(b)==g(a)&&b]??=++c:a.map(v=>h([...b,v]))|c)([])

```

Don't try any matrix larger than 2x2. As its time complexity is at least \\$\Omega(wh^{wh+1})\\$.

```
m=>(
// counter of output
c=0,
// o as a dictionary, its key is any seen transform
o=[0],
// width of input
w=m[0].length
// convert input into 1d array
a=m.flat(w),
// sort array and convert it into a string
// we don't really care what order the sort works
// as long as it works consistent
s=a=>0+[...a].sort(),
// build the neighbor list of input flatten matrix
g=a=>s(a.map((v,i)=>[
// first item its the cell value itself
v,
// and followed by its neighbors, sorted in some order
s([a[i-w],a[i+w],i%w&&a[i-1],++i%w&&a[i]])
])),
// for each possible matrix with same size and use seen numbers
h=b=>b[a.length-1]?o[
// when sort the matrix, it uses same numbers as input
s(b)==s(a)&
// its neighbor list is same as input
g(b)==g(a)&&
// if above 2 condition meets, we find out a new transform
// we use o[b] to verify if the transform we have ever seen or not
// otherwise, the expression is 0, while o[0] is initialized
b]??=
// increase the counter whenever we find out a new transform
++c:
a.map(v=>h([...b,v]))|c)([])

```

# Answer
> 1 votes
# Python3, 1075 bytes:

```
from copy import*
from itertools import*
R=range
c=lambda x:[(j,k)for j in R(len(x))for k in R(len(x[0]))]
def n(b):
 Q={}
 for x,y in c(b):
  q=[]
  for J,K in[(0,-1),(0,1),(1,0),(-1,0)]:
   if(j:=x+J)>=0 and(k:=y+K)>=0:
    try:q+=[b[j][k]]
    except:1
  Q[b[x][y]]=Q.get(b[x][y],[])+[sorted(q)]
 return Q
v=lambda B,N:all(all(i in N[q]for i in p)for q,p in n(B).items())
def u(b,x,y,j,I):
 q=[]
 for J,K in[(0,-1),(0,1),(1,0),(-1,0)]:
  if(j:=x+J)>=0 and(k:=y+K)>=0:
   try:q+=[(b[j][k],(j,k))]
   except:1
 if len(q)!=len(I):return 0
 for s,(_,(j,k))in zip(I,q):
  if b[j][k] and b[j][k]!=s:return 0
  b[j][k]=s
 return b
F=lambda x:[*chain(*x)]
def r(W,b,n):
 q,S=[b],[b]
 while q:
  if all(map(all,b:=q.pop(0))):yield b;continue
  for x,y in c(b):
   if not b[x][y]:
    for j,k in n.items():
     for i in k:
      for I in permutations(i,len(i)):
       B=deepcopy(b)
       B[x][y]=j
       if(B:=u(B,x,y,j,I))and B not in S and all(F(B).count(O)<=F(W).count(O)for O in n):q+=[B];S+=[B];break
f=lambda b:sum(v(i,n(b))for i in r(b,[[0 for _ in i]for i in b],n(b)))

```

Try it online!

The main strategy is to produce possible transformations and then count the number of valid results.

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


title: BigNum Bakeoff Reboot

text:
# Question
Title: BigNum Bakeoff Reboot
Some of you may be familiar with the BigNum Bakeoff, which ended up quite interestingly. The goal can more or less be summarized as writing a C program who's output would be the largest, under some constraints and theoretical conditions e.g. a computer that could run the program.

In the same spirit, I'm posing a similar challenge open to all languages. The conditions are:

* **Maximum 512 bytes**.
* Final result must be printed to STDOUT. This is your score. If multiple integers are printed, they will be concatenated.
* Output must be an integer. (Note: **Infinity is not an integer**.)
* No built-in constants larger than 10, but numerals/digits are fine (e.g. Avogadro's constant (as a built-in constant) is invalid, but 10000 isn't.)
* The program **must terminate** when provided sufficient resources to be run.
* The printed output must be **deterministic** when provided sufficient resources to be run.
* You are provided large enough integers or bigints for your program to run. For example, if your program requires applying basic operations to numbers smaller than 101,000,000, then you may assume the computer running this can handle numbers at least up to 101,000,000. (Note: Your program may also be run on a computer that handles numbers up to 102,000,000, so simply calling on the maximum integer the computer can handle will not result in deterministic results.)
* You are provided enough computing power for your program to finish executing in under 5 seconds. (So don't worry if your program has been running for an hour on your computer and isn't going to finish anytime soon.)
* No external resources, so don't think about importing that Ackermann function unless it's a built-in.

All magical items are being temporarily borrowed from a generous deity.

## Extremely large with unknown limit

where B³F is the Church-Kleene ordinal with the fundamental sequence of

```
B³F[n] = B³F(n), the Busy Beaver BrainF*** variant
B³F[x] = x, ω ≤ x < B³F

```

## Leaderboard:

1. *Simply Beautiful Art*, Ruby fψ0(X(ΩM+X(ΩM+1ΩM+1)))+29(999)
2. *Binary198*, Python 3 fψ0Ωω+1)+1(3) (there was previously an error but it was fixed)
3. *Steven H*, Pyth fψ(ΩΩ)+ω²+183(25627!)
4. *Leaky Nun*, Python 3 fε0(999)
5. *fejfo*, Python 3 fωω6(fωω5(9e999))
6. *Steven H*, Python 3 fωω+ω²(99999)
7. *Simply Beautiful Art*, Ruby fω+35(9999)
8. *i..*, Python 2, f3(f3(141))

## Some side notes:

If we can't verify your score, we can't put it on the leaderboard. So you may want to expect explaining your program a bit.

Likewise, if you don't understand how large your number is, explain your program and we'll try to work it out.

If you use a Loader's number type of program, I'll place you in a separate category called **"Extremely large with unknown limit"**, since Loader's number doesn't have a non-trivial upper bound in terms of the fast growing hierarchy for 'standard' fundamental sequences.

Numbers will be ranked via the fast-growing hierarchy.

For those who would like to learn how to use the fast growing hierarchy to approximate really large numbers, I'm hosting a Discord server just for that. There's also a chat room: Ordinality.

Similar challenges:

Largest Number Printable

Golf a number bigger than TREE(3)

Shortest terminating program whose output size exceeds Graham's number

For those who want to see some simple programs that output the fast growing hierarchy for small values, here they are:

### Ruby: fast growing hierarchy

```
#f_0:
f=->n{n+=1}

#f_1:
f=->n{n.times{n+=1};n}

#f_2:
f=->n{n.times{n.times{n+=1}};n}

#f_3:
f=->n{n.times{n.times{n.times{n+=1}}};n}

#f_ω:
f=->n{eval("n.times{"*n+"n+=1"+"}"*n);n}

#f_(ω+1):
f=->n{n.times{eval("n.times{"*n+"n+=1"+"}"*n)};n}

#f_(ω+2):
f=->n{n.times{n.times{eval("n.times{"*n+"n+=1"+"}"*n)}};n}

#f_(ω+3):
f=->n{n.times{n.times{n.times{eval("n.times{"*n+"n+=1"+"}"*n)}}};n}

#f_(ω∙2) = f_(ω+ω):
f=->n{eval("n.times{"*n+"eval(\"n.times{\"*n+\"n+=1\"+\"}\"*n)"+"}"*n);n}

```

etc.

To go from `f_x` to `f_(x+1)`, we add one loop of the `n.times{...}`.

Otherwise, we're diagonalizing against all the previous e.g.

```
f_ω(1) = f_1(1)
f_ω(2) = f_2(2)
f_ω(3) = f_3(3)

f_(ω+ω)(1) = f_(ω+1)(1)
f_(ω+ω)(2) = f_(ω+2)(2)
f_(ω+ω)(3) = f_(ω+3)(3)

```

etc.

# Answer
> 8 votes
# Ruby, fψ0(X(ΩM+X(ΩM+1ΩM+1)))+29(999)

where **M** is the first Mahlo 'ordinal', **X** is the chi function (Mahlo collapsing function), and **ψ** is the ordinal collapsing function.

```
f=->a,n,b=a,q=n{c,d,e=a;!c ?[q]:a==c ?a-1:e==0||e&&d==0?c:e ?[[c,d,f[e,n,b,q]],f[d,n,b,q],c]:n<1?9:!d ?[f[b,n-1],c]:c==0?n:[t=[f[c,n],d],n,c==-1?[]:d==0?n:[f[d,n,b,t]]]};(x=9**9**9).times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{x.times{h=[];x.times{h=[h,h,h]};h=[[-1,1,[h]]];h=f[h,p x*=x]until h!=0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

```

Try it online!

### Code Breakdown:

```
f=->a,n,b=a,q=n{          # Declare function
                c,d,e=a;          # If a is an integer, c=a and d,e=nil. If a is an array, a=[c,d,e].compact, and c,d,e will become nil if there aren't enough elements in a (e.g. a=[1] #=> c=1,d=e=nil).
                        !c ?[q]:          # If c is nil, return [q], else
                                a==c ?a-1:          # If a==c, return a-1, else
                                          e==0||e&&d==0?c:          # If e==0 or e is not nil and d==0, return c, else
                                                          e ?[[c,d,f[e,n,b,q]],f[d,n,b,q],c]:          # If e is not nil, return an array inside an array, else
                                                                                n<1?9:          # If n<1, return 9, else
                                                                                !d ?[f[b,n-1],c]:          # If d is nil, return [f[b,n-1],c], else
                                                                                c==0?n:          # If c==0, return n, else
                                                                                [t=[f[c,n],d],n,c==-1?[]:d==0?n:[f[d,n,b,t]]]          # t=[f[c,n],d]. If c==-1, return [t,n,[]], else if d==0, return [t,n,n], else return [t,n,[f[d,n,b,t]]].
                                                                                };          # End of function
                                                                                (x=9**9**9)          # Declare x
                                                                                x.times{...}          # Looped within 33 x.times{...} loops
                                                                                h=[];          # Declare h
                                                                                x.times{h=[h,h,h]};          # Nest h=[h,h,h] x times
                                                                                h=f[h,p x*=x]          # Apply x*=x, print x, then h=f[h,x]
                                                                                until h==0          # Repeat previous line until h==0

```

### Math Breakdown:

`f` reduces `a` based on `n,b,q`.

The basic idea is to have an extremely nested `a` and reduce it repeatedly until it reduces down to `a=0`. For simplicity, let

```
g[0,n]=n
g[a,n]=g[f[a,n],n+1]

```

For now, let's only worry about `n`.

For any integer `k`, we get `f[k,n]=k-1`, so we can see that

```
g[k,n]=n+k

```

We then have, for any `d`, `f[[0,d],n]=n`, so we can see that

```
g[[0,d],n]
= g[f[[0,d],n],n+1]
= g[n,n+1]
= n+n+1

```

We then have, for any `c,d,e`, `f[[c,0,e],n]=f[[c,d,0],n]=c`. For example,

```
g[[[0,d],0,e],n]
= g[f[[[0,d],0,e]],n+1]
= g[[0,d],n+1]
= (n+1)+(n+1)+1
= 2n+3

```

We then have, for any `c,d,e` such that it does not fall into the previous case, `f[[c,d,e],n]=[[c,d,f[e,n]],f[d,n],e]`. This is where it starts to get complicated. A few examples:

```
g[[[0,d],1,1],n]
= g[f[[[0,d],1,1],n],n+1]
= g[[[0,d],1,0],0,[0,d]],n+1]
= g[f[[[0,d],1,0],0,[0,d]],n+1],n+2]
= g[[[0,d],1,0],n+2]
= g[f[[[0,d],1,0],n+2],n+3]
= g[[0,d],n+3]
= (n+3)+(n+3)+1
= 2n+7

#=> Generally g[[[0,d],1,k],n] = 2n+4k+3

g[[[0,d],2,1],n]
= g[f[[[0,d],2,1],n],n+1]
= g[[[[0,d],2,0],1,[0,d]],n+1]
= g[f[[[[0,d],2,0],1,[0,d]],n+1],n+2]
= g[[[[[0,d],2,0],1,n+1],0,[[0,d],2,0]]],n+2]
= g[f[[[[[0,d],2,0],1,n+1],0,[[0,d],2,0]]],n+2],n+3]
= g[[[[0,d],2,0],1,n+1],n+3]
= ...
= g[[[0,d],2,0],3n+6]
= g[f[[[0,d],2,0],2n+6],3n+7]
= g[[0,d],3n+7]
= (3n+7)+(3n+7)+1
= 6n+15

```

It quickly ramps up from there. Some points of interest:

```
g[[[0,d],3,[0,d]],n] ≈ Ack(n,n), the Ackermann function
g[[[0,d],3,[[0,d],0,0]],63] ≈ Graham's number
g[[[0,d],5,[0,d]],n] ≈ G(2^^n), where 2^^n = n applications of 2^x, and G(x) is the length of the Goodstein sequence starting at x.

```

Eventually introducing more arguments of the `f` function as well as more cases for the array allows us to surpass most named computable notations. Some particularly known ones:

```
g[[[0],3,[0,d]],n] ≈ tree(n), the weak tree function
g[[[[0],3,[0,d]],2,[0,d]],n] ≈ TREE(n), the more well-known TREE function
g[[[[0,d]],5,[0,d]],n] >≈ SCG(n), sub-cubic graph numbers
g[[[0]],n] ≈ S(n), Chris Bird's S function

```

# Answer
> 3 votes
# Pyth, fψ(ΩΩ)+ω2+183(~25627!)

```
=QC`.pGL&=^QQ?+Ibt]0?htb?eb[Xb2yeby@b1hb)hbXb2yeb@,tb&bQ<b1=Y_1VQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQVQ.v%%Fms["*s[.v"*\\^2d"\"%s"*\\^2d"\"")Qs["=Y.v+*"*\\^2Q"\"*3]"*\\^2Q"\"Q\YuyFYHpQ)

```

Requires any non-empty input, but the value thereof is not used.

Explanation (for the *new and actually-reasonably-scoring* version):

```
=QC`.pG                   Sets the value of the autofill variable to app. 256^27!
                                  27! ~= the number of characters in the string
                                  containing all permutations of the alphabet.
                                  We interpret that string as a base-256 number.
       L                  Define a function y(b,global Q):
        &=^QQ             Set Q to Q^Q and:
        ?+Ibt]0           If (?) the variable (b) is (I)nvariant on (+)adding itself
                             to the empty array (i.e. if it's an array itself):
               ?htb        If the second element of b is not 0:
                   ?eb         If the last element is not 0
                       [Xb2yeby@b1hG)   return [b with its last element replaced with y(b[-1]), y(b[1]), b[0]]
                     hb                 else return b[0]
                 Xb2yeb     else return b with its last element replaced with y(b[-1])
           @,tb&bQ<b1      If b isn't an array,return:
                               either b-1 if it's a standard ordinal (1 or more)
                               or Q if b is ω
                               or 0 if b is 0
 =Y_1                          Set the global variable Y to -1 (representing ω)
 VQ                        Q times, do (the rest of the explanation):
  VQVQ....VQ               Iterate from 0 to Q-1 183 times, each subiteration
                              reading the most recent value of Q when it starts:
  .v%%Fms["*s[.v"*\\^2d"\"%s"*\\^2d"\"")Q
                            Iterate from 0 to Q-1 Q times, each subiteration
                               reading the most recent value of Q when it starts:
 s["=Y.v+*"*\\^2Q"\"*3]"*\\^2Q"\"Q
                             Y = [Y,Y,Y] Q times, stacking with previous iterations.
 uyFYHpQ)                    Run y_x(Y) for x incrementing until y_(x-1)(Y)=0

```

It's very hard for me to compute the size of this, mostly because ~~it's late in the day and I'm not super familiar with fast-growing hierarchies or how I'd even go about trying to figure out how many times Q goes through the `y()` wringer.~~ While I now know more about ordinals, I still have no idea how to calculate the value of the ordinal represented by the recursive definition in my program. I'd join the Discord server, but that's under a pseudonym I'd rather not be linked to my real name.

~~Unfortunately, because I know relatively little about said fast-growing hierarchies, I'm likely to have already lost to the Ruby answer. It's hard for me to tell.~~ ~~I may have beaten the Ruby answer, but I'm not 100% sure.~~ ¯\\\_(ツ)\_/¯

# Answer
> 3 votes
# Pyth, f3+σ-12(25626)

Where σm\[n\] is the Busy Beaver function Σ of order `m` called on `n`: σm\[n\] = Σm(n). The order `-1` is to denote that the Busy Beaver here is not being called on a true Turing Machine, but rather an approximation with a finite wrapping tape of `Q` elements. This allows the halting problem to be solvable for these programs.

```
=QCGM.x-Hlhf!-/T4/T5.__<GH0M.x+Hlhf!-/T4/T5._>GHlGL=.<QC`m.uX@[XN2%h@N2l@N1XN2%t@N2l@N1XN1X@N1@N2%h@@N1@N2l@N1XN1X@N1@N2%t@@N1@N2l@N1XW!@@N1@N2N2nFKtPNXW@@N1@N2N2gFK)@hNeN3%heNlhNd)bLym*F[]d^UQQUQUld)^U6QJ"s*].v*\mQ"
.v+PPPP*JQ"+*\mQ\'

```

The TL;DR is that this creates all possible BrainF\**k programs of length Q, runs them in an environment where the maximum value of an integer is Q and the tape length is Q, and compiles all the states from these operations together to append (that's the `3+`) to Q, repeating the above on a scale of fω2.

I still have ~half the characters to work with if I wanted to do something more, but until we figure out where this is I'll just leave it as is.

# Answer
> 3 votes
# Python 3, probably fε0(99) I have no idea

```
def f(n,d,a,i):
 if d < 0 or i >= len(a):
  return n

 k = a[i]
 if type(k) == int:
  if k < 0:
   a[i] = [-2]*n
   a = f(n,d,a,i+k+2)
  else:
   a[i] -= 1
 else:
  a[i] = f(n,d-1,k,0)
 return a

def g(n):
 d=n
 a=[-2]*n
 while type(a) != int:
  a = f(n,d,a,0)
  n += 1

print(g(99))

```

*Edit: Accidentally left d=2 from the slower-growing format, fixed and it's now d=n.*

Try it online!

First, this is my first CGSE post (and my first SE post in general) so this definitely looks weird. Second, I'm not sure it's fε0(99) I have no idea what this is. Third, I did no golfing on this, just trying to get something out there that I can understand (and build upon in later edits). I consider this to be "v0.1",

## Equivalent equation

Fourth, I'm not sure that g(n) grows at fε0. I sent it to the mathematics stackex discord, and ended up making an approximation of this program.

\\$g(n) = f(n,n,\\{-2,-2,\cdots\ n\ times\\},0)\\a=\\{a\_0,a\_1,\cdots a\_k\\}\\$

\\$f(n,d,a,i) =\left\\{ \begin{array}{cl} n & : \ d \< 0 \\ n & : \ i \> k\\ f(n,d,\\{a\_0,\cdots a\_{i-1},\\{-2,-2,-2,\cdots n\ times\\},a\_{i+1}\cdots a\_k \\},i+k+2) & : \ a\_i \in \mathbb{Z}\ \cap\ a\_i\<0\\ f(n+1,d-1,\\{a\_0\cdots a\_{i-1},a\_i-1,a\_{i+1},\cdots a\_k\\},0) & : \ a\_i \in \mathbb{Z}\ \cap\ a\_i\geq 0 \\ \\{a\_0,a\_1\cdots a\_{i-1},f(n,d-1,a\_i,0),a\_{i+1},\cdots a\_k\\}&:\ a\_i\notin\mathbb{Z} \end{array} \right.\\$

If f(n,d,a,i) is cutting off on the side of the screen, then use these links to an image of the equation, both with a White background and with a Discord Dark Mode background.

## Slower growing formats

Lastly, while testing it, to make sure it worked, I made a version that grows significantly slower.

Slower growing function. For this, it increments an unrelated *q* variable instead of incrementing *n* directly, then outputs q. With n=2 and d=2, it outputs 714025. With n=3 and d=2 or n=2 and d=3, tio.run gives me a "Program has exceeded the 60 second time limit."

```
def f(n,d,a,i):
 if d < 0 or i >= len(a):
  return n

 k = a[i]
 if type(k) == int:
  if k < 0:
   a[i] = [-2]*n
   a = f(n,d,a,i+k+2)
  else:
   a[i] -= 1
 else:
  a[i] = f(n,d-1,k,0)
 return a

n=3
d=2
a=[-2]*n
q=0

while type(a) != int:
 a = f(n,d,a,0)
 q += 1

print(q)

```

# Answer
> 3 votes
# Python 3, Greater than fSVO(Z)≈fψ0Ωω)(Z)

# Where Z = (...((9^9)^(9^9))^((9^9)^(9^9))...) with about 9^9 parenthesis

```
def R(a,n):
    if type(a)==int:return a-1
    if n<1:return 0
    if not a:return n
    if a[-1]==0:return a[:-1]
    if a[0]!=0:a[0]=R(a[0],n);return a
    i=0
    while a[i]==0:i+=1
    a[i-1]=R(a[:],n-1);a[i]=R(a[i],n);return a
def G(a,n,m=0):
    A='\t'
    if a==0:return n+1
    if m:
        prgm='';b=G(a,n)
        for i in range(b):prgm+=A*i+'for _ in range(n):\n'
        prgm+=A*b+'n=G(R(a,n),n,m-1)';exec(prgm)
    m=0
    if type(a)==list:m=n
    for i in range(n):n=G(R(a,n),n,m)
    return n+1
z=Z=9**9
for i in range(z):Z=Z**Z
Z=G([Z]*Z,Z)
print(Z)

```

I wrote this mess a while back but didn't upload it because I was thinking I should just go for First Place Or Bust. Turns out: First Place is hard. So here's my 4th place submission.

Ungolfed program: https://github.com/cpaca/BignumReboot/blob/main/VeblenMethod.py

Website to minify a python program: https://python-minifier.com/

Unfortunately, because I wrote it so long ago, **I've forgotten most of what I wrote.** I remembered what my goal was, I remembered finishing it, but I don't remember the mathematics behind the mess very well. The ungolfed program has comments (lots of them, actually, looking at it) but there are a *few* hints that I do remember:

---

G(a,n,m) accepts either a list, int, int *or* an int, int, int. If the last variable isn't given, it's defaulted to 0.

All integers are positive. Negative integers should be inaccessible.

G(a,n,0) for int, int, 0 should be equivalent to fa(n) under the fast growing hierarchy. This evidently isn't the case, as it's calculating G(1,1) = 3, G(1,2) = 5, G(1,5) = 11, G(2,2) = 12. (Best guess, it's actually f0(fa(n)) but I can't really confirm.)

G(\[\],n,0) - in other words, for empty list - should be equivalent to G(n,n,0)

R(a,n) is φ(a)\[n\] under the Veblen hierarchy.

G(a,n,0) should be greater than fφ(a)(n), where φ is the veblen function.

However, there is one thing that could make this function less than what I expect. In the analysis of the FGH, and the Veblen function, I made one assumption which MIGHT not be true:

$$f\_{\alpha+\beta}(n) \< f\_{\alpha+f\_\beta(n)}(n)$$

# Answer
> 2 votes
# python, f3(f3(141)), 512 bytes

```
import math
def f(x):
    return math.factorial(x)
x=9
for j in range(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(x))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))):
    x=f(x)
print x

```

This isn't really a valid answer, but I wanted to post it anyway. A quick rundown:

```
import math # imports the factorial function
def f(x):
    return math.factorial(x) # shortens the factorial operation
x=9 # sets x to highest available number
for j in range(f(...f(x)...)): # repeats * A LOT *
    x=f(x) # does the factorial of x
print x # outputs the result

```

Anyway, I don't know if this answer technically legal, but it was fun to write. Feel free to edit any errors you find in the code.

# Answer
> 1 votes
# Ruby, probably ~ fω+35(9999)

```
G=->n,k{n<1?k:(f=->b,c,d{x=[]
c<G[b,d]?b-=1:(x<<=b;c-=G[b,d])while c>=d
x<<[c]}
x=f[n-1,k,b=1]
(b+=1;*u,v=x;x=v==[0]?u:v==[*v]?u<<[v[0]-1]:u+f[n-1,G[v,b]-1,b])while x[0]
b)};(n=9**9**99).times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n.times{n=G[n,n]}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}};p n

```

Try it online!

### Approximate Math Explanation:

The below is approximately equal to the program above, but simplified so that its easier to understand.

`G(0,k) = k` is our base function.

To evaluate `G(n,k)`, we take `k` and write it as `G(n-1,1) + ... + G(n-2,1) + ... + G(0,1)`.

Then change all of the `G(x,1)`'s into `G(x,2)`'s and subtract `1` from the entire result.

Rewrite it in the above form using `G(x,2)`, where `x<n`, and leave the remainder at the end. Repeat, changing `G(x,2)` to `G(x,3)`, etc.

When the result reaches `-1`, return the base (the `b` that would be in `G(x,b)`.)

## Examples:

### G(1,1):

```
1: 1 = G(0,1)
2: G(0,2) - 1 = 1
3: 1 - 1 = 0
4: 0 - 1 = -1      <----- G(1,1) = 4

```

### G(1,2):

```
1: 2 = G(0,1) + G(0,1)
2: G(0,2) + G(0,2) - 1 = G(0,2) + 1
3: G(0,3) + 1 - 1 = G(0,3)
4: G(0,4) - 1 = 3
5: 3 - 1 = 2
6: 2 - 1 = 1
7: 1 - 1 = 0
8: 0 - 1 = -1      <----- G(1,2) = 8

```

### G(1,3):

```
1: 3 = G(0,1) + G(0,1) + G(0,1)
2: G(0,2) + G(0,2) + G(0,2) - 1 = G(0,2) + G(0,2) + 1
3: G(0,3) + G(0,3)
4: G(0,4) + 3
5: G(0,5) + 2
6: G(0,6) + 1
7: G(0,7)
8: 7
9: 6
10:5
11:4
12:3
13:2
14:1
15:0
16:-1      <----- G(1,3) = 16

```

### G(2,5):

```
1: 5 = G(1,1) + G(0,1)
2: G(1,2) + 1
3: G(1,3)
4: G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + G(0,4) + 3
5: G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + G(0,5) + 2
6: G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + G(0,6) + 1
...
1024: -1      <----- G(2,5) = 1024

```

Doing some math, I found that

```
G(1,n-1) = 2ⁿ
G(2,n+6) ~ 2^G(2,n),  large enough n.

```

And beyond that it tends to get a bit hairy.

In general, we have

```
G(n,k+G(n-1,1)) ~ G(n-1,G(n,k)), large enough n.

```

# Answer
> 1 votes
# Python 3, fωω+ω\*ω(99999)

```
from functools import*
h=lambda a,x,b:h(h(a,x,b-1),x-1,a)if x*b else a+b
def f(*x):
    if(any(x[:2]):return reduce(lambda y,z:h(z,y,f(x[0],x[1]-1,*x[2:])),x[::-1])if x[0]*x[1]else(f(x[0]-1,f(x[0]-1,x[0],*x[2:]))if x[0]>x[1]else(f(x[1]-1,f(*([x[1]-1]*2+x[2:])),*x[2:])))
    for a,k in enumerate(x):if k:return f(*[f(*[k]*a,k-1,*x[a+1:])]*a,k-1,*x[a+1:])
    return 0
x,s,g,e,r,z=9**9**9**99,"f(*[%s]*%s)",lambda a,b:a%((b,)*a.count("%")),"x*=eval(\"%s\");","x","x=g(e,g(reduce(g,[s]*x,s),r));"
print(exec(z*x)or eval(r))

```

I'll get an explanation up soon.

# Answer
> 1 votes
# Python 3, ~ fε0(999)

```
N=9**9**9
def f(a,n):
 if a[0]==[]:return a[1:]
 if a[0][0]==[]:return[a[0][1:]]*n+a[1:]
 return [f(a[0],n)]+a[1:]
a=eval("["*N+"]"*N)
n=2
while a:a=f(a,n);n+=1
print(n)

```

Try it online!

# Answer
> 1 votes
# Python 3, 323 bytes, g9e9(9)

```
exec("""a=`x:9**x
n=`a,f:`x:a and n(a-1,f)(f(x))or x
c=`n:`l:l[~n](l)
e=`x:n(x,c(0))([x,`l:[a(l[0]),n(*l)],c(0),`l:[a(l[0]),l[2](l[:2])[1]]+map(`i:l[1]((l[0],i))[1],l[2:])]+list(map(c,range(a(x),1,-1))))[1]
f=`l:[l[1](l[0]),e(l[1](l[0]))(l)[1]]
g=`x:e(x)((x,f))[1]((x,a))[1](x)
print(n(9e9,g)(9))""".replace('`','lambda '))

```

Try it online!

## Explanation

Python 3 is a truly recursive language, this means that not only can a function call itself, a function can also take other functions as input or output functions. Using functions to make themselves better is what my program is based on.

f=lambda x,a:\[a(x),e(x)((x,a))\[1\]\]

### Definition

```
a(x)=9^x
b(x,f)=a(x), f^x
c(n)(*l)=l[~n](l)
c(0)=c0 <=> c0(…,f)=f(…,f)
d(x,b,c,*l)=a(x), c0(x,b), b(x,c0), b(x,f) for f in l
e(x)=c0^x(x,b,c0,d,c(a(x)),c(a(x)-1),c(a(x)-2),…,c(3),c(2),c(1))[1]
f(x,a)=a(x),e(a(x))(x,a)[1](x)
g(x)=e(x)(x,f)[1](x,a)[1](x)
myNumber=g^9e9(9)

```

### Definition explained

`a(x)=9^x` a is the base function, I chose this function because x\>0=\>a(x)\>x\` which avoids fixed points.

`b(x,f)=a(x), f^x` b is the general improving function, it takes in any function and outputs a better version of it. b can even be applied to itself: `b(x,b)[1]=b^x` `b(x,b^x)[1]=b^(x*x)`

but to fully use the power of `b` to improve `b` you need to take the output of b and use it as the new b, this is what c0 does:

`c0(…,f)=f(…,f)`
`c0(x,b^x)=b^x(x,b^x)[1]>b^(9↑↑x)`

the more general c(n) function takes the n last argument (starting from 0) so `c(1)(…,f,a)=f(…,f,a)` and `c(2)(…,f,a,b)=f(…,f,a,b)`. `*l` means l is an array and `l[~n]` takes the n last argument

`d(x,b,c,*l)=a(x), c0(x,b), b(x,c0), b(x,f) for f in l` d uses c0 to upgrade b and b to upgrade all of the other input functions (of which there can be any amount because of the list)
`d(x,b,c,d)>9^x,b^x,c^x,d^x` and `d²(x,b,c,d)>a²(x), b^(9↑↑x), c^(9↑↑x), d^(9↑↑x)`

but d gets even better if you combine it with c:
`c0²(x,b,c0,d)=d^x(9^x,b^x,c0^x,d^x)=…` `c0(x,b,c0,d,c1)=c1(x,b,c0,d,c1)=d(x,b,c0,d,c1)=9^x,b^x,c0^x,d^x,c1^x` `c0²(x,b,c0,d,c1)=c0(9^x,b^x,c0^x,d^x,c1^x)=c1^x(9^x,b^x,c0^x,d^x,c1^x)=…`

the more c(x) you add at the end the more powerful it becomes. The first c0 always remains d: `c0(x,b,c0,d,c4,c3,c2,c1)=c1(…)=c2(…)=c3(…)=c4(…)=d(x,b,c0,d,cX,cX-1,…,c3,c2,c1)=…`
But the second leaves iterated versions behind:

```
c0²(x+1,b,c0,d,c4,c3,c2,c1)
=c0(9^x+1,b^x+1,c0^x+1,d^x+1,c4^x+1,c3^x+1,c2^x+1,c1^x+1)
=c1^x(c2^x(c3^x(c4^x(d^x(9^x+1,b^x+1,c0^x+1,d^x+1,c4^x+1,c3^x+1,c2^x+1,c1^x+1)))))

```

When `d^x` is finally calculated `c4` will take a much more iterated version of `d` the next time. When `c4^x` is finally calculated `c3` will take a much more iterated version of `c4`,…
This creates a really powerful version of iteration because `d`:

1. Improves `b` using `c0`
2. Improves `c0` using `b`
3. Improves all the layers of nesting using `b` The improves themselves improve, this means d becomes more powerful when it is iterated more.

Creating this long chain of c is what what `e(x)=c0^x(x,b,c0,d,c(a(x)),c(a(x)-1),c(a(x)-2),…,c(3),c(2),c(1))[1]` does.
It uses `c0^x` to bypass that `c0` would just give `d`.
The `[1]` means that it will eventually return the second output of `d^…`. So `b^…`.

At this point I couldn't think of any thing to do with e(x) to significantly increase it's output except increasing input.

So `f(x,a)=a(x),e(a(x))(x,a)[1](x)` uses the `b^…` generated by `e(x)` to output a better base function and uses that base function to call `e(x)` with a bigger input.

`g(x)=e(x)(x,f)[1](x,a)[1](x)` uses a final `e(x)` to nest `f` and produces a really powerful function.

### Fgh approximation

I will need help approximating this number with any sort of fgh.

**Old version**: fωω6(fωω5 (9e999)), Try it online! Revision history of explanation

# Answer
> 1 votes
# Ruby, fε02(5), 271 bytes

```
m=->n{x="";(0..n).map{|k|x+="->f#{k}{"};x+="->k{"+"y=#{n<1??k:"f1"};k.times{y=f0[y]};y";(2..n).map{|l|x+="[f#{l}]"};eval x+(n<1?"":"[k]")+"}"*(n+2)}
g=->z{t="m[#{z}]";(0...z).map{|j|t+="[m[#{z-j-1}]]"};eval t+"[->n{n+n}][#{z}]"}
p m[5][m[4]][m[3]][m[2]][m[1]][m[0]][g][6]

```

Try it online!

This is based off of the m(n) map.

## Explanation:

`m[0][f0][k] = f0[f0[...f0[k]...]]` with `k` iterations of `f0`.

`m[1][f0][f1][k] = f0[f0[...f0[f1]...]][k]` with `k` iterations of `f0`.

`m[2][f0][f1][f2][k] = f0[f0[...f0[f1]...]][f2][k]` with `k` iterations of `f0`.

In general, `m[n]` takes in `n+2` arguments, iterates the first argument, `f0`, `k` times onto the second argument, and then applies the resulting function onto the third argument (if it exists), then applies the resulting function onto the fourth argument (if it exists), etc.

### Examples

`m[0][n↦n+1][3] = (((3+1)+1)+1 = 6`

In general, `m[0][n↦n+1] = n↦2n`.

`m[0][m[0][n↦n+1]][3] = m[0][n↦2n][3] = 2(2(2(3))) = 24`

In general, `m[0][m[0][n↦n+1]] = n↦n*2^n`.

```
m[1][m[0]][3]
= m[0][m[0][m[0][n↦n+1]]][3]
= m[0][m[0][n↦2n]][3]
= m[0][n↦n*2^n][3]
= (n↦n*2^n)[(n↦n*2^n)[n↦n*2^n(3)]]
= (n↦n*2^n)[(n↦n*2^n)[24]]
= (n↦n*2^n)[402653184]
= 402653184*2^402653184

```

In general, `m[1][m[0]][n↦n+1] = f_ω` in the fast-growing hierarchy.

---

```
g[z] = m[z][m[z-1]][m[z-2]]...[m[1]][m[0]][n↦2n][z]

```

and the final output being

```
m[5][m[4]][m[3]][m[2]][m[1]][m[0]][g][6]

```

# Answer
> 1 votes
# Python 2, 181 bytes

```
def B(s):
 D=range(1,s);B=[[A]for A in D]+[[0]]
 for C in B[::-1]:
  for F in D:C+=[B[C[-1]][C[0]]]
 A=1;E=B[0]
 while s//A*E[:A]!=E:A*=2
 return A
A=0
while B(2**A)<99:A+=1
print A

```

Try it online!

Much, much larger than Loader’s number. It is well defined.

Nothing new. This is known as the Inverse Laver function.

# Answer
> 0 votes
# Javascript, 483 bytes

So, I'm just reusing a program I wrote for "Golf a number bigger than TREE(3)". The program results in \\$f\_{TFBO+1}(3) = f\_{TFBO}(f\_{TFBO}(f\_{TFBO}(3)))\\$ in the fast-growing hierarchy (3rd place), where \\${TFBO}\\$ is the Takeuti-Feferman-Buchholz Ordinal \\$\psi(\Omega\_{\omega+1})\\$. It uses Buchholz hydras and implements the BH function. Here is my compressed code, which was done with Naruyoko's Javascript compressor:

```
_="69{%t.length-1D*6m#{%B]}*6s#{t.splice(m#,14*@n=1;*6e#{7==0/s#;if(9>1/$i=0;i<n;i:t'B-1]4}}7>0&&typeof t==\"number\"/$i=98t[i]<m#8i--/}@s;$j5i8j <= 98j:s't[j]4@?5s;?[j]=?[i]-1;?[l(?)]=0;s#;$k508k <= l(?)8k:t'?[k]4}7==A/B]=n+1Dn += 1;%tD*6b(k/i5[\"+\",0];$l508l < k-28l:i'A)}while(l(i)>=0/i=e(i4%nD*Console.log(b(b(b(3))));#(t)$for(let %return '.push(*\n    /){4)D5 = 6function 7if(m#8; 9l#:++/?sa@var A\"w\"Bt[9D;}";for($ of"DBA@?:987654/*'%$#")with(_.split($))_=join(pop());eval(_)

```

This is basically incomprehensible, with only fragments of the original code revealing themselves, so here is the original code:

```
function l(t){return t.length-1;}
function m(t){return t[l(t)]}
function s(t){t.splice(m(t),1);}
var n=1;
function e(t){if(m(t)==0){s(t);if(l(t)>1){for(let i=0;i<n;i++){t.push(t[l(t)-1]);}}}if(m(t)>0&&typeof t=="number"){for(let i=l(t); t[i]<m(t); i--){}var s;for(let j = i; j <= l(t); j++){s.push(t[j]);}var sa = s;sa[j]=sa[i]-1;sa[l(sa)]=0;s(t);for(let k = 0; k <= l(sa); k++){t.push(sa[k]);}}if(m(t)=="w"){t[l(t)]=n+1;}n += 1;return t;}
function b(k){i = ["+",0];for(let l = 0; l < k-2; l++){i.push("w")}while(l(i)>=0){i=e(i);}return n;}
Console.log(b(b(b(3))));

```

# Explanation

This program, as I mentioned earlier implements Buchholz hydras, which are stored as arrays. The program has functions l, m and s, which just serve as shorthand for commonly repeated chunks of code. The function e takes a given hydra and expands it using rules.

It was proven by Buchholz that you can always kill a hydra in a very large, yet finite, amount of steps, so this is what the program uses. The function b(n) produces the hydra \[+,0\] and then a string of n-2 \\$\omega\\$s, and returns the number of steps it took to be killed.

The number which it returns is \\$BH^3(3)\\$, which is around \\$f\_{\psi\_0(\varepsilon\_{\Omega\_\omega+1})+1}(3)\\$ in the FGH.

# Size

The function \\$BH(n)\\$ which this program implements is proven to eventually dominate (overtakes) any function which is provably total in \\$\Pi^1\_1\\$-comprehension with bar induction (\\$\Pi^1\_1-CA+BI\\$).

In fact, even if I replaced "chain of n-2 \\$\omega\\$s" with "chain of n-2 ones", I would still get third place. However, I have to say, Simply Beautiful Art, your achievement of second place is simply beautiful, and I could never beat it just by trivially this program. Since \\$TFBO = \psi\_0(\varepsilon\_{\Omega\_\omega + 1})\\$, I could say that \\$TFBO\_2 = \psi\_0(\varepsilon\_{\Omega\_{TFBO} + 1})\\$, and so on, if I allowed labels up to \\$TFBO\_{TFBO\_{...}}\\$ instead of just \\$\omega\\$, my new growth rate would fall around \\$\psi\_0(\chi(\Omega))+1\\$, which is tiny compared to \\$\psi\_0(\chi(\Omega\_{M+\chi(\Omega\_M+1^{Ω\_{M+1}})}))+29\\$

---
Tags: math, code-challenge, busy-beaver, open-ended-function
---


# Question
Title: Write a regex that would increment a 2-digit hexadecimal number
Your regex will receive a string of the form

```
!XX!

#<extra>

```

where `X` is any hexadecimal digit (0-9 and A-F **capital letters only**), and `<extra>` is a character sequence to your choosing. (perhaps something like `0123456789ABCDEF0` could be useful?)

You may use any regex flavour.

Scoring will be calculated as: find regex length + replace length + custom string length. lowest score wins.

Your submission must include which flavour you are using, the find regex, the replace string, and your extra string, all of their lengths, and the total length.

**test cases:**

```
!00!

#<extra>

```

Expected output:

```
!01!

#<extra>

```

---

```
!AC!

#<extra>

```

Expected output:

```
!AD!

#<extra>

```

---

```
!2F!

#<extra>

```

Expected output:

```
!30!

#<extra>

```

---

```
!FF!

#<extra>

```

Expected output:

```
!00!

#<extra>

```

---

# Answer
# Perl 5, ~~58~~ score: 21 + 2 + 17 = 40 bytes

Using PCRE substitution

```
s/(\w)(?=F?.
#.*?\1(.))/$2/g

```

with extra

```
0123456789ABCDEF0

```

Try it online!

First solution overcomplicated

~~```
s/(\w)(F)?(?=.
#.*?\1(.).*(?(2)F(.)))/$3$4/g

```
with extra<br>```
0123456789ABCDEF0F0

```~~
> 2 votes

# Answer
# Retina 0.8.2, 20 + 2 + 17 = 39 bytes

```
(\w)(?=F*!¶¶.*\1(.))
$2

```

Try it online! Linked test suite automatically adds and removes the extra string.
> 1 votes

# Answer
# Perl 5, 3+25+0 = 28

```
s/\w+/sprintf"%02X",1+hex$&&255/e

```

Try it online!

3 chars in `\w+`.

25 in `sprintf"%02X",1+hex$&&255` where `$&` is the found input hex number.

0 extra chars after `#`.
> 0 votes

---
Tags: code-challenge, regular-expression, hexadecimal
---


# Question
Title: Smallest positive integer not yet appeared so that the sum of the first n elements is divisible by n
# Task

Given positive integer `n`, output `a(n)` where `a` is the sequence defined below:

`a(n)` is the smallest positive integer not yet appeared so that the sum of the first `n` elements in the sequence is divisible by `n`.

# Example

* `a(1)` is `1` because it is the smallest positive integer that has not appeared in the sequence, and `1` is divisible by `1`.
* `a(10)` is `16` because look at the first nine elements: `1,3,2,6,8,4,11,5,14`. They sum up to `54`, so for the first ten elements to sum up to a multiple of `10`, `a(10)` would need to have a remainder of `6` when divided by `10`. `6` has already appeared, so `a(10)` is `16` instead.

# Testcases

```
n     a(n)
1     1
2     3
3     2
4     6
5     8
6     4
7     11
8     5
9     14
10    16
11    7
12    19
13    21
14    9
15    24
16    10
17    27
18    29
19    12
20    32
100   62
1000  1618
10000 16180

```

# References

# Answer
## Python 2, 43 bytes

```
r=.5+5**.5/2
lambda n:[n/r+1,n*r][n%r<1]//1

```

Outputs floats. Uses the relation

> a(n) = A002251(n-1) + 1

to Wythoff pairs. Takes from the upper or lower Beatty sequence by multiplying or dividing by the golden ratio and converting to an integer.
> 13 votes

# Answer
# Python 3, 102 bytes

Definitely not the shortest solution (not familiar with code golf) but I was bored so here it is in Python. I'm sure you could make it smaller with lambdas/filter.

```
def a(n,s=[]):
    for j in range(1,n+1):
        i=1
        while i in s or(sum(s)+i)%j:i+=1
        s+=[i]
    return s[-1]

```
> 3 votes

# Answer
# OCaml, 163 bytes

```
open List
let a x=let rec h m s=let rec n m s c=if fold_left(+)c(s)mod m<>0||mem c s then n m s(c+1)else c in if m=x then hd s else h(m+1)((n(m+1)s 2)::s) in h 1[1]

```

Online interpreter

### Usage

```
>> open List
>> let a x=let rec h m s=let rec n m s c=if fold_left(+)c(s)mod m<>0||mem c s then n m s(c+1)else c in if m=x then hd s else h(m+1)((n(m+1)s 2)::s)in h 1[1];;
<< val a : int -> int = <fun>
>> a(100);;
<< int = 62

```

where `>>` is STDIN and `<<` is STDOUT.
> 3 votes

# Answer
# Pyth - ~~23~~ ~~21~~ 18 bytes

Can probably streamline the generation process with more lambdas or other tricks, but this is my first answer in more than a month.

```
eem=+Yf!|}TY%+TsYh

```

Try it online here.
> 2 votes

# Answer
# Actually, 17 bytes

This uses xnor's algorithm. Golfing suggestions welcome. Try it online!

```
,;;φ(/u(φ*1φ(%<I≈

```

Here's a 31-byte version that uses the function definition, but with the oddity that, at first, the function returns the sequence `a(n)-1`, so the result needs to be incremented at the end. Try it online!

```
[]╗,`1";#╜+;l@Σ%@╜í+uY"£╓╖`n╜Nu

```

**Ungolfing:**

```
First algorithm

,;;                 Take the input, duplicate it twice
          1φ(%<I    If input mod phi less than 1
       (φ*          then input * phi
   φ(/u             else input / phi + 1
                ≈   int() the result

Second algorithm

[]╗    Push a list to register 0 (call this res from now on)
,      Take input
`1     Start function, push 1
  "      Start string
  ;      Duplicate i
  #╜+;   res + list(i), duplicate
  l      len(new list)
  @Σ     sum(new list)
  %      sum % len
  @╜í    Rotate i to top, check if i in res
  +uY    (sum%len) + (i in res) + 1, negate (1 if i fits conditions, else 0)
  "£     End string, turn into a function
╓      Push first (1) values where f(x) is truthy, starting with f(0)
╖`     Append result to the list in register 0, end function
n      Run function (input) times
╜Nu    Return res[-1]+1

```
> 2 votes

# Answer
# R, 99 bytes

```
f=function(n){a=n
b=c()
while(0<(a=a-1))b=c(f(a),b)
while(a<-a+1)if(!(sum(b)+a)%%n&!a%in%b)break
a}

```

Simple algorithm. Runs from `n-1` to `1` and gathers all of those numbers in the sequence. Then it moves up from 1 -- checking membership and whether it divides appropriately.
> 1 votes

# Answer
# Python 3, 96 bytes

```
n=int(input())
a=[]
for L in range(1,n+1):
 t=L-sum(a)%L
 while t in a:t+=L
 a+=[t]
print(a[-1])

```

Ideone it!
> 0 votes

# Answer
## JavaScript (ES6), 69 bytes

```
n=>{for(a=[],s=i=0;i++<n;a[j]=1,s+=j)for(j=i-s%i;a[j];)j+=i;return j}

```

At each stage just checks all the numbers with the appropriate remainder until it finds one that it hasn't seen before, then marks it seen and updates the total.
> 0 votes

# Answer
# Behaviour, 64 bytes

```
c=&[(~!a{})(l=c:a-1s=0\(~(l<=s+=1)~!(l+s>&a+b)%a)l+s)]f=&(!c)%-1

```

Test with:

```
f:1
f:2
f:10

```

Calculates the list recursively and doesn't even work for n \> 300, but you know, there was an attempt.

Ungolfed and commented:

```
// There are two functions, the first is recursive and creates the entire list
createList = &
  [
    (~!a; {})    // Base case, n==0 return empty list
    (
      list = createList:a-1 // create the list for n-1
      smallest = 0          // initialize the variable to find the smallest
                            // Repeat the following Sequencer until success
      \(
        // Increments smallest and check if it is NOT on the list
        ~(list <= smallest+=1)

        // sum up the list with the smallest found
        sum = list+smallest > &a+b

        // is the sum divided by n remainder 0
        ~!sum%a
      )
      // returns the list with the smallest
      list + smallest
    )
  ]
// The second function just execute the first and return its last item
f = &(!createList)%-1

```
> 0 votes

---
Tags: code-golf, sequence, integer
---


# Question
Title: Find a fraction's position in the Stern-Brocot tree
The Stern-Brocot tree is a binary tree of fractions where each fraction is acquired by adding the numerators and denominators of the two fractions neighbouring it in the levels above.

It is generated by starting with `0/1` and `1/0` as "endpoint fractions", and from there, iterating by placing one fraction between each consecutive pair of fractions by adding the numerators and denominators of those fractions together, like so:

```
0.  0/1                                                             1/0
1.  0/1                             1/1                             1/0
2.  0/1             1/2             1/1             2/1             1/0
3.  0/1     1/3     1/2     2/3     1/1     3/2     2/1     3/1     1/0
4.  0/1 1/4 1/3 2/5 1/2 3/5 2/3 3/4 1/1 4/3 3/2 5/3 2/1 5/2 3/1 4/1 1/0

```

In each iteration of the Stern-Brocot tree (the `n`th iteration), there are `2^n + 1` elements in the sequence, to which we can ascribe a fraction from `0/2^n` to `2^n/2^n`. Each new iteration simply inserts one fraction "halfway" between each pair of consecutive fractions.

This makes the Stern-Brocot tree a one-to-one mapping between the positive rational numbers and the binary fractions between 0 and 1, thereby also serving as a proof that the two sets have the same cardinality.

Your task is to write a program or function that, given the numerator and denominator of a positive rational number in lowest terms, determines the binary fraction that corresponds to that fraction's position in the Stern-Brocot tree.

Examples of inputs and outputs are provided below:

```
2/3 -> 3/8   (4th number in iteration 3)
4/7 -> 9/32  (between 1/2 and 3/5 in the chart above)
1/1 -> 1/2   (middle number in the first iteration)

```

Inputs you don't need to support, but are included for reference:

```
0/1 -> 0/1   (0/1 is considered the left number)
1/0 -> 1/1   (1/0 is considered the rightmost number)

```

The shortest program in any language to achieve this goal wins.

# Answer
## GolfScript (49 48 46 chars)

```
{0\@{}{@2*2$2$>!+@@{{\}3$)*}:j~1$-j}/\)\,?}:f;

```

or

```
{0:x;\{}{.2$<!2x*+:x){\}*1$-{\}x)*}/x@)@,?}:g;

```

Both are functions which take the numerator and denominator on the stack and leave the numerator and denominator on the stack. Online demo.

The core idea is expressed in pseudocode in *Concrete Mathematics* section 4.5 (p122 in my edition):

```
while m != n do
    if m < n then (output(L); n := n - m)
             else (output(R); m := m - n)

```

If the string of Ls and Rs is interpreted as a binary value with L=0 and R=1 then twice that value plus one is the numerator, and the denominator is one bit longer.

As a point of interest to Golfscripters, this is one of those rare occasions when I've found unfold useful. (Ok, I only use it as a loop counter, but that's better than nothing).
> 2 votes

# Answer
# Python 3, ~~98~~ 83 bytes

```
f=lambda a,b,n=1,d=2:a>b and f(a-b,b,n*2+1,d*2)or a<b and f(a,b-a,n*2-1,d*2)or(n,d)

```

Try it online!

Explanation: The sequence of turns starting from 1 down to the given fraction in the Stern-Brocot tree is identical to the sequence of turns starting from the given fraction going to 1 in the Calkin-Wilf tree. This makes it much simpler to get the sequence.

*Improvement given by Bubbler. Original solution here.*
> 4 votes

# Answer
## Ruby (69 chars) CoffeeScript (59 chars)

This is a function which takes numerator and denominator as arguments and returns an array containing the numerator and denominator after the bijection.

```
g=(a,b,x=0,y=1)->c=a>=b;a&&g(a-b*c,b-a*!c,2*x+c,2*y)||[x,y]

```

Online demo

It uses the same approach as my GolfScript solution above, but is much more readable because I can use 4 variables without having to worry about boxing and unboxing into an array. I chose CoffeeScript because it doesn't prefix variables with `$` (20 chars saved over e.g. PHP), has short function definition syntax which allows default parameter values (so there's no need to wrap `f(a,b,x,y)` in a function `g(a,b) = f(a,b,0,1)`), and lets me use Booleans as integers in expressions with useful values. For those who don't know it, CoffeeScript doesn't have the standard C-style ternary operator (`C?P:Q`), but I'm able to substitute `C&&P||Q` here because `P` will never be falsy.

An arguably more elegant, but inarguably less short, alternative is to replace the repeated subtraction with division and modulo:

```
f=(a,b,x=0,y=1,p=0)->a&&f(b%a,a,(x+p<<b/a)-p,y<<b/a,1-p)||[x+p,y]

```

(65 chars; online demo). Writing it this way exposes the relationship with Euclid's algorithm.
> 2 votes

# Answer
## Ruby, ~~132~~ 125

Rubied & golfed the reference solution from @JoeZ.

```
def t(n,d)u=k=0;v,j,f,g,b=[1,]*5;c=2
while(z=(f*d).<=>(g*n))!=0;z>0?(j,k=f,g):(u,v=f,g);b=b*2-z;f,g=u+j,v+k;c*=2;end
[b,c]end

```

Usage examples:

```
>> t(2,3)
=> [3, 8]
>> t(4,7)
=> [9, 32]
>> t(1,1)
=> [1, 2]

```
> 1 votes

# Answer
# Mathematica, ~~130 114~~ 111 chars

```
f=#~g~0&;0~g~q_=q;p_~g~q_:=g[#,(Sign[p-#]+q)/2]&@FromContinuedFraction[ContinuedFraction@p/.{x___,n_}:>{x,n-1}]

```

### Example:

```
f[2/3]

```

> 3/8

```
f[4/7]

```

> 9/32

```
f[1]

```

> 1/2
> 1 votes

# Answer
# Mathematica 138

Not as streamlined as alephalpha's procedure, but it was the best I've been able to produce so far.

```
q_~r~k_:=Nest[#+Sign@k/(2Denominator@# )&,q,Abs@k]
g@d_:=
Module[{l=ContinuedFraction@d,p=-1},
l[[-1]]-=1;
(p=-p;# p)&/@l]
h[q_]:=Fold[r,1/2,g@q]

```

Testing

```
h[2/3]
h[4/7]
h[1]

```

> 3/8
> 9/32
> 1/2
> 1 votes

# Answer
# Haskell, 125 bytes

```
n((a,b):(c,d):r)=(a,b):(a+c,b+d):n((c,d):r)
n a=a
z=zip[0..]
t x=[(j,2^i)|(i,r)<-z$iterate n[(0,1),(1,0)],(j,y)<-z r,x==y]!!0

```

Try it online!

Input and output in the form of a pair `(n,d)`.

Brief Explanation:

`n` constructs the next row from the previous one by looking at each pair of fractions and inserting the new one between the first and the recursion (which will put the second fraction right there). The base case is very simple since it's basically just the identity function. The `t` function iterates that function indefinitely based off the initial state with just the two boundary fractions. `t` then indexes each row (`i`) and each item in the row (`j`) and looks for the first fraction that matches what we're looking for. When it finds it yields `j` as the numerator and `2^i` as the denominator.
> 1 votes

# Answer
# Python - 531

An ungolfed solution in Python, to serve as a last-place reference solution:

```
def sbtree(n, d):
    ufrac = [0, 1]
    lfrac = [1, 0]
    frac = [1, 1]
    bfrac = [1, 2]
    while(frac[0] * d != frac[1] * n):
        if(frac[0] * d > frac[1] * n):
            # push it towards lfrac
            lfrac[0] = frac[0]
            lfrac[1] = frac[1]
            bfrac[0] = bfrac[0] * 2 - 1
        elif(frac[0] * d < frac[1] * n):
            # push it towards ufrac
            ufrac[0] = frac[0]
            ufrac[1] = frac[1]
            bfrac[0] = bfrac[0] * 2 + 1
        frac[0] = ufrac[0] + lfrac[0]
        frac[1] = ufrac[1] + lfrac[1]
        bfrac[1] *= 2
    return bfrac

```

It simply does a binary search between fractions, taking advantage of the fact that the mediant of any two fractions will always between the values of those two fractions.
> 0 votes

# Answer
### GolfScript, 54 characters

```
'/'/n*~][2,.-1%]{[{.~3$~@+@@+[\]\}*].2$?0<}do.@?'/'@,(

```

Input must be given on STDIN in the form specified in the task. You may try the code online.

```
> 4/7
9/32

> 9/7
35/64

> 5/1
31/32

```
> 0 votes

# Answer
# JavaScript 186

```
f=(p1,q1,p2,q2)=>{if(p1*q2+1==p2*q1){return{p:p1+p2,q:q1+q2}}let p,q,pl=0,ql=1,ph=1,qh=0;for(;;){p=pl+ph;q=ql+qh;if(p*q1<=q*p1){pl=p;ql=q}else if(p2*q<=q2*p){ph=p;qh=q}else return{p,q}}}

```

could be less, but I like readable golf
> 0 votes

---
Tags: code-golf, math, rational-numbers, binary-tree
---