title: Generate the ticks of a graph

text:
# Question
Title: Generate the ticks of a graph
A challenge many developers face when drawing a graph from scratch to plot some data is generating its ticks. In below graph, there are 6 horizontal ticks (1750, 1800, 1830, 1860, 1880 and 1900) and 11 vertical ticks (0, 10, 20, 30, 40, 50, 60, 70, 80, 90 and 100).

The horizontal bounds of the above graph goes from 1750 to 1900, which we'll call \\$x\_{min}\\$ and \\$x\_{max}\\$, respectively. For any \\$x\_{min}\\$ and \\$x\_{max}\\$ values, using \\$n\\$ ticks, there is a minimum multiple \\$m\\$ of a value \\$s\\$ that satisfies the following:

1. \\$m \geq x\_{min}\\$
2. \\$(m + s \times (n - 1)) \leq x\_{max}\\$; and
3. \\$(m + s \times n) \gt x\_{max}\\$.

Let's suppose \\$x\_{min} = 0\\$, \\$x\_{max} = 19\\$ and \\$n=4\\$.

* Consider \\$s=4\\$. The minimum multiple of \\$s\\$ that is greater or equal than \\$x\_{min}\\$ is 0, therefore \\$m=0\\$. While the second condition is satisfied (\\$0 + 4 \times 3 = 12 \leq x\_{max}\\$), the third condition is not (\\$0 + 4 \times 4 = 16 \not \gt x\_{max}\\$).
* Consider \\$s=5\\$. The minimum multiple of \\$s\\$ that is greater or equal than \\$x\_{min}\\$ is 0, therefore \\$m=0\\$. Both the second (\\$0 + 5 \times 3 = 15 \leq x\_{max}\\$) and the third (\\$0 + 5 \times 4 = 20 \gt x\_{max}\\$) conditions are satisfied, therefore \\$s=5\\$.

Note that we need to minimize \\$s\\$: \\$s=6\\$ also satisfies all of the conditions, but we'll use \\$s=5\\$. In addition, since there could be more than one multiple of \\$s\\$ that satisfies all three conditions, we want also to minimize \\$m\\$ of the minimum found \\$s\\$.

Finding \\$s\\$ allows us to create \\$n\\$ equally-spaced ticks that can be used for our graph. The sequence goes from \\$m\\$ to \\$m + s \times (n - 1)\\$ with step \\$s\\$, so using \\$s=5\\$ as in the previous example, the generated ticks are \\$\\{0, 5, 10, 15\\}\\$. These ticks also gives the impression that our graph is sliding if we scale those properly, since they will only change if \\$x\_{min}\\$ is a multiple of \\$s\\$. Below a gif that illustrates the generated ticks for \\$(x\_{min}, x\_{max})\\$ going from (0, 19) to (10, 29), with \\$n=4\\$.

Another way of thinking about this problem is generating the ticks beforehand. Let's suppose \\$x\_{min} = 4\\$, \\$x\_{max} = 21\\$ and \\$n=3\\$.

* Consider \\$s=5\\$. This would generate the ticks \\$\\{5, 10, 15\\}\\$ and the next tick would be 20, which is not greater than \\$x\_{max}\\$ (breaking the third condition). Note that here, \\$m=5\\$ since it's the first multiple \\$m\\$ of \\$s\\$ such that \\$m \geq x\_{min}\\$.
* Consider \\$s=6\\$. This would generate the ticks \\$\\{6, 12, 18\\}\\$ and the next tick would be 24, which is greater than \\$x\_{max}\\$ (satisfying all conditions). We could also use \\$s = 7\\$, but we want to minimize this value.

## Input

* Two real numbers `min` and `max` representing the minimum and the maximum values of a range, where `max` is greater than `min`; and one positive integer (`num`) representing the number of ticks.

The input is guaranteed to generate an integer `s`, so you should not handle `min = 0`, `max = 4`, and `num = 3` for example.

## Output

* A sequence of equally-spaced numbers with length `num` representing the ticks of a graph based on the previous explanation.

## Test cases

```
# from gif
0, 19, 4 -> [0, 5, 10, 15]
1, 20, 4 -> [5, 10, 15, 20]
2, 21, 4 -> [5, 10, 15, 20]
3, 22, 4 -> [5, 10, 15, 20]
4, 23, 4 -> [5, 10, 15, 20]
5, 24, 4 -> [5, 10, 15, 20]
6, 25, 4 -> [10, 15, 20, 25]
7, 26, 4 -> [10, 15, 20, 25]
8, 27, 4 -> [10, 15, 20, 25]
9, 28, 4 -> [10, 15, 20, 25]
10, 29, 4 -> [10, 15, 20, 25]
11, 30, 4 -> [15, 20, 25, 30]

# m can be negative
-10, 1, 3 -> [-8, -4, 0]
-9, 2, 3 -> [-8, -4, 0]
-8, 3, 3 -> [-8, -4, 0]
-7, 4, 3 -> [-4, 0, 4]
-6, 5, 3 -> [-4, 0, 4]
-5, 6, 3 -> [-4, 0, 4]
-4, 7, 3 -> [-4, 0, 4]
-3, 8, 3 -> [0, 4, 8]
-2, 9, 3 -> [0, 4, 8]
-1, 10, 3 -> [0, 4, 8]

# num can be 1
0, 3, 1 -> [0]
1, 4, 1 -> [3]
2, 5, 1 -> [3]
3, 6, 1 -> [4]
4, 7, 1 -> [6]
5, 8, 1 -> [6]
6, 9, 1 -> [8]
7, 10, 1 -> [9]
8, 11, 1 -> [9]
9, 12, 1 -> [12]

```

This is , so shortest code in bytes wins. Default I/O methods apply.

# Answer
> 4 votes
# , <sup>30 28 </sup> 38 bytes

```
1 :'](]*i.@u+>.@%),(]+0 0-:|~)u>.@%~-'

```

Try it online!

This is a J adverb modifing `n`, the number of ticks, and taking the max and min as left and right args, respectively. Called like:

```
19 (4 f) 0

```
* `u>.@%~-` Calculates step size by dividing `n` into the difference between the max and min.
    + `,(]+0 0-:|~)` Adds one to the step size if the step size evenly divides both endpoints.
* `]*` The step size times...
    + `i.@u` Produces range `0..n-1`
    + `+` Add elementwise to...
    + `>.@%` The ceiling of `>.@` the min divided by the step size `%` -- adjusts so the first tick starts where we want.

# Answer
> 4 votes
# Charcoal, 41 bytes

```
ＮθＮηＮζ≔¹ε≔…·⌈θηδＷ⁻Ｌδζ«≦⊕ε≔…·⌈∕θε∕ηεδ»Ｉ×δε

```

Try it online! Link is to verbose version of code. Explanation: I tried and failed to find some sort of formula, so brute force it is.

```
ＮθＮηＮζ

```

Input the minimum, maximum and ticks.

```
≔¹ε≔…·⌈θηδ

```

Start with a step of 1 and ticks from the ceiling of the minimum to (the floor of) the maximum.

```
Ｗ⁻Ｌδζ«

```

Repeat until we get the desired number of ticks.

```
≦⊕ε

```

Increment the step.

```
≔…·⌈∕θε∕ηεδ

```

Divide the ends by the new step size and list the integers in that range.

```
»Ｉ×δε

```

Multiply those by the step to get the desired output.

# Answer
> 3 votes
# , ~~45~~ ~~69~~ 59 bytes

*Edit: ~~+24~~ +14 bytes to fix bug pointed-out by Neil & ophact*

```
function(l,h,n){while((t=-l%/%T+1)+h%/%T-n)T=T+1
T*(1:n-t)}

```

Try it online!

**Ungolfed version**

```
ticks=
function(l,h,n){        # l=low, h=high, n=n ticks
  d=1:(h-l+1)           # d=range of possible values of s to try
  s=match(n,(floor(h/d)-ceiling(l/d)+1))
                        # calculate s by trying each value of d
                        # until floor(h/d)-ceiling(l/d)+1 is equal to n
                        # (golfed: match(n,h%/%d+-l%/%d+1))
  a=ceiling(l/s)*s      # calculate a=start value (golfed: --l%/%s*s)
  return(a+(1:n-1)*s)   # output ticks (golfed: s*(1:n-1--l%/%s))
}

```

# Answer
> 2 votes
# Jelly, 13 bytes

```
r/ḍ@ƇⱮJ$L⁼¥ƇḢ

```

A dyadic Link accepting a pair of numbers, `[xmin, xmax]`, on the left and an integer, `n`, on the right that yields a list of ticks.

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

### How?

```
r/ḍ@ƇⱮJ$L⁼¥ƇḢ - Link: list, bounds; integer, n:
 /            - reduce (bounds) with:
r             -   inclusive range -> [xmin..xmax]
       $      - last two links as a monad - f([xmin..xmax]):
      J       -   range of length -> [1..(xmax-xmin)+1]
     Ɱ        -   map across that with:
    Ƈ         -     filter keep those for which:
   @          -       with swapped arguments:
  ḍ           -         divides?
           Ƈ  - filter keep those for which:
          ¥   -   last two links as a dyad - f(potential tick list, n):
        L     -     length (potential tick list)
         ⁼    -     equals (n)?
            Ḣ - head

```

# Answer
> 2 votes
# Haskell, 63 bytes

```
(x#y)n=[[i|i<-[x..y],mod i s<1]|s<-[1..],div y s+div(-x)s<n]!!0

```

Try it online!

The function `(#)` takes the minimum value `x`, the maximum value `y` and the number of ticks `n`.

## How?

The problem is equivalent to finding $$ \min\left\\{s\ge 1:\left\lfloor\frac{x\_{\text{max}}}{s}\right\rfloor-\left\lceil\frac{x\_{\text{min}}}{s}\right\rceil=n-1\right\\}. $$

Since we are guaranteed that an answer exists, it is sufficient to find $$ \min\left\\{s\ge 1:\left\lfloor\frac{x\_{\text{max}}}{s}\right\rfloor-\left\lceil\frac{x\_{\text{min}}}{s}\right\rceil\<n\right\\}. $$

# Answer
> 1 votes
# JavaScript, ~~99~~ 97 bytes

```
(a,b,n)=>(g=s=>(x=s*Math.ceil(a/s))+s*(n-1)<=b&x+s*n>b?[...Array(n)].map((_,i)=>x+s*i):g(s+1))(0)

```

I will golf this later; could not find a suitable replacement for `Math.ceil`.

*-2 bytes thanks to my own golfing efforts.*

# Explanation.

This is an implementation which simply follows what is asked in the question. The function is recursive and will call itself with `s+1` if the conditions are not satisfied.

## commented

```
(a,b,n)                         // declare parameters: input a, b, n
=>                              // start of arrow function expression
(g=                             // assign function expression to g
s=>                             // declare parameters: s
(x=                             // assignment expression: assign value to identifier x
s*Math.ceil(a/s))               // s multiplied by ceiling of a over s
+s*(n-1)<=b                     // speaks for itself
&                               // bitwise and (saves one byte)
x+s*n>b                         // speaks for itself
?                               // if above conditions satisfied, return
[...Array(n)].map((_,i)=>x+s*i) // array of n elements each filled in with x + s times i
:                               // otherwise return
g(s+1)                          // call with s+1
)                               // closing bracket
(0)                             // IIFE: initial call with s=0.

```

And "fun fact": when s is 0, we get `NaN` (`Infinity * 0`) as the value for `x`, which makes it quietly fail. However, this is not noticed as the function increments `s` due to unsatisfied conditions.

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


title: Time bomb (KoTH)

text:
# Question
Title: Time bomb (KoTH)
In this challenge, players need to tamper with a time bomb as late as possible without getting blasted in the face.

## Mechanics

Let `N` be the number of bots plus one. Each round, each bot receives the following arguments:

* numbers played by all bots last round in ascending order.
* number of points it received last round. Negative if it lost last round.

The bot is asked to play an integer between 1 to `N` inclusive. After all bots played their numbers, a counter is initialized with half of the sum of numbers from all bots. Each bots then subtracts the number it played from the counter. Bots are sorted from the lowest to the highest. Bots with the same number are considered subtracts the counter at the same time. The bomb explodes when the counter hits zero or becomes negative.

## Scoring

After the bomb exploded, the round ends, and the points for this round is calculated as the following:

* Bots that played before the explosion get the number of points equal to **twice** the number it played this round.
* Bots that played when the explosion lose the number of points equal to the number it played this round.
* Bots that played after the explosion do not get nor receive point.

Example rounds:

* Number played: `[1,2,3,4,5]`. The initial counter is 7.5, and the bomb explodes on 4. The bot with 1, 2, and 3 gets 2, 4, and 6 points respectively, the bot with 4 loses 4, and the bot with 5 neither gets not lose points.
* Number played: `[1,1,2,4]`. The initial counter is 4, and the bomb explodes on 2. Bots with 1 gets 2 points, the bot with 2 loses 2, and the bot with 4 neither gets not lose points.
* Number played: `[3,3,3,3]`. The initial counter is 6, and the bomb explodes on 3. All bots lose 3 points.

The point for each round is added to a total score for that run. Each run consist of 1000 rounds, and there will be 10 runs. The final total score is the sum of each run, and the bot with the highest final score the the end wins.

## Specifications

The challenge is in JS.

Your bot must be an object that has a `run` method that takes an array of numbers and a number as input, and returns a integer between 1 and `N` inclusive. The value being outside the valid range will be rounded and clamped. If the value is not a number, a number in the valid range will be selected and the behavior of selecting the number is not specified.

On the first round, the array of numbers given will be initialized with random numbers, and the number for points last round will be 0.

## Other rules

* Storing data in your bot's properties is allowed.
* You can use the `Math.random` method. During scoring, seedrandom.min.js will be used, with a secret string concatenated with the run number as the seed for each run. The md5 of the secret string is `4311868bf10b3f7c1782982e68e6d7ca`, for proving that I didn't change the key after the challenge.
* You can use the helper function `sum`.
* Trying to access any other variables outside your bot's own properties is forbidden.
* Standard loopholes apply.

The code for controller can be found here. Feel free to point out mistakes in my code, thanks.

## Example bots

```
{
  // Example bot
  // It always play the middle number.
  name: "Middle",
  run(number) {
    return Math.round((numbers.length+2)/2);
  }
}

```

```
{
  // Example bot
  // It starts at 1, advances when it got points last round,
  // and resets when it lost points.
  name: "Advance and reset",
  last: 1, // Setting properties is allowed
  run(numbers, points) {
    var own = this.last;
    if(points > 0){
      own = Math.min(this.last+1, numbers.length+1);
    }
    if(points < 0){
      own = 1;
    }
    this.last = own;
    return own;
  }
}

```

Both example bots above will also play in the game.

# Submissions are due by 2021-05-06 12:00 UTC, but might be lenient depending on when I'm online after the said time above.

# Answer
> 5 votes
```
{
  name: "Playing It Safe",
  run(numbers) {
    return 1;
  }
}

```

# Answer
> 4 votes
Some "basic" bots to get this started, also to serve as baseline (they will also play in the game):

```
{
  name: "33%",
  run(numbers) {
    return numbers[Math.floor(numbers.length/3)];
  }
}

```

```
{
  name: "Pure random",
  run(numbers) {
    return Math.floor(Math.random() * (numbers.length+1))+1;
  }
}

```

```
{
  name: "Copy random",
  run(numbers) {
    return numbers[Math.floor(Math.random() * numbers.length)];
  }
}

```

```
{
  name: "Alternate",
  round: 0,
  run(numbers) {
    this.round++
    return (this.round % 2)? 1 : (numbers.length + 1)
  }
}

```

# Answer
> 3 votes
# Smart Random

```
{
name: "Smart Random",
  run(numbers) {
    var random_int = Math.floor(Math.random() * 3 * (numbers.length+1)/4);
    return random_int
  }
}

```

Returns a random integer between 0 and 3/4`N` inclusive.

I hope this works - this is my first JS and my first KoTH answer.

# Answer
> 2 votes
# Coinflipper

Starts by initialising `x` to half of `N`, then flips `N` coins. If heads, decrement `x` (unless already zero). If tails, increment `x` (unless already equal to `N`).

```
{
  name: "Coinflipper",
  run(numbers) {
    let x = Math.floor(numbers.length/2);
    numbers.forEach(function(){
        let coin = (Math.floor(Math.random()*2)+1)
        if (coin==1) { x--; }
        else if (coin==2) { x++; }
        if (x<0) { x=0; }
        if (x>numbers.length) { x=numbers.length; }
    });
    return x;
  }
}

```

# Answer
> 1 votes
# Painfully Average

```
{
    name: "Painfully Average",
    run: (n)=>Math.abs(Math.floor(n.reduce((a,x)=>a+x))/n.length-1)
}

```

# Answer
> 1 votes
# OnePlus

Plays one plus a random floating point between 0 and a random integer between 0 and 5.

```
{
  name: "OnePlus",
  run(numbers) {
    return 1 + Math.random() * Math.floor(Math.random() * 5);
  }
}

```

My first King Of The Hill answer, not sure if I am doing things correctly. From my understanding, `numbers` is the list of numbers of the bots? But I am completely ignoring that `numbers`.

# Answer
> 1 votes
# D8roller

Rolls a 8-sided die, and plays that number.

```
{
  name: "D8roller",
  run(numbers) {
    return Math.floor(Math.random()*8)+1;
  }
}

```

---
Tags: king-of-the-hill, javascript
---


title: Implement swap encoding

text:
# Question
Title: Implement swap encoding
Swap encoding is an encoding method where you iterate through a string, reversing sections of it between pairs of identical characters.

### The basic algorithm

For each character in the string:

Check: Does the string contain the character again, after the instance you found?

If so, then modify the string by reversing the section between the character and the next instance, inclusive.

Otherwise do nothing.

# Example

Start with the string 'eat potatoes'.

e is found again, so reverse that section: `eotatop taes`
o is found again, so reverse that section (doing nothing as it is palindromic)
t is found again, so reverse that section (doing nothing as it is palindromic)
a is found again, so reverse that section: `eotat potaes`
t is found again, so reverse that section: `eotatop taes`
None of 'op taes' are found again, so `eotatop taes` is our final string!

# Your challenge

Your challenge is to make a program or function that takes a string as input and returns it encoded as above. Capital letters and lowercase letters are treated as different, and all characters, including spaces, can be swapped.

# Testcases

```
Sandbox for Proposed Challenges => SahC Pr foropox dbosenallednges
Collatz, Sort, Repeat => CoS ,ztrollaepeR ,tat
Write a fast-growing assembly function => Wrgnufa ylbme asa f g-tesstcnoritiwoin
Decompress a Sparse Matrix => Dera aM ssrtapmocese Sprix
Rob the King: Hexagonal Mazes => Rog: Kinob eH lagnaM thezaxes
Determine if a dot(comma) program halts => Detoc(tlamarommi finerp ha mrgod a) ets
Closest Binary Fraction => CloinosestiB Fry tcaran
Quote a rational number => Qunatebmuoiton re al ar
Solve the Alien Probe puzzle => SorP Alveht en eilzzup elobe

```

Yes I just took the titles of various sandboxed challenges for the testcases.

My reference implementation is available here if anyone wants it.

This is actually an encoding as `reverse(swap(reverse(string)))` decodes it.

# Answer
# JavaScript (ES6), 67 bytes

```
f=([c,...a])=>c?c+f([...a.splice(0,a.indexOf(c)).reverse(),...a]):a

```

Try it online!

### How?

`a.splice(0, n)` removes and returns the first \\$n\\$ entries in `a[]` if \\$n\ge1\\$ or removes nothing and returns an empty array if \\$n\<1\\$. If `c` is not found in `a[]`, `a.indexOf(c)` returns \\$-1\\$ and we just pass `a[]` unchanged to the next iteration.
> 6 votes

# Answer
# Python 3, 98 92 89 bytes

```
def f(s):
 if s:t=s[1:];i=t.find(s[0]);return s[0]+f([t,s[i::-1]+t[i+1:]][i>0])
 return s

```

Try it online!

Thanks to this question, I am now absolutely confident of the usage of Python slices, which I had never remembered the off-by-one rules, especially when the step-size is negative.
> 6 votes

# Answer
# , 39 38 bytes

*-1 thanks to Jonah!*

```
0}:@{&|:(}.(|.@{.,}.)~<:@#|}.i.{.)^:a:

```

Try it online!

```
0}:@{&|:(}.(|.@{.,}.)~<:@#|}.i.{.)^:a:
                                  ^:a: repeat until result does not change,
                                        keeping the results
                           }.i.{.      index of first character in the tail
                      <:@#|            if not found, set to 0
         }.(        )~                 call with index and the tail
            |.@{.                      rotate up to the index
                 ,}.                   append after the index unchanged
      |:                               transpose,
0   {&                                 get the first char of each iteration
 }:@                                   and drop the last space

```
> 3 votes

# Answer
# , ~~104~~ 103 bytes

*Edit: -1 byte thanks to Kirill L.*

```
function(s,t=utf8ToInt(s)){for(i in seq(t))if(e<-match(t[i],t[-1:-i],0))t[i+0:e]=t[i+e:0];intToUtf8(t)}

```

Try it online!
> 3 votes

# Answer
# K (ngn/k), ~~35~~ 31 bytes

-4 bytes thanks to @coltim

```
*'{1<#x}{{(|x),y}.(1|2#*=x)_x}\

```

Try it online!
> 3 votes

# Answer
# Charcoal, 25 bytes

```
ＰθＷＫＫ«→≔⪫ＫＤＬθ→ωη¿ηＰ⮌…η⌕ηι

```

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

```
Ｐθ

```

Print the input string to the canvas without moving the cursor.

```
ＷＫＫ«

```

Repeat while the cursor is above a character of the input string:

Move to the next character.

```
≔⪫ＫＤＬθ→ωη

```

Get the current suffix.

```
¿ηＰ⮌…η⌕ηι

```

Print the reverse of the prefix of the suffix up to the first occurrence of the character that was moved away from, or the empty string if no such occurrence exists. (I need to check that the suffix is not empty because the `CycleChop` function fails for empty strings.)
> 2 votes

# Answer
# C (clang), ~~98~~ ~~96~~ 87 bytes

```
i;j;t;f(char*s){for(;*s;++s)for(i=0,j=index(s+1,*s)-s;j>i;s[j--]=t)t=s[i],s[i++]=s[j];}

```

Try it online!

Inputs a pointer to a string and swap encodes the string in place.
> 2 votes

# Answer
# Python 3.8, ~~67~~ 65 bytes

```
f=lambda s:s and s[0]+f(s[(j:=abs(s.find(s[0],1)))-1:0:-1]+s[j:])

```

Try it online!

-2 bytes thanks to @defald0r! Always adds a (possibly empty) reversed prefix to a (possibly empty) suffix after chopping off the first element.
> 2 votes

# Answer
# Ruby `-p`, ~~63~~ 58 bytes

```
$_.size.times{|i|$_[/(?<=^#{?.*i})(.).*?\1/]&&=$&.reverse}

```

Try it online!

Thanks to G B for -5 bytes.
> 2 votes

# Answer
# Retina 0.8.2, 56 bytes

```
^
¶¶
{`¶¶(.*?(.))(.*?)\2
$1¶$3¶$2
}+`¶(.)(.*¶)
¶$2$1
¶¶

```

Try it online! Link includes test cases. Explanation:

```
^
¶¶

```

Insert two blank lines so that there are now three lines: the output area, the reversing area and the input area.

```
{`
}`

```

Repeat until there are no duplicate characters in the input area.

```
¶¶(.*?(.))(.*?)\2
$1¶$3¶$2

```

Move the text up to and including the first duplicate into the output area and the text from after the first duplicate up to the second duplicate into the reversing area, leaving the second duplicate in the input area.

```
+`¶(.)(.*¶)
¶$2$1

```

Reverse the text between the duplicates and move it back to the input area.

```
¶¶

```

Join the output area with any remaining text in the input area.
> 1 votes

# Answer
# Haskell, 62 bytes

```
f(h:t)|(a,u:v)<-span(/=h)t=u:f(reverse a++h:v)|0<1=h:f t
f e=e

```

Try it online!
> 1 votes

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

```
{⌽@(⍳(≢c)|c⍳⍞←⍵∩⍨⊃⍵)⊢c←1↓⍵}⍣≡

```

Try it on APLgolf!

A dfn submission which takes the string as argument and outputs to STDOUT.

Shortened from 32 with Bubbler's help.
> 1 votes

# Answer
# PHP, 121 bytes

```
for($a=$argn;$c=$a[$i++];)for($j=0;2*$j<-$i+$p=strpos($a,$c,$i);$a[$p-$j]=$b){$b=$a[$j+$i];$a[$j+$i]=$a[$p-++$j];}echo$a;

```

Try it online!

PHP still competing for one of the worse golfing language with brio!

For the record, my best version with appropriate string functions is just the same number of bytes:

# PHP, 121 bytes

```
for($a=$argn;$c=$a[$i++];)if($p=strpos($a,$c,$i))$a=substr_replace($a,strrev(substr($a,$i-1,$l=$p-$i+2)),$i-1,$l);echo$a;

```

Try it online!
> 1 votes

# Answer
# Python 3.8, 96 bytes

```
f=lambda s,i=0:i<len(s)and f(i<(j:=s[i+1:].find(s[i])+i+1)and s[:i]+s[j:i:-1]+s[j:]or s,i+1)or s

```

Try it online!
> 0 votes

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


title: Generate a password

text:
# Question
Title: Generate a password
It is very hard to remember my password, so I came up with a way to generate a password.

The way I generate my password is from a word or a sentence, following these steps:

1. Start from left to right
2. Find the count of each letter
3. Put letter with its count in an order

* Letters with higher repetition will be in the end
    * Letters with the same repetition will be ordered alphabetically
4. Numbers and special letters will be ignored including whitespace (e.g. 9, 4, @, (, \*, etc. are ignored)
5. Group letters ignoring case. In the output, use the case of the last occurrence in the input
6. The count of the letter can be any number e.g. 5H17M345K
7. If input is all numbers or special letters then output will be empty string e.g. Input "12$\*34^!" then output ""
8. when order for the same occurrence alphabetically case does not matter e.g. 1a1B1c

Example:

```
Input: Kitkat Tango
(2k / 1i / 3T / 2a / 1n / 1g / 1o)
Output: 1g1i1n1o2a2k3T

```

Another example:

```
Input: Database Partitions Task
(1D / 5a / 4T / 1b / 3s / 1e / 1P / 1r / 2i / 1o / 1n / 3s / 1k)
Output: 1b1D1e1k1n1o1P1r2i3s4T5a

```

Note: the letters with 1 repeat are in the beginning ordered alphabetically then the letters with more reps

This is , the shortest code wins.

# Answer
> 7 votes
# Japt v2.0a0 `-P`, 14 bytes

```
f\l üv ñÊ®ÌiZÊ

```

Try it

```
f\l üv ñÊ®ÌiZÊ     :Implicit input of string
                   > e.g., "Kitkat Tango"

f                  :Split to an array of characters
 \l                :  Matching RegEx /[a-z]/gi
                   > ["K","i","t","k","a","t","T","a","n","g","o"]

    ü              :Sort & group (Preserves original order within each group)
     v             :  By lowercase
                   > [["a","a"],["g"],["i"],["K","k"],["n"],["o"],["t","t","T"]]

       ñ           :Sort
        Ê          :  By length
                   > [["g"],["i"],["n"],["o"],["a","a"],["K","k"],["t","t","T"]]

         ®         :Map each Z
          Ì        :  Last element of Z
                   >   ["g","i","n","o","a","k","T"]
           i       :  Prepend
            ZÊ     :    Length of Z
                   >   ["1g","1i","1n","1o","2a","2k","3T"]

                   :Implicitly join & output
                   > "1g1i1n1o2a2k3T"

```

# Answer
> 10 votes
# 05AB1E, ~~19~~ ~~17~~ 16 bytes

Saved 1 byte thanks to *Kevin Cruijssen*

```
áΣl}.γl}éεgyθJ}J

```

Try it online! or as a Test Suite

**Explanation**

```
á                  # keep only letters in input
 Σl}               # sort by lower-case
    .γl}           # group by lower-case
        é          # sort by length (stable)
         ε    }    # map each to
          g        # its length
             J     # joined with
           yθ      # the last letter
               J   # join to string

```

# Answer
> 8 votes
# Perl 6, ~~66~~ 63 bytes

```
{[~] map {+$_~.tail},sort {+$_,.lc},m:g/<:L>/.classify(&lc){*}}

```

Try it online!

### Explanation

```
{                                                             }  # Anon block
                                    m:g/<:L>/  # Match all letters
                                             .classify(&lc)  # Group by lowercase
                                                           {*}  # Get hash values
                     sort {+$_,.lc},  # Sort by array length and lowercase
     map {         },  # Map to
          +$_~.tail  # Concat array length and last letter
 [~]  # Join

```

# Answer
> 8 votes
# C# (Visual C# Interactive Compiler), 105 bytes

```
x=>x.Where(char.IsLetter).GroupBy(a=>a%32).OrderBy(a=>(a.Count(),a.Key)).Select(a=>a.Count()+""+a.Last())

```

Try it online!

Thanks to dana for bringing it down to 105 bytes from 138 bytes.

# Answer
> 6 votes
# Retina, ~~67~~ ~~66~~ ~~41~~ 39 bytes

```
\P{L}

O$`.
$l$0
ir`\1*(.)
$.0$1
N`\d+.

```

-25 bytes and a minor bug-fix thanks to *@Neil*.
-2 bytes thanks to *@Neil* and *@Shaggy* together.

Try it online or verify all test cases.

**Explanation:**

Remove everything except for upper- and lowercase letters:
i.e. `Kitkat Tango 123!``KitkatTango`

```
\P{L}

```

Sort the individual letters case-insensitive (thanks to *@MartinEnder* for this):
i.e. `KitkatTango``aagiKknottT`

```
O$`.
$l$0

```

Capture every chunk of case-insensitive repeated adjacent letters:
i.e. `aagiKknottT` → \[`aa`,`g`,`i`,`Kk`,`n`,`o`,`ttT`\]

```
ir`\1*(.)

```

Prepend the length of every match, and only keep the last letter of every chunk:
i.e. \[`aa`,`g`,`i`,`Kk`,`n`,`o`,`ttT`\] → `2a1g1i2k1n1o3T`

```
$.0$1

```

Sort the numbers and letter groups based on the numbers:
`2a1g1i2k1n1o3T``1g1i1n1o2a2k3T`

```
N`\d+.

```

After which the result is output implicitly.

# Answer
> 4 votes
# Perl 5 (`-n`), ~~74~~, ~~68~~, ~~66~~, 65 bytes

-6 bytes changing `-p` to `-n` and using `say` instead of `$_=join"",`
-2 bytes thanks to Abigail using `\pL` instead of `[a-z]`
-1 byte thanks to Kjetil S. removing `i` flag no more necessary after using `\pL`

```
s/\pL/($h{lc$&}+=1).=$&/ge;say sort{$a-$b||lc$a cmp lc$b}values%h

```

TIO

58 bytes, in case there is no more than 9 occurence of each character

```
s/\pL/($h{lc$&}+=1).=$&/ge;say sort{lc$a cmp lc$b}values%h

```

# Answer
> 4 votes
# Pyth, ~~27~~ ~~24~~ 22 bytes

```
ssrD0m,lded.gr0k@+Gr1G

```

Try it online here.

```
ssrD0m,lded.gr0k@+Gr1GQ   Implicit: Q=eval(input()), G=lowercase alphabet
                          Trailing Q inferred
                   r1G    Uppercase alphabet
                 +G       Concatenate with lowercase alphabet
                @     Q   Keep those characters in Q which are also in the above
           .g             Group the remaining characters, as k, using:
             r0k             Convert k to lowercase
                              (Grouping preserves relative order)
     m                    Map the sorted groups, as d, using:
       ld                   Length of d
      ,                     Pair the above with...
         ed                 ... last element of d
   D                      Sort the above...
  r 0                     ... by their lowercase values
ss                        Flatten, then concatenate the result of the above into a string, implicit print

```

*Edit: Golfed 3 bytes by ordering by character before group, previous version: `sm+ldedo,lNr0eN.gr0kf}r0TGQ`*

*Edit 2: Golfed off another 2 bytes by formatting output before any ordering, previous version: `sm+ldedlD.gr0krD0f}r0TGQ`*

*Edit 3: Golfed off another byte by changing the filter, thanks to @FryAmTheEggman. Also had to fix a bug when OP clarified that a single letter can appear more than 9 times, which added a byte back on :o( Previous version: `srD0m+lded.gr0kf}r0TGQ`*

# Answer
> 4 votes
# Python 3, 105 bytes

```
s=input()
t=s.upper()
for n,c in sorted((t.count(i),i)for i in{*t}if'@'<i<'['):print(n,end=s[t.rfind(c)])

```

Try it online!

-1 thanks to ArBo.

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~102~~ ~~96~~ ~~93~~ 87 bytes

```
""<>Map@ToString/@Sort[(r=Reverse)/@Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]]&

```

Try it online!

```
Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]      Start with a char list
        #/." "->Nothing                                Remove spaces
      r@                                               Reverse the result
Tally[                 ,Equal@@ToLowerCase@{##}&]
                                             Make a list of letters and multiplicities,
                                             where two letters are considered the same if
                                             their lowercase values are equal. Then:

""<>Map@ToString/@Sort[(r=Reverse)/@ ... ]&
                       (r=Reverse)           Reverse each {letter, freq} to {freq,letter}.
                                             Then the standard Wolfram order function sorts
                                               lower frequencies first, with ties broken by
                                               by letters earlier in the alphabet,
                  Sort[                  ]     exactly what we want.

    Map@ToString/@                           @ has higher precedence than /@, so
                                               this effectively does Map[Map[ToString]].
""<>                                         StringJoin the nested list into a single string.

```

# Answer
> 3 votes
# Python 2, 116 bytes

```
def f(s):a=s.lower();return''.join(`n`+s[a.rfind(c)] for n,c in sorted((a.count(c),c)for c in set(a)if c.isalpha()))

```

Try it online!

# Answer
> 3 votes
# Red, ~~220~~ ~~196~~ 206 bytes

```
func[s][a: charset[#"a"-#"z"#"A"-#"Z"]trim/all form sort/skip collect[foreach c sort
unique reverse rejoin parse s[collect[any[keep[a]| skip]]][i: 0
foreach d s[if(c% 32)=(d% 32)[i: i + 1]]keep i keep c]]2]

```

Try it online!

Thanks to Shaggy for finding a bug.

# Answer
> 3 votes
# Haskell, ~~114/113~~ 105 bytes

-9 bytes thanks to Laikoni (using list-comprehension and `(||)` instead of `filter` with `elem` & shorten `length` to get rid of ugly `zip`)!

```
f s=id=<<[show(h r)++[last r]|l<-[1..h s],a<-['A'..'Z'],r<-[[x|x<-s,x==a||x==[a..]!!32]],h r==l]
h=length

```

Try it online!

# Answer
> 3 votes
# Scala, 103 bytes

```
_.filter(_.isLetter).groupBy(_%32).values.map(l=>l.size+""+l.last).toSeq.sortBy(_.toLowerCase).mkString

```

Try it online!

# Answer
> 2 votes
# Jelly, 15 bytes

```
fØẠµŒlĠLÞịµL,Ṫ)

```

A full program printing the password as specified (as a monadic Link it yields a list of lists each containing an integer and a character).

**Try it online!**

# Answer
> 2 votes
# Husk, 15 bytes

No problems with imports when using Husk, therefore we can make use of the various handy functions such as `groupOn`, `sortOn`, `toLower` etc:

```
ṁ§:osL→ÖLSġÖ_f√

```

Try it online or try them all!

## Explanation

```
ṁ§:(sL)→ÖLSġÖ_f√  -- example input: "Kitkat Tango"
              f√  -- `filter isAlpha`: "KitkatTango"
          S  _    -- apply _ to .. then ..
            Ö     -- | sortOn: `sortOn toLower`
           ġ      -- | groupOn: `groupOn toLower`
                  -- .. compose: `groupOn toLower . sortOn toLower`
                  -- `sortOn toLower` (stable): "aagiKknottT"
                  -- `groupOn toLower`: ["aa","g","i","Kk","n","o","ttT"]
        ÖL        -- `sortOn length` (stable): ["g","i","n","o","aa","Kk","ttT"]
ṁ                 -- map and flatten (`concatMap`)
 §                -- | fork argument ..
       →          -- | | `last`: ['g','i','n','o','a','k','T']
   (sL)           -- | | `show . length`: ["1","1","1","1","2","2","3"]
  :               -- | .. and `snoc`: ["1g","1i","1n","1o","2a","2k","3T"]
                  -- : "1g1i1n1o2a2k3T"

```

# Answer
> 2 votes
# APL (Dyalog Extended), 28 bytesSBCS

Anonymous tacit prefix function.

```
(∊⍤∧⌊(⊂⍕⍤≢,⊢/)⍤⊢⌸⊢)'\PL'⎕R''

```

Try it online!

`'\PL'` non-letters
`⎕R` PCRE **R**eplaced with
`''` empty strings

`(``)` apply the following tacit function:

with the lowercase as keys,
… apply the below tacit function to each key and its corresponding set of values, namely
the argument:

`(``)` apply the following tacit function
to
the list of values:

`⊢/` the last value

…`,` prepend the following to that:

the stringification
of
the tally

enclose (to treat character list as single string)

**ϵ**nlist (flatten)
the
sorted-ascending version of that

# Answer
> 2 votes
# JavaScript (Node.js), 127 bytes

```
s=>[...s].sort(o=(x,y)=>p(0+x,36)-p(0+y,36),p=parseInt).join``.match(/([a-z])\1*/ig).map(x=>(l=x.length)+x[l-1]).sort(o).join``

```

Try it online!

* `parseInt(numberAsString, radix)` will try to parse integer in the beginning of string. For example, `parseInt('120px', 10)` will output 120. When parsing failed, it returns `NaN` instead. We connect an `'0'` to the beginning of each character so it will return `0` for any non numeric-alpha characters. And we can sort same letters together and non-alpha character to the beginning by this algorithm.
* After `sort` and `join`, `"Hello world!123"` would become `" !123deHllloorw"`. An matching against `/([a-z])\1*/ig` will ignore any non-alpha character and split the string into chunks with same letters. \`.
* `map` convert `"aaa"` to `"3a"` as required in the question.
* The second sort use same function as the first one. Thanks to the number system, `"3b"` would be less than `"12a"` in base 36 just as we expect: It compare counts first (`n div 36`), and compare the letter later (`n mod 36`).
* Finally `join` them together.

---

# JavaScript (Node.js), 146 bytes

```
f=(s,...a)=>(s=s.replace(/[^a-z]/ig,''))?f(s.replace(RegExp(s[c=0],'ig'),x=>(l=++c+x,'')),...a,l):a.sort((x,y)=>p(x,36)-p(y,36),p=parseInt).join``

```

Try it online!

# Answer
> 2 votes
# Java 10, ~~223~~ ~~209~~ 301 bytes

```
s->{int i=32,t;String M[]=new String[i],r,R="";for(var c:s)M[c%32]+=c>64&c<91|c>96&c<123?c:R;for(;i-->0;M[i]=(t=r.length()-4)>0?t+r.split(R)[t+3]:R)r=M[i]+R;java.util.Arrays.sort(M);for(var p:M)R+=p;return R;}

```

+92 bytes as a fix for inputs with more than 9 of a single letter.. Will see if I can bring that down again with a different approach.

Try it online.

**Explanation:**

```
s->{                        // Method with character-array parameter and String return-type
  int i=32,                 //  Index-integer, starting at 32
      t;                    //  Temp-integer, uninitialized
  String M[]=new String[i], //  Create a String-array of size 32, filled with null by default
         R="",              //  Result-String, starting empty
         r;                 //  Temp-String, uninitialized
  for(var c:s)              //  Loop over the characters of the input-array:
    M[c%32]+=               //   Append the string at index code-point of `c` modulo-32 with:
     c>64&c<91|c>96&c<123?  //    If the character is a letter:
      c                     //     Append the character
     :                      //    Else:
      R;                    //     Append an empty String
  for(;i-->0                //  Loop `i` in the range (32, 0]:
      ;                     //    After every iteration:
       M[i]=                //     Replace the String at index `i` with:
        (t=r.length()-4)    //      Set `t` to the length of String `r` minus 4
                            //      (the minus 4 is for the prepended "null")
         >0?                //      If this length minus 4 is larger than 0:
          t                 //       Set the String to this length minus 4
          +r.split(R)[t+3]  //       Appended with the last character of `r` as String
         :                  //      Else:
          R)                //       Make the String at index `i` empty
    r=M[i]                  //   Set `r` to the `i`'th String
          +R;               //  Converted to String
                            // (null becomes "null", to prevent NullPointerException-errors)
  java.util.Arrays.sort(M,  //  Now sort the array of Strings on:
   (a,b)->                  //   For each pair of two Strings:
     new Byte(              //    Convert the first String to a number
      (0+a).replaceAll("\\D",""))
                            //    after we've added a leading 0 and removed all non-digits
    .compareTo(             //   And compare it to:
     new Byte(              //    The second String converted to a number
      (0+b).replaceAll("\\D",""))));
                            //    after we've added a leading 0 and remove all non-digits
  for(var p:M)              //  Loop over the Strings of the array:
    R+=p;                   //   And append each to the result-String `R`
  return R;}                //  And finally return the result-String `R`

```

# Answer
> 2 votes
# Swift 4.2.1/Xcode 10.1, ~~1054~~ ~~1050~~ ~~1048~~ ~~370~~ ~~368~~ 364 bytes

```
s.map{String($0)}.filter{$0.rangeOfCharacter(from:.letters) != nil}.reversed().reduce(into:[String:Int]()){d,s in if let l=[s.uppercased(),s.lowercased()].first(where:{d[$0] != nil}){d[l]=d[l]!+1}else{d[s]=1}}.sorted{let c=$0.value-$1.value;return c==0 ?$0.key.compare($1.key,options:.caseInsensitive) == .orderedAscending:c<0}.map{"\($0.value)\($0.key)"}.joined()

```

Try it online!

@KevinCruijssen also removed some spaces.

# Answer
> 1 votes
# Charcoal, 30 bytes

```
Ｆ⌈Ｅβ№↧θιＦβ¿⁼№↧θκ⊕ι⁺⊕ι§Φθ⁼↧λκ±¹

```

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

```
Ｆ⌈Ｅβ№↧θι

```

Run through the lowercase alphabet and find the highest character count in the lowercased input. Loop over the implicit range. (The loop actually goes from `0` to `n-1` so I have to increment the loop variable at each use.)

```
Ｆβ

```

Loop over the lowercase alphabet again.

```
¿⁼№↧θκ⊕ι

```

If the count of the current letter is equal to the outer loop value...

```
⁺⊕ι§Φθ⁼↧λκ±¹

```

Concatenate the current count with the last occurrence of the current letter and implicitly print.

# Answer
> 1 votes
# Jelly, 14 bytes

```
fØẠŒuL,ṪƊƙ$ŒuÞ

```

Try it online!

Full program.

# Answer
> 1 votes
## NodeJS, 299 bytes, -6 bytes thank to @tsh

Not so beauty but it work!

```
(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).join``[R](/,/g,'')[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())

```

## Javascript (ES8) (Firefox or Chrome), 294 bytes, -1 byte thank to @tsh

With new `.flat` method, I can save 10 bytes:

```
(x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).flat().join``[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase())

```

Try this online: https://repl.it/repls/ConcernedHorribleHypothesis

# Answer
> 1 votes
# , ~~131~~ 129 bytes

```
cat(paste0(N<-by(X<-utf8ToInt(gsub('[^a-z]','',scan(,''),T)),G<-X%%32,length),L<-intToUtf8(by(X,G,tail,1),T))[order(N,L)],sep='')

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, 158 bytes

```
¬t=(c=Dict();C=Dict();for i=eachmatch(r"\w",t);l=i.match;k=lowercase(l);c[k]=get(c,k,0)+1;C[k]=l;end;*(["$v$(C[k])" for (v,k)=sort([(v,k) for (k,v)=c])]...))

```

Original ungolfed version with same logic:

```
function password(text)
    letter_counts = Dict()
    cases = Dict()

    for i in eachmatch(r"\w", text)
        letter = i.match[1]
        letter_key = lowercase(letter)
        letter_counts[letter_key] = get(letter_counts, letter_key, 0) + 1
        cases[letter_key] = letter
    end

    sorted_counts = sort([(value, key) for (key, value) in letter_counts])

    return string(["$v$(cases[k])" for (v,k) in sorted_counts]...)
end

```

Try it online!

# Answer
> 0 votes
# Perl 6, ~~86~~ 82 bytes

```
{[~] flat map *[0,2],sort map {+$^b,$^a,$b[*-1]},kv classify &lc,.comb: /<alpha>/}

```

# Answer
> 0 votes
## Rebol, 149, 146 bytes

```
f: func[s][l: charset[#"a"- #"z"#"A"- #"Z"]rejoin sort/skip collect[parse sort s[any[copy t[copy o l any o](keep length? t keep last t)| skip]]]2]

```

Try it online!

Ungolfed:

```
f: func [s] [
    l: charset[#"a" - #"z" #"A" - #"Z"]
    rejoin sort/skip collect [
        parse sort s [
            any [
                copy t [copy o l any o] (keep length? t keep last t)
                | skip
            ]
        ]
    ] 2
]

```

Example usage in Rebol console:

```
>> f "Kitkat Tango"
== "1g1i1n1o2a2k3T"

>> f "Database Partitions Task"
== "1b1D1e1k1n1o1P1r2i3s4T5a"

>> f "12$*34^!"
== ""

```

---
Tags: code-golf, word-puzzle
---


title: Number of coins needed to make change

text:
# Question
Title: Number of coins needed to make change
Relatable scenario: I'm going to the store to buy a single item, but only have a $100k bill. As a result, I need exactly $99,979 in change, and in the fewest coins/bills possible because I'm quite obviously a very practical person.

The denominations of these coins/bills follow the hyperinflation sequence: \\$1, 2, 5, 10, 20, 50, 100, 200\\$, and so on.

(I'd proposed an OEIS sequence for this, but the first 100k terms are identical to another one so it got rejected)

**Task:**

Given an amount of money as a nonnegative integer, such as \\$73\\$, return the minimum number of coins/bills needed to total to that amount. In this example, it would be \\$4\\$. The coins required would be \\$50 + 20 + 2 + 1\\$.

As per the standard rules for , you can also choose to return all terms up to an inputted index, or return a (potentially infinite) lazy list or generator that represents the whole sequence.

**Test cases:**

```
0       0
1       1
2       1
3       2
4       2
5       1
6       2
7       2
8       3
9       3
10      1
11      2
20      1
30      2
37      4
90      3
111     3
147     5
1000    1
1002    2
1010    2
12478   9

```

**Other:**

This is , so shortest answer in bytes per language wins!

# Answer
# JavaScript (ES7),  ~~36~~  35 bytes

Similar to other answers. Using a Black Magic formula instead of a lookup table.

```
f=n=>n&&(n%10)**29%3571%4+f(n/10|0)

```

Try it online!

Here is a script that looks for \\$(p,m)\\$ pairs such that \\$(n^p\bmod m)\bmod 4=a\_n\\$ for all \\$n\in\[0..9\]\\$.

It's worth noting that this code takes IEEE-754 precision errors into account. So the results are correct but the math is wrong.

With exact values, we could do instead:

$$\big((n \bmod 10)^{18}\bmod 4011\big)\bmod 4$$

Or better yet, as suggested by @dingledooper:

$$\big((n \bmod 10)^{55}\bmod 767\big)\bmod 4$$

For instance, in Python:

### Python 2, 40 bytes

```
f=lambda n:n and(n%10)**55%767%4+f(n/10)

```

Try it online!

---

# JavaScript (ES7), 71 bytes

Expects the amount as a string.

A naive recursive approach that subtracts one coin/bill at a time.

```
n=>(k=10**n.length,g=t=>+n?k>n?g(t,k/=~++i%3?2:2.5):g(t+1,n-=k):t)(i=0)

```

Try it online!
> 14 votes

# Answer
# Husk, ~~11~~ ~~9~~ 8 bytes

*Edit: -1 byte thanks to caird coinheringaahing*

```
ṁo⌈½ṁB5d

```

Try it online!

```
       d   # get the digits
    ṁB5    # convert them all to base-5
           # (this gives a 1 for each 5-denomination coin needed,
           # as well as the leftover for each digit.
           # We'll need 2 more coins for those with leftover 3 or 4,
           # and only one more coin if the leftover is 1 or 2.)
ṁo         # So: map across all the base-5 digits
   ½       # dividing each of them by 2
  ⌈        # and then getting the ceiling;
           # and finally output the sum

```
> 14 votes

# Answer
# Haskell, <sup>~~55~~~~41~~</sup> 40 bytes

* -1 byte thanks to xnor, for using a string instead of the hard-coded list.

```
a=0:tail[i+read[j]|i<-a,j<-"0112212233"]

```

Try it online!

`a` is the infinite sequence.

## How?

It's not hard to find the recursive formula $$ a(n)=a\left(\left\lfloor\frac{n}{10}\right\rfloor\right)+a(n \operatorname{mod} 10) $$ with the base cases for \\$n\in\\{0,\ldots,9\\}\\$ given by $$ \[0,1,1,2,2,1,2,2,3,3\]. $$

This means that the infinite list `a` satisfies the equality

```
a==[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]]

```

Now, Haskell is magical, but not magical enough to compute `a` from the definition

```
a=[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]]

```

However, giving the first term explicitly is enough:

```
a=0:tail[i+j|i<-a,j<-[0,1,1,2,2,1,2,2,3,3]]

```

The 40-bytes code above is equivalent to this, but shorter.
> 10 votes

# Answer
# , ~~64~~ ~~52~~ ~~50~~ 45 bytes

```
sum(c(1,2,1:3)[.6*utf8ToInt(scan(,""))-28.4])

```

Try it online!

Same strategy as Delfad0r's Haskell answer, which is nicely explained.

First, `scan(,"")` reads in input as a string. Then, `utf8ToInt(...)-48` takes a string of digits and converts it to a vector of integer digits. This works out shorter than taking input as an integer and splitting it into digits.

The digits from 0 to 9 then have to be mapped to the vector `c(0,1,1,2,2,1,2,2,3,3)`. To do this, consider the vector `a=c(1,2,1,2,3)`. For digit `d`, `a[.4+d*.6]` is the value we want. This uses the fact that when calling a non-integer index in a vector (say `a[2.8]`), R rounds down the index (here `a[2]`), and also the fact that `a[0]` returns `NULL` which will be ignored in the sum.

Putting this operation with the operation to convert the string to digits simplifies to `.6*utf8ToInt(...)-28.4`.

Note that Dominic van Essen has a solution of (currently) the same length with a different strategy.
> 8 votes

# Answer
# , ~~54~~ ~~51~~ ~~47~~ 45 bytes

*Edit: converted to console input instead of a full function to try not to fall behind Robin Ryder's answer*

```
d=utf8ToInt(scan(,''))-48;sum(d>0,d>5,d%%5>2)

```

Try it online!
> 8 votes

# Answer
# Jelly, 7 bytes

```
Db5FHĊS

```

Try it online!

~~Steals~~ Ports Dominic Van Essen's Husk answer, be sure to upvote that!

## How it works

```
Db5FHĊS - Main link. Takes an integer n on the left
D       - Convert to digits
 b5     - Convert each digit to base 5
   F    - Flatten
    H   - Halve each
     Ċ  - Ceiling of each
      S - SUm

```

---

# Jelly, 11 bytes

```
Dị“FȮŀO’D¤S

```

Try it online!

## How it works

```
Dị“FȮŀO’D¤S - Main link. Takes n on the left
D           - Convert n to digits
         ¤  - Create a nilad:
  “FȮŀO’    -   Compressed integer: 1122122330
        D   -   To digits
 ị          - Index into the digits of this integer
          S - Sum

```
> 7 votes

# Answer
# 05AB1E, 11 bytes

```
S<•δ¬Èº•sèO

```

Try it online!

Same approach as my Jelly answer.

## How it works

```
S<•δ¬Èº•sèO - Program. Input: n
S           - Cast n to digits
 <          - Decrement
  •δ¬Èº•    - Compressed integer: 1122122330
        sè  - Using n's digits, index into the digits of 1122122330
          O - Sum

```

Kudos to Kevin Cruijssen's excellent integer compressor!
> 6 votes

# Answer
# Husk, 23 bytes

```
L◄Lfo=⁰Σ↑o≤⁰LṖƒ(+İ€m*10

```

Try it online!

Extremely slow past 11.

## Explanation

```
L◄Lfo=⁰Σ↑o≤⁰LṖƒ(+İ€m*10
              ƒ(        create an infinite list using:
                 İ€     currency denomination builtin: [1,1/2,1/5,...200]
                +       plus
                   m*10 the input mapped to *10
                        this gives [1,1/2,...100] + 10*([1,1/2,...100] + (10*[1,1/2,...100]...))
             Ṗ          powerset(unordered)
        ↑o≤⁰L           take all sequences which have length ≤ input
                        this makes sure everything till [1]*n is in the list
   fo=⁰Σ                filter out the ones which do not sum to the input
 ◄L                     maximum element by length
L                       take the length

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 39 bytes

```
⌈.4#⌉-⌊#/5⌋&@*IntegerDigits/*Tr

```

Try it online!
> 4 votes

# Answer
# Python 2, 37 bytes

```
f=lambda n:n and n/5%2-n%5/-2+f(n/10)

```

Try it online!

Uses a formula rather than a lookup table for each digit. `n/5%2` counts the five-cent coin, and subtracting `-n%5/-2` is equivalent to adding `(n%5+1)/2` for the one- and two-cent coins.

```
n%10      0 1 2 3 4 5 6 7 8 9
-----------------------------
n/5%2     0 0 0 0 0 1 1 1 1 1
0-n%5/-2  0 1 1 2 2 0 1 1 2 2
Total     0 1 1 2 2 1 2 2 3 3

```
> 4 votes

# Answer
# C (gcc), 39 bytes

```
f(n){n=n?f(n/10)+""[n%10]:0;}

```

Try it online!

# JavaScript (Node.js), 37 bytes

```
f=n=>n&&+"0112212233"[n%10]+f(n/10|0)

```

Try it online!
> 3 votes

# Answer
# Python 2, 48 bytes

```
f=lambda x:x and int("0112212233"[x%10])+f(x/10)

```

Try it online!

49 bytes in Python 3 because you'd need `//` for floor division.
> 3 votes

# Answer
# Charcoal, 13 bytes

```
ＩΣ⭆Ｓ⭆↨Ｉι⁵Ｌ↨λ³

```

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

```
   Ｓ            Convert input to a string
  ⭆             Map over characters and join
       ι        Current character
      Ｉ         Cast to integer
     ↨  ⁵       Convert to base 5
    ⭆           Map over base 5 digits and join
           λ    Current digit
          ↨ ³   Convert to base 3
         Ｌ      Take the length
 Σ              Take the (digital) sum
Ｉ               Cast to string
                Implicitly print

```

Table of base 5 digit to base 3 length:

```
Decimal Base 3 Length
0       []     0
1       [1]    1
2       [2]    1
3       [1, 0] 2
4       [1, 1] 2

```
> 3 votes

# Answer
# Vyxal, `d`, 5 bytes

```
5vτ½⌈

```

Try it Online!

A port of the Jelly answer which is a port of short husk answer.

## Explained

```
5vτ½⌈
5vτ   # convert each digit of the input to base 5
   ½  # halve each item in that list (halving vectorises all the way down)
    ⌈ # ceiling each item in that list
      # -d deep sums the list and implicitly outputs

```
> 3 votes

# Answer
# Retina 0.8.2, ~~20~~ 15 bytes

```
.
$*1,
1{5}|11?

```

Try it online! Link includes test cases. Explanation:

```
.
$*1,

```

Convert each digit to unary separately.

```
1{5}|11?

```

Count the number of 5s, 2s and 1s needed to make each digit.
> 2 votes

# Answer
# 05AB1E (legacy), 7 bytes

```
5δв˜;îO

```

Port of *@Dominic van Essen*'s Husk answer, so make sure to upvote him as well!

Uses the legacy version of 05AB1E to get rid of a leading `S` that would be required in the new version of 05AB1E in this case, due to the way the `δ` acts on strings/integers.

Try it online or verify all test cases.

**Explanation:**

```
 δ       # Map each digit in the (implicit) input-integer to:
5 в      #  A base-5 list
   ˜     # Flatten this list of lists
    ;    # Halve each integer
     î   # Ceil each float
      O  # Sum the integers in the list together
         # (after which the result is output implicitly)

```
> 1 votes

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


title: 99 bugs in the code

text:
# Question
Title: 99 bugs in the code
# 99 bugs in the code

The adaption of "99 bottles of beer on the wall" for computer science where the bugs increase instead of the bottles decreasing is often re-posted around the internet. Example T-Shirt Here.

I think it'll be interesting to see potential recursion and random number generation across a huge variety of languages and finding the most efficient ways to do it.

There's a fair few other challenges to do with 99 bottles of beer but none seem to have an increasing and decreasing number!

# Challenge

Your program or function should take no input and then print

> 99 bugs in the code
>
> 99 bugs in the code
>
> Take one down and patch it around
>
> X bugs in the code
>
> (blank line)

Where X is the previous integer minus 1 plus a random integer in the range \[-15,5\].
You can merge the minus 1 into the random integer, hence allowing the range \[-16,4\].
Ranges can be exclusive, so minus one plus (-16,6) or (-17,5).

The random integers don't have to be evenly distributed they just have to all be possible.

The program always starts with 99 bugs.

You can ignore the grammatical error of "1 bugs".

The program should stop when the number of bugs is 0 or negative and print

> 0 bugs in the code

There should never be a negative number of bugs. The ending should look like

> Y bugs in the code
>
> Y bugs in the code
>
> Take one down and patch it around
>
> 0 bugs in the code
>
> (blank line)
>
> 0 bugs in the code

A trailing new line is acceptable.

* Your code can be a full program or a function.
* There is no input.
* The output should be to stdout or returned.
* Warnings/errors in logs/STDERR are okay as long as STDOUT has the required text. See here for more info.

This is code-golf so the shortest code in bytes wins.

# Example Output

Paste bin example output rigged for -11 bugs each time

# Answer
> 19 votes
# , ~~182~~ ~~140~~ ~~138~~ 135 bytes

```
n=99;while(n)cat(n,b<-" bugs in the code
",n,b,"take one down and patch it around
",n<-max(0,n-sample(21,1)+5),b,"
",c(n,b)[!n],sep="")

```

Try it online!

~~while being reasonably good at random number generation, R is terrible at strings and printing.~~ *JayCe found about a billion bytes, and continues to find new ways to golf this!*

# Answer
> 13 votes
# Java 8, ~~161~~ 160 bytes

```
v->{String s="",t=" bugs in the code\n";for(int i=99;i>0;s+=i+t+i+t+"Take one down and patch it around\n"+((i-=Math.random()*21+4)<0?0:i)+t+"\n");return s+0+t;}

```

-1 byte thanks to *@JonathanAllan*.

Try it online.

**Explanation:**

```
v->{                   // Method with empty unused parameter and String return-type
  String s="",         //  Result-String, starting empty
         t=" bugs in the code\n";
                       //  Temp-String we use multiple times
  for(int i=99;i>0;    //  Start `i` at 99, and loop as long as it's larger than 0
    s+=                //   Append to the result-String:
       i+t             //    The first line of the verse
       +i+t            //    The second (duplicated) line of the verse
       +"Take one down and patch it around\n"
                       //    The third line of the verse
       +((i-=Math.random()*21-4)
                       //    Decrease `i` by a random integer in the range [-16, 4]
         <0?0:i)       //    If `i` is now negative, set it to 0
        +t+"\n");      //    And append the fourth line of the verse
  return s             //  Return the result,
         +0+t;}        //  appended with an additional line for 0 at the very end

```

# Answer
> 10 votes
# PowerShell, ~~137~~ ~~135~~ ~~133~~ 131 bytes

```
$b=' bugs in the code';for($a=99;$a){,"$a$b"*2;"Take one down and patch it around";$a+=-16..4|Random;if($a-lt0){$a=0}"$a$b`n"}"0$b"

```

Try it online!

The "bugs in the code" section is saved into `$b` for later use. Sets `$a` to `99`, enters a `for` loop on `$a`. First we create an array of two strings `," "*2`, with the string being the `"X bugs in the code"`.

Next is just the string `"Take one down and patch it around"`. Then we increment `$a` by selecting a `Random` integer from the range `[-16,4]`. After that, we clamp `$a` to be at minimum zero using an if `if($a-lt0){$a=0}`. Then the string `"Y bugs in the code"`.

Finally, after the loop is finished, we put the string `"0 bugs in the code"` onto the pipeline. All of those strings are gathered from the pipeline, and an implicit `Write-Output` gives us newlines between them for free.

*Saved two bytes using a `for` loop instead of a `while` loop.*
*Saved two bytes by moving `$b` onto its own section.*
*Saved two bytes thanks to Adrian Blackburn.*

# Answer
> 8 votes
# JavaScript (Node.js), 127 bytes

```
f=(i=99,t=` bugs in the code
`)=>i>0?i+t+`Take one down and patch it around
`+((i+=0|Math.random()*21-15)<0?0:i)+t+`
`+f(i):0+t

```

Try it online!

---

# Explanation :

```
f = (                                          // start of our recursive function
    i=99,t=` bugs in the code                 // parameters, 1. num bugs , 2. text
`)                                           // using string literal end text with \n
=>                                          // start function
    i > 0 ?                                // if i is greater than 0
        i + t +                           // return value of i, value of t and
    `Take one down and patch it around   // and this text
    `                                   // + new line
    + (( i +=                          // and add
        0|Math.random()*21-15) < 0 ?  // remove decimal from value obtained by multiplying
                                     // random number (between 0 and 1) multiplied by 21
                                    // and then subtracting 15 from it
                                   // if that value is less than 0
        0 :                       // add 0 to i
        i                        // otherwise add value of i
        )                       // end the parenthesis
    + t                        // add value of t to that
    + `\n`                    // along with a new line
    + f(i)                   // and repeat the process (this is recursive)
    :                       // if i > 0 condition not met then
        0 + t              // return 0 + t. Zero is there so the last line can be
                          // repeated

```

---

Thanks to @tsh for the idea of recursion and implementation (saved some bytes)

Any suggestions to golf this further are welcome.

# Answer
> 7 votes
# Python 3, ~~156~~ 138 bytes

Thanks to Jonathan's Python 2 answer for the `id` trick

```
r=n=99
z='%d bugs in the code\n'
while n:x=n;r+=id(r);n-=min(n,r%21-4);print((z%x)*2+'Take one down and patch it around\n'+z%n)
print(z%n)

```

Try it online!

### Explanation:

```
r=n=99       #Initialise r and n to 99
z='%d bugs in the code\n'  #Save n
while n:     #Loop while n is not 0
    x=n      #Save value of n
    r+=id(r) #Modify value of r, which changes the hash value
    n-=min(n,r%21-4)  #Change n's value by a random number between 4 and -16
    print((z%x)*2+'Take one down and patch it around\n'+z%n)   #Print the message
print(z%n)  #And print the final line

```

# Answer
> 7 votes
# 05AB1E, 59 bytes

```
99[Ð16(4ŸΩ+¾‚{θ©3F“ÿ±À€†€€ƒË“Š}“ƒ¶€µ„‹€ƒš¡€•…¡“ªsõ®>#®]sDŠ»

```

Try it online!

# Answer
> 6 votes
# JavaScript, ~~189~~ ~~176~~ ~~168~~ 162 bytes

```
f=(x=99)=>{c=console.log;m=Math;a=` bugs in the code
`;c(x+a+x+a+"Take one down and patch it around"+(x=m.max(x+m.ceil(m.random()*21-15),0))+a)
x?f(x):c(`
`+x+a)}

```

Try it online!

Thanks for Muhammad Salman for the missing `console.log` replacement, and for Oliver for the x test improvement

Thanks for l4m2 for golfing this by 8 bytes

# Answer
> 6 votes
# Charcoal, 81 bytes

```
≔⁹⁹θ≔”⧴"pWº⁴tＳn/{yBⅈ⁺”ζＷ›θ⁰«×²﹪ζθ”↶0⪫\`3+¤⸿Zν(z¬hＬÀＴj'ZXεＰraF”≧⁺⁻⁴‽²¹θ﹪ζ×θ›θ⁰¶»﹪ζ⁰

```

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

```
≔⁹⁹θ

```

Start with 99 bugs in the code.

```
≔”⧴"pWº⁴tＳn/{yBⅈ⁺”ζ

```

Save the compressed string "%d bugs in the code\n".

```
Ｗ›θ⁰«

```

Repeat while there are a positive number of bugs remaining.

```
×²﹪ζθ

```

Print the number of bugs in the code twice.

```
”↶0⪫\`3+¤⸿Zν(z¬hＬÀＴj'ZXεＰraF”

```

Print "Take one down and patch it around".

```
≧⁺⁻⁴‽²¹θ

```

Add a random number of bugs between -17 (exclusive) and 4 (inclusive).

```
﹪ζ×θ›θ⁰

```

Print the number of bugs remaining, or 0 if negative.

Leave a blank line between verses.

```
»﹪ζ⁰

```

After the last verse, print 0 bugs in the code again.

# Answer
> 6 votes
# COBOL (GnuCOBOL), ~~317~~ ~~294~~ ~~279~~ ~~270~~ ~~269~~ ~~249~~ ~~248~~ 247 bytes

### Using `go to` statements: 247 bytes

```
data division.working-storage section. 1 i pic S99 value 99.procedure division.a.perform b 2 times display"Take one down and patch it around"compute i=4+i- random*21 set i to max(0,i)perform b display""if i>0 go to a.b.display i" bugs in the code"

```

Try it online!

**Ungolfed**

```
data division.                     <-- Define the variables we want to use
working-storage section.           <-- Define global variables used in this
                                       program

1 i pic S99 value 99.              <-- Define variable i with datatype signed
                                       numeric and with two digits

procedure division.                <-- Define our program

a.                                 <-- Define label a, to jump to
    perform b 2 times              <-- Execute the procedure called 'b'
                                       twice, see below
    display "Take one down and..." <-- Display this sentence
    compute i =
        4 + i - (random * 21)      <-- Subtract from i some random value
    set i to max(0,i)              <-- If i is negative, then assign 0 to i

    perform b                      <-- Execute the procedure 'b'
    display ""                     <-- Display an empty string; needed
                                       because of the blank line
    if i > 0                       <-- If i is still greater than 0, then
                                       we're not done yet
        go to a.                   <-- and we'll jump back to 'a'

b.                                 <-- Define procedure called 'b'.
    display i " bugs in the code"  <-- Display the value of i and then the
                                       given string literal

```

### Using the `perform` statement as loop control: 269 bytes

```
data division.working-storage section. 1 i pic S99 value 99.procedure division.perform until i=0 perform a 2 times display"Take one down and patch it around"compute i=4+i-(random*21)if i<0 compute i=0 end-if perform a display""end-perform.a.display i" bugs in the code"

```

Try it online!

**Ungolfed**

```
data division.                     <-- Define the variables we want to use
working-storage section.           <-- Define global variables used in this
                                       program

1 i pic S99 value 99.              <-- Define variable i with datatype signed
                                       numeric and with two digits

procedure division.                <-- Define our program

perform until i = 0                <-- Perform the following code until i = 0
    perform a 2 times              <-- Execute the procedure called 'a' twice,
                                       see below

    display "Take one down and..." <-- Display this sentence
    compute i =
        4 + i - (random * 21)      <-- Subtract from i some random value

    if i < 0                       <-- if i < 0
        compute i=0                <-- then assign 0 to i
    end-if
    perform a                      <-- Execute the procedure 'a'
    display ""                     <-- Display an empty string; needed because
                                       of the blank line
end-perform.

a.                                 <-- Define procedure called 'a'.
    display i " bugs in the code"  <-- Display the value of i and then the
                                       given string literal

```

Note: the last sentence is still printed, because COBOL executes the whole program, and after the `perform until` loop it "falls-through" the label *a*, executing its statements. This behaviour is similar to a `switch case` without `break`.

---

* Thanks to tail spark rabbit ear, 1 byte has been saved by using the intrinsic function `max` instead of an `if` statement.
* Thanks to tail spark rabbit ear, 1 byte has been saved by replacing the `compute` by the `set` statement.
* Thanks to raznagul, 1 byte has been saved by rewriting the formula for the new number of bugs.

---

*PS: The numbers are not exactly displayed as required, but COBOL is not that good at auto-converting numbers to a pretty textual representation.*

# Answer
> 5 votes
# Octave, ~~149~~ 148 bytes

Saved one byte by changing `randi(21)` and `%i` to `21*rand` and `%.f`. `%.f` ensures the output is a float with zero decimals (i.e. and integer).

Inserted a bunch of line breaks instead of commas and semicolons to ease readability. It feels wrong, but it's not longer than the one-liner.

```
x=99;do(p=@(i)printf('%.f bugs in the code\n',i))(x)
p(x)
disp('Take one down and patch it around')
p(max([0,x+=21*rand-17]))
disp('')until x<1
p(0)

```

Try it online!

### Explanation:

```
x=99;               % Initialize the number of bugs to 99
do ...  until x<1   % Loop until the number of bugs is less than 1
 (p=@(i)printf('%.f bugs in the code\n',i))(x)  % Create a function handle p that takes
                                                % the number of bugs as input and outputs
                                                % the string x bugs ... \n
 p(x)                % Call that function with the same number of bugs to get two lines
 ,disp('Take on down and patch it around')       % Outputs that line, including a newline
 ,p(max([0,x+=21*rand-17]))                    % Call p again, while updating the number
                                                 % of bugs. The number of bugs will be
                                                 % the old one plus the random number, or 0
                                                 % if it would have turned negative
 ,disp('')        % A newline
p(0)              % Finally, the last single line.

```

Using `p((x+=21*rand-17)*(x>0)` instead of `max` saves a byte, but the last line outputs `-0 bugs ...` instead of `0 bugs`. It works with `randi(21)-17`, but then it's the same length as the one above. Try it online!

# Answer
> 5 votes
# Python 2, 151 bytes

Nice trick `j=i+max(-i,randint(-16,4))` by Jo King, exploiting allowed uneven distribution

Saved couple bytes thanks to Mnemonic

```
from random import*
i,s=99,'bugs in the code\n'
while i:j=max(0,i+randint(-16,4));print i,s,i,s,'Take one down and patch it around\n',j,s;i=j
print i,s

```

Try it online!

# Answer
> 4 votes
# C,  ~~169~~  165 bytes

*Thanks to @ceilingcat for saving four bytes!*

```
*s=" bugs in the code";f(i,j){for(i=99;i>0;i=j)printf("%d%s\n%d%s\nTake one down and patch it around\n%d%s\n\n",i,s,i,s,(j=i+rand()%19-15)<0?0:j,s);printf("0%s",s);}

```

Try it online!

# Answer
> 4 votes
# VBA: ~~212~~ 163 Bytes

This solution is based on the one by Chronocidal posted yesterday. This my first post and I don't have enough reputation to comment on his post.

This revision contains two enhancements.

1. Using `While/Wend` instead of `For/Next` saves a few characters.
2. Calling a Sub named with a single character is shorter than `GoSub` and the `Exit Sub` and `Return` lines needed to support it.

Edit:
3. Removed whitespace and characters that the VBA editor will automatically add back in. See Tips for golfing in VBA
4. Added suggestions by @EricF, then saw his paste bin algorithm was even smaller so I replaced my algorithm with his and removed whitespace. A key change was appending `vbLF` to the output string so `Debug.Print` did not have to be called as often. Kudos to EricF.

---

```
Sub b()
s=" bugs in the code"&vbLf
c=99
While c
Debug.? c &s &c &s &"Take one down and patch it around
c=c+5-Int(Rnd()*20)
c=IIf(c<0,0,c)
Debug.? c &s
Wend
End Sub

```

This was a fun challenge. If you know of an online interpreter like TIO for VB6/VBScript/VBA please leave a comment.

*If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out `Option Explicit`. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).*

# Answer
> 4 votes
# LaTeX, ~~368~~ ~~304~~ ~~293~~ ~~287~~ ~~245~~ 240 bytes

While not really competitive compared to the other programs in terms of bytes, I just wanted to see how to do this in LaTeX.

```
\documentclass{proc}\newcount\b\b99\usepackage[first=-16,last=5]{lcg}\def~{\the\b\ bugs in the code\\}\def\|{\loop~~Take one down and patch it around\\\rand\advance\b\value{rand}\ifnum\b>0 ~\\\repeat\b0 ~\\~}\begin{document}\|\end{document}

```

More readable:

```
\documentclass{proc}               %shortest document class
\newcount\b                        %short variable name
\b 99                              %set the value to 99
\usepackage[first=-16,last=5]{lcg} %random number generator
%\the prints the value of the variable behind it
%\def is shorter than \newcommand and can redefine commands
\def~{\the\b\ bugs in the code\\}
\def\|{                            %the function
    \loop
        ~
        ~
        Take one down and patch it around\\
        %\rand creates a counter named rand and
        %stores the random value in it
        \rand \advance\b\value{rand}
        %if the counter is smaller than 0, it becomes 0
        \ifnum\b>0
            ~ \\                  %extra newline as required
    \repeat
    %if b is equal or smaller than 0, set it to 0
    \b 0
    ~ \\                          %then print like normal
    %extra print at the end
    ~
}
\begin{document}
    \|                             %calling the function
\end{document}

```

**Improvements** (per edit):

1. "x bugs in the code" is now a function instead of 4 lines
2. Rewrote the `\if` clause for the `\repeat` as a `\else`
3. Apparently `\value{b}=x` works for initialisation but not in the loop (instead of `\setcounter{b}{x}`)
4. Apparently `\relax` should be used for point 3, but that can also be achieved by inserting a space. Removed the `\else`, used TeX commands instead of LaTeX as these are shorter, and replaced `\'` by `~`.
5. Some code didn't need to be relaxed for some reason.

# Answer
> 3 votes
## SAS, 210 bytes

```
%macro t;%let b=bugs in the code;%let a=99;%do%until(&a<=0);%put&a &b;%put&a &b;%put Take one down, pass it around;%let a=%eval(&a-%sysfunc(ranbin(0,20,.3))+4);%if &a<0%then%let a=0;%put&a &b;%put;%end;%mend;%t

```

Ungolfed:

```
%macro t;
%let b=bugs in the code;
%let a=99;
%do%until(&a<=0);
  %put &a &b;
  %put &a &b;
  %put Take one down, pass it around;
  %let a=%eval(&a-%sysfunc(ranbin(0,20,.3))+4);
  %if &a<0%then%let a=0;
  %put &a &b;
  %put;
%end;
%mend;
%t

```

Can save a few bytes if warnings in the log are permitted (put the `&a` into the `&b` macro variable, but that generates an initial warning).

# Answer
> 3 votes
# C (gcc), 141 137 bytes

I used preprocessor macros for great justice (warning: TV Tropes)

```
#define _(a)printf("%d bugs in the code\n"#a,i)
f(i){for(i=99;_(),i;i+=rand()%21-16,i*=i>0,_(\n))_(Take one down and patch it around\n);}

```

Try it online!

# Answer
> 3 votes
# Clean, ~~245~~ 234 bytes

```
import StdEnv,Math.Random,System.Time,System._Unsafe,Text
f[n,v:l]b|n>0=n<+b<+n<+b+"Take one down and patch it around\n"<+max 0v<+b+"\n"+f[v:l]b=0<+b

```

#

```
f(scan(+)99[n rem 20-16\\n<-genRandInt(toInt(accUnsafe time))])" bugs in the code\n"

```

Try it online!

# Answer
> 3 votes
## PHP, 126 bytes

Run on the command line, using `php -r 'code here'`:

```
$b=" bugs in the code
";for($x=99;print$x.$b,$x;)echo"$x{$b}Take one down and patch it around
",$x-=min($x,rand(-4,16)),"$b
";

```

# Answer
> 3 votes
## ABAP, 295 bytes

...because why the heck not!

```
REPORT z.DATA:a(16),c TYPE qfranint.a = 'bugs in the code'.data(b) = 99.WRITE:/ b,a.WHILE b > 0.WRITE:/ b,a,/'Take one down and patch it around'.CALL FUNCTION
'QF05_RANDOM_INTEGER' EXPORTING ran_int_max = 21 IMPORTING ran_int = c.b = b + c - 17.IF b < 1.b = 0.ENDIF.WRITE:/ b,a,/,/ b,a.ENDWHILE.

```

It's certainly not competitive compared to other languages, but I even managed to slim it down from 330 bytes I wrote initially, so I count it as a personal win.

Since ABAP doesn't allow lines longer than 255 characters, I had to replace a space with a line break. On Windows this initially increased the size to 296 bytes due to CRLF, but it runs fine with just the LF in there. ABAP sure requires many spaces though, so this is no big deal.

WRITE simply dumps text the GUI, so I guess that is kind of like stdout? I could probably save some bytes here by using a structure or table, but due to how SAP handles mixed structures (containing chars and numbers) the approach I imagined would only work on non-Unicode systems... Which I personally consider a no-go, despite having access to both.

The function module for random numbers is the only one I could find in our system, I suppose there could be one with a shorter name or parameters. No idea!

**More or less readable code, comments included:**

```
REPORT z.
  "Define a (text) and c (random)
  DATA: a(16),
        c TYPE qfranint. "A stupid data type for a random INT

  "This is shorter than using VALUE (saves 3 bytes)
  a = 'bugs in the code'.
  "This is slightly shorter than doing ',b TYPE i' and 'b = 99'. (saves 2 bytes)
  data(b) = 99.

  "first line has to be outside of loop due to our exit condition (saved me ~5 bytes)
  WRITE: / b,a. "\n xx bugs in the code

  WHILE b > 0.
    WRITE: / b,a, "\n xx bugs in the code
    /'Take one down and patch it around'.

    "This ridiculous function for random numbers...
    "To save some bytes, I leave ran_int_min at it's default
    "of 1, and set the max to 21 instead, from which I remove
    "17 later on, resulting in a range of [-16,4]
    "Compare:
    "   ' - 17'              =  5 bytes
    "   ' ran_int_min = -16' = 18 bytes
    "(saves 13 bytes)

    CALL FUNCTION 'QF05_RANDOM_INTEGER'
        EXPORTING ran_int_max = 21
        IMPORTING ran_int = c.

    "Maximum number of bugs added:     4 = 21 - 17
    "Maximum number of bugs removed: -16 =  1 - 17
    b = b + c - 17.

    IF b <= 0.
        b = 0.
    ENDIF.

    WRITE: / b,a,/,/ b,a. "\nxx bugs in the code\n\nxx bugs in the code
  ENDWHILE.

```

Thanks for the challenge!
*To my boss: Please don't fire me, I'm just educating myself!*

# Answer
> 3 votes
# Python 2,  ~~138 134 133 131~~  127 bytes

**-1** Thanks to Jo King (rearrange so as to use the logic `bugs-=min(bugs,randomNumber)` rather than `bugs=max(0,bugs-randomNumber)`). This allowed the force-quit using a division by zero error, saving a further **6** bytes!

```
r=n=99
t="bugs in the code\n"
while 1:r+=id(r);b=n;n-=min(n,r%21-4);print b,t,1/b|b,t,"Take one down and patch it around\n",n,t

```

**Try it online!**

# Answer
> 3 votes
# C#, ~~184~~ 181 bytes

My first Code Golf answer!

(Based on Java answer from @Kevin Cruijssen)

```
Func<String>c=()=>{String s="",t=" bugs in the code\n";for(int i=99;i>0;s+=i+t+i+t+"Take one down and patch it around\n"+((i-=new Random().Next(21)-4)<0?0:i)+t+"\n");return s+0+t;};

```

Try it online!

# Answer
> 2 votes
# T-SQL, 188 bytes

```
DECLARE @ INT=99,@b CHAR(18)=' bugs in the code
'a:PRINT CONCAT(@,@b,@,@b,'Take one down and patch it around
')SET @+=5-22*RAND()IF @<0SET @=0PRINT CONCAT(@,@b,'
')IF @>0GOTO a;PRINT '0'+@b

```

SQL allows returns inside string literals, so that helps.

`CONCAT()` does an implicit conversion to text so I don't have to worry about `CAST` or `CONVERT`.

# Answer
> 2 votes
# Jelly, 61 bytes

```
;“,Ȥm46Ṛṛ⁽eɼḞF»
ÇȮ“"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8»20X+_«¥©17Ç⁷®ßÇ®?
99Ç

```

A niladic link which also works as a full program.

**Try it online!** (output is flushed after execution is complete but it prints paragraph by paragraph)

### How?

```
;“,Ȥm46Ṛṛ⁽eɼḞF» - Link 1, helper to construct count-text: number
 “,Ȥm46Ṛṛ⁽eɼḞF» - compressed string (list of characters) = " bugs in the code\n"
;               - concatenate the number with that list of characters

ÇȮ“"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8»20X+_«¥©17Ç⁷®ßÇ®? - Link 2, print stuff: number
Ç                                         - call the last Link (1) as a monad
 Ȯ                                        - print and yield that
                                          - ...at this point that is then printed again
                                          -    implicitly due to the start of a new leading
                                          -    constant chain below
  “"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8»                  - compressed string (list of characters)
                                          -     = "Take one down and patch it around\n"
                                          - ...once again an implicit print, same reason
                        20                - twenty
                          X               - random int from [1,20]
                           +              - add the left argument, the number
                                17        - seventeen
                              ¥           - last two links as a dyad:
                             «            -   minimum (of rand[1,20]+n and 17)
                            _             -   subtract
                               ©          - copy this newNumber to the register
                                  Ç       - call last Link (1) as a monad = f(newNumber)
                                          - here we get another implicit print, same reason
                                   ⁷      - a new line character
                                          - yet another implicit print, same reason
                                    ®     - recall newNumber from the register
                                        ? - if...
                                       ®  - ...condition: recall from register again
                                          -               (i.e. if non-zero)
                                     ß    - ...then: call this Link (2) as a monad
                                          -          = Link 2(newNumber)
                                      Ç   - ...else: call the last Link (1) as a monad
                                          -          = Link 1(0) (since newNumber=0)

99Ç - Main Link: no arguments
99  - yep, you guessed it, ninety nine
  Ç - call the last Link (2) as a monad

```

# Answer
> 2 votes
# JavaScript, 138 bytes

```
_=>(I=i=>`Take one down and patch it around
${l=(i>0?i:0)+` bugs in the code
`}
`+l+l+(i>0&&I(i+Math.random()*21-15|0)))(99).slice(55,-25)

```

```
f=

_=>(I=i=>`Take one down and patch it around
${l=(i>0?i:0)+` bugs in the code
`}
`+l+l+(i>0&&I(i+Math.random()*21-15|0)))(99).slice(55,-25)

console.log(f())
```

# Answer
> 2 votes
# QB64, 134 bytes

From my brother.

```
S$="bugs in the code":I=99:WHILE I>0:?I;S$:?I;S$:?"Take one down and patch it around":I=I+INT(RND*21)-15:I=-(I>0)*I:?I;S$:?:WEND:?I;S$

```

# Answer
> 2 votes
# Pyth, ~~94~~ 92 bytes

```
J99WJ%jb[K"%d bugs in the code"K"Take one down and patch it around"Kk)[JJ=JeS,Z+J-O21 16;%KZ

```

Try it online

---

*Previous version: 94 bytes*

```
J99WJp%jb[K"%d bugs in the code"K"Take one down and patch it around"K)[JJ=JeS,Z+J-O21 16)b;%KZ

```

# Answer
> 2 votes
# Perl, 132 bytes

```
$c=" bugs in the code
";for($i=99;$i>0;$i+=~~rand(21)-16){print$t.$/,($t=$i.$c)x2,"Take one down and patch it around
"}print"0$c
"x2

```

# Answer
> 2 votes
## VBA: ~~225~~ 233 Bytes

```
Sub b()
For c = 99 To 0 Step -1
GoSub d
GoSub d
Debug.Print "Take one down and patch it around"
c = c + 5 - Int(rnd() * 20)
If c < 0 Then c = 0
GoSub d
Debug.Print
Next c
Exit Sub
d:
Debug.Print c & " bugs in the code"
Return
End Sub

```

**{EDIT}** *Added the missing `rnd()*`*

**Notes:**
Uses `GoSub` to print the triplicated line, because it's slightly shorter than assigning the line to a variable and `Debug.Print`ing it.
`Debug.Print` without any arguments prints an empty line (no need for a Null or an empty string) A `WorksheetFunction.Max` line would be too long, so I used an "if less than" to prevent negatives.

## With indentation and comments

```
Sub b()
    For c = 99 To 0 Step -1
        GoSub d '"# bugs in the code"
        GoSub d '"# bugs in the code"
        Debug.Print "Take one down and patch it around"
        c = c + 5 - Int(rnd() * 20)
        If c < 0 Then c = 0 'Non-negative
        GoSub d '"# bugs in the code"
        Debug.Print
    Next c
    Exit Sub
d: 'This is our GoSub bit
    Debug.Print c & " bugs in the code"
    Return
End Sub

```

# Answer
> 2 votes
# Bash, ~~182~~ ~~178~~ ~~151~~ 149 bytes

```
i=99;b=" bugs in the code";a(){ echo $i$b;};while((i>0));do a;a;echo Take one down and patch it around;i=$[i-$RANDOM%21+4];((i<0))&&i=0;a;echo;done;a

```

Try it online!

**Ungolfed**

```
i=99;                             # Var i as current number of bugs
b=" bugs in the code";            # b to shortcut our string

a() {                             # Define function 'a'
    echo $i$b;                    # to shortcut displaying or number of bugs
};

while((i>0)); do                  # Repeat as long as var i is greater than 0
    a;a                           # Execute 'a' twice
    echo Take one down and...     # Display some bugs taken down
    i=                            # Assign the following value to $i:
      $[i-$RANDOM%21+4]           # i minus a random value between -4 and 16
                                  #     $RANDOM is a bash builtin function to generate a
                                  #     pseudorandom value between 0 and 32767 inclusive.
                                  #     I have applied a modulo 21 to get 21 possible
                                  #     values. We take advantage of the allowed uneven
                                  #     distribution.

    ((i<0))                       # Perform the expression i < 0
           &&                     # and assign 0 to i only if the previous
             i=0                  # command completed successfully

    a                             # Execute 'a'
    echo                          # Display a blank line
done
a                                 # Execute 'a'

```

*Thanks to muru and Sam Dean for their improvements, they saved me 31 bytes.*

# Answer
> 2 votes
# Ruby: 149 bytes

```
n=99;f=" bugs in the code\n";loop{puts"#{n}#{f}"*2+"Take one down and patch it around\n";(n+=rand -16..4)>0?puts("#{n}#{f}\n"):break};puts"0#{f}\n"*2

```

Should work in pretty much any version of Ruby \>= 1.8

I think it might be possible to optimise the strings a bit more, but in general I'm pretty pleased with it - in particular the combo assignment/comparison/break statement and the abuse of optional brackets.

Note: the output technically has two trailing newlines; if that needs to be accounted for then it goes up by 4 characters.

# Answer
> 2 votes
# Zsh, 133 bytes

```
b="%d bugs in the code
";for ((n=99;n;)){printf $b$b"Take one down and patch it around
$b
" n n n-=RANDOM%21-4,n=n\>0\?n:0};printf $b

```

Try it online!

---

This takes advantage of a few zsh features.

* the alternative loop form: `while list; do list; done` can be written as `while list {list}`
* If a format specifier in `printf` is numeric, the corresponding argument is evaluated as an arithmetic expression. So:
    + we get the value of `n` for free without using a `$`
    + `n -= RANDOM % 21 - 4, n = n > 0 ? n : 0` is again evaluated without having to use `$((...))`, `$[...]` or similar. The `>` and `?` had to be escaped.
    + The `printf $b` at the end evaluates an empty argument as 0 for `%d`.
* Word splitting on parameter expansion is off by default, so I do not have to quote `$b` anywhere.
    + This allows allows me to write `$b$b"Take..."` instead of `"$b${b}Take..."`.

---

* Saved a few bytes by using actual newlines instead of `\n`, and `for((n=99;n;))` instead of `n=99;while ((n))`.

# Answer
> 2 votes
# javascript: 142

```
i=99
t=` bugs in the code
`;s='';while(i){s+=i+t+i+t+`Take one down and patch it around
`;i+=4-Math.random()*20|0;i=i<0?0:i;s+=i+t+`
`}s+=i+t;

```

Try it online

# Answer
> 2 votes
# C (GCC), 138 bytes

```
i=99;main(v){for(;i-v--;printf("%d bugs in the code\n%s",i*=i>0,v?v+1?i-=rand()%21-4,"\n":"Take one down and patch it around\n":""))v%=3;}

```

Note: I managed to get it down to 141 bytes by myself (no external help); later I saved three bytes by applying a technique that ErikF used (i\*=i\>0 instead of i=i\<0?0:i). My original solo version:

```
i=99;main(v){for(;i-v--;printf("%d bugs in the code\n%s",i=i<0?0:i,v?v+1?i-=rand()%21-4,"\n":"Take one down and patch it around\n":""))v%=3;}

```

# Answer
> 2 votes
# Python 3, 187 bytes

```
from random import randint as r
p=print;b=99
def l(x): p(x if x > 0 else 0,"bugs in the code.")
while b > 0: l(b);l(b);p("Take one down and patch it around.");b+=r(-16,4);l(b);p("")
l(0)

```

So it turns out that dealing with IO/Random in Haskell is a nightmare, so changed the solution to Python. First attempt, not too great :( But at least it's working.

# Answer
> 2 votes
# Python 3, ~~199~~ ~~191~~ 171 bytes

-8 bytes thanks to @Stephen
-20 bytes thanks to @Jo King

```
import random
x=99
l="bugs in the code\n"
p=print
while x>0:p(f"{x} {l}"*2+"Take one down and patch it around");x=max(0,x+random.choice(range(-16,5)));p(f"{x} {l}")
p(0,l)

```

Try it online!

# Answer
> 2 votes
# SAS 153 146 145 bytes

```
data;a=99;b='bugs in the code';do while(a>0);put a b/a b;put'Take one down and patch it around';a=max(a+int(ranuni(0)*20-16),0);put a b/;end;run;
```

The original version is Joe's answer, thanks him.

# Answer
> 2 votes
# Julia 0.7, ~~123~~ 115 bytes

```
~n="$n bugs in the code"
!(n=99,m=max(0,n-rand(-4:16)))=n>0?[~n;~n;"Take one down and patch it around";~m;"";!m]:~n

```

Try it online!

`!()` returns a vector of strings (for each line)

# Answer
> 1 votes
# Japt, ~~124~~ ~~123~~ ~~121~~ ~~120~~ ~~116~~ ~~110~~ 107 bytes

```
U=U||99P=` Þï  e ¬¸`OpU+POpU+P  Op`Take e Üµ, p®  ÂÐ` U=Mr0-15,5 +U-1U=Uc  (U>0 ?(OpU+P+R ,ßU  :Oo0+P

```

Try it online!

# Answer
> 1 votes
# Python 3, 144 bytes

```
from pylab import*
s='bugs in the code\n'
X=99
while X>0:i=randint(-16,5);print(X,s,X,s,'\ntake one down and patch it around',max(X+i,0),s);X+=i

```

# Answer
> 1 votes
# Red, 166 163 bytes

```
b: 99 forever[if b > 1[print[b t:{bugs in the code}s:"^/"b t
s{Take one down and patch it around}]if
0 > b: b + 4 - random 20[prin[0 t s s 0 t]break]print[b t s]]]

```

Try it online!

## More readable:

```
b: 99
t: {bugs in the code}
s: "^/"
forever [
    if b > 1 [
        print [ b t s b t s {Take one down and patch it around} ]
        if 0 > b: b + 4 - random 20 [
            prin [ 0 t s s 0 t ]
            break
        ]
        print [ b t s ]
    ]
]

```

# Answer
> 1 votes
# .COM opcode, 137 bytes

```
0000h: BE 63 00 E8 3B 00 85 F6 75 01 C3 E8 33 00 B2 61
0010h: CD 21 0F C7 F0 F7 26 87 01 01 D6 83 EE 10 73 02
0020h: 31 F6 E8 1C 00 B2 5E CD 21 EB D8 99 F7 36 85 01
0030h: 85 C0 74 05 52 E8 F3 FF 5A B4 02 80 CA 30 CD 21
0040h: C3 89 F0 E8 E5 FF B4 09 BA 4D 01 EB F1 20 62 75
0050h: 67 73 20 69 6E 20 74 68 65 20 63 6F 64 65 0D 0A
0060h: 24 54 61 6B 65 20 6F 6E 65 20 64 6F 77 6E 20 61
0070h: 6E 64 20 70 61 74 63 68 20 69 74 20 61 72 6F 75
0080h: 6E 64 0D 0A 24 0A 00 15 00

        org 100h

        mov si, 99
lp:     call put2
        test si, si
        jnz @f
            ret
        @@:
        call put2
        mov dl, str2 - 256
        int 33
        rdrand ax
        ;mov ax, 65536*14/21+1
        mul [twentyone]
        add si, dx
        sub si, 16
        ;lea si, [esi+edx-16]
        jnc @f
            xor si, si
        @@:
        call put2
        mov dl, str2 - 256 - 3
        int 33
        jmp lp

put1:   cwd
        div [ten]
        test ax, ax
        jz @f
            push dx
            call put1
            pop dx
        @@:
        mov ah, 2
        or dl, 48
int33:  int 33
        ret

put2:   mov ax, si
        call put1
        mov ah, 9
        mov dx, str1
        jmp int33

str1:   db ' bugs in the code', 13, 10, '$'
str2:   db 'Take one down and patch it around', 13, 10, '$'
ten     dw 10
twentyone dw 21

```

# Answer
> 1 votes
# Japt `-R`, ~~83~~ ~~79~~ ~~75~~ 73 bytes

Includes a trailing newline

```
#c
` Þï  e ¬¸
`
@§T}a@Np[UVUV`ìÇ¦ÓnÓlp®äNh
`qÊ¸TwU±Gn#ö¹V]¬ÃpViT

```

Test it

---

## Explanation

```
#c                                         :99
\n                                         :Assign to variable U
`...`                                      :The compressed string " bugs in the code\n"
\n                                         :Assign to variable V
        [UVUV                  V]          :Build an array with U as the 1st & 3rd elements,
                                           : V as the 2nd, 4th & 7th
                                           : and the following as the 5th & 6th:
             `...`                         :  The compressed string "Takeloneldownlandlpatchlitlaround\n"
                  qÊ                       :   Split on "l"
                    ¸                      :   Join with spaces
                      w       ¹            :  Maximum of
                     T                     :   0 and
                           #               :    21
                             ö             :    Random number in the range [0,21)
                          n                :    Subtract
                         G                 :    16
                       U±                  :    Add to U
                                 ¬         :Join to a string
      Np                                   :Push to N, initially an empty array
@  }a@                            Ã        :Repeat until
 §T                                        :  U is less than or equal to 0
                                   p       :Push
                                    ViT    :  V prepended with 0
                                           :Implicitly join with newlines and output

```

# Answer
> 1 votes
# Ruby, 128 bytes

```
N=99
def f;puts"#{N} bugs in the code"end
(f;f
puts"Take one down and patch it around"
N-=[N,15-rand(21)].min
f
puts)while 0<N
f

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 175 bytes

```
var s="";var r=new Random();for(int p=99;p>0;){var d=" bugs in the code\n";s+=p+d+p+d+"Take one down and patch it around\n";p+=r.Next(-17,5);s+=(p>0?p:0)+d+"\n";}return s;

```

Try it online!

C# uses a class for randomizing. Without the "Random" object, the response would be around 148 bytes. Using a for loop instead of a while loop removes one byte. using "new Random.Next()" will not work, since creating multiple Random objects within a loop wont make the Randomizer actually random.

# Answer
> 1 votes
# BLZ 2.6, 155 bytes

```
b=99
while b>0
n={text.newline}
s=" bugs in the code"+n
p=(x->print(99+s+99+s+"Take one down and patch it around"+n+b+s))
p()
b=b+random(-16,5)
end
b=0
p()

```

Reminds me that I need to make "\n" a newline so I can save some of those characters from {text.newline}

# Answer
> 1 votes
# Clojure, 192 188 bytes

```
#(loop[b 99](def s"bugs in the code")(printf"%s %s\n%s %s\nTake one down and patch it around\n"b s b s)(def n(max(+ b(rand-int 21)-16)0))(println n s"\n")(if(= n 0)(println n s)(recur n)))

```

Try it online!

## Explanation

```
#(loop [b 99] ; Initialize a loop with b=99
  (def s "bugs in the code") ; Define a variable s that equals "bugs in the code"
  (printf "%s %s\n%s %s\nTake one down and patch it around\n" b s b s) ; Prints
    ;    "99 bugs in the code
    ;     99 bugs in the code
    ;     Take one down and patch it around" with the correct formatting.
  (def n (max (+ b (rand-int 21) -16) 0)) ; Let n = max(b+<some random number between -16 and 4 inclusive>, 0) This prevents negative numbers by replacing them with 0
  (println n s "\n") ; Prints "<n> bugs in the code" followed by an extra newline
  (if (= n 0) ; If n equals 0
    (println n s) ; Prints "<n> bugs in the code"
    (recur n))) ; Otherwise run the loop again with b=n

```

# Answer
> 1 votes
# Dart, ~~173~~ 169 bytes

```
import'dart:math';f({n=99,m=' bugs in the code\n'}){while(n>0){print('$n$m$n$m\Take one down and patch it around');n=n+Random().nextInt(20)-16;n=n<0?0:n;print('$n$m');}}

```

Try it online!

Almost competing with other Java-like languages for once

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