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!


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

  • 1
    \$\begingroup\$ Related: 1 2 (difference: in this challenge the output can be arbitrarily long). \$\endgroup\$ – user202729 May 29 '18 at 14:16
  • 16
    \$\begingroup\$ A more realistic scenario would be if the sign of the random number was flipped! \$\endgroup\$ – Stewie Griffin May 29 '18 at 15:21
  • 9
    \$\begingroup\$ I am disappointed, that the requirements don't include that the program must have a bug once a negative number is encountered, like crashing, overflowing to max int or similar ;). \$\endgroup\$ – allo May 30 '18 at 9:58
  • 3
    \$\begingroup\$ "The random integers don't have to be evenly distributed they just have to all be possible." reminded me of xkcd.com/221 \$\endgroup\$ – Ivo Beckers May 30 '18 at 12:33
  • 2
    \$\begingroup\$ It's a shame 99 has no random number generation. \$\endgroup\$ – Jonathan Allan May 30 '18 at 21:07

46 Answers 46


R, 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

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!


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.


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
                       //    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
  • \$\begingroup\$ Seems you are not using r for anything? \$\endgroup\$ – O.O.Balance May 29 '18 at 15:12
  • 1
    \$\begingroup\$ Removing ,r appears to still work: Try it online! \$\endgroup\$ – Kamil Drakari May 29 '18 at 15:45
  • \$\begingroup\$ @O.O.Balance Oops.. Not sure why I got that there.. >.> Thanks for noticing. \$\endgroup\$ – Kevin Cruijssen May 29 '18 at 17:13
  • 1
    \$\begingroup\$ i-=...+5 saves one (although I think the range should be [-16 4] not [-15,5]) \$\endgroup\$ – Jonathan Allan May 31 '18 at 0:35
  • 1
    \$\begingroup\$ @O.O.Balance yes r is not used, because he is using java ;-) \$\endgroup\$ – Anand Rockzz May 31 '18 at 5:44

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.

  • \$\begingroup\$ You could replace $a=(0,$a)[$a-gt0]; with If($a-lt0){$a=0} for a couple of bytes \$\endgroup\$ – Adrian Nov 30 '18 at 6:06
  • \$\begingroup\$ @AdrianBlackburn Thanks! \$\endgroup\$ – AdmBorkBork Nov 30 '18 at 13:28

JavaScript (Node.js), 127 bytes

f=(i=99,t=` bugs in the code
`)=>i>0?i+t+`Take one down and patch it around

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.

  • \$\begingroup\$ Use recursion save some bytes \$\endgroup\$ – tsh May 30 '18 at 3:16
  • 1
    \$\begingroup\$ Why was 0+ removed? It seems to be required output. \$\endgroup\$ – tsh May 30 '18 at 8:55
  • \$\begingroup\$ @tsh : Is it ? I didn't read that part. \$\endgroup\$ – Muhammad Salman May 30 '18 at 9:14

05AB1E, 59 bytes


Try it online!


Charcoal, 81 bytes


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


Start with 99 bugs in the code.


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.


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.

  • \$\begingroup\$ Need that final repeated "0 bugs in the code"! \$\endgroup\$ – Sam Dean May 30 '18 at 9:17
  • 1
    \$\begingroup\$ @SamDean Sorry I'd overlooked that, fixed. \$\endgroup\$ – Neil May 30 '18 at 9:42

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)

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

  • \$\begingroup\$ I'm no node expert, but I believe "The program should stop when the number of bugs is 0 or negative" means you need x<=0?console.log("\n"+0+a):f(x) at the end. \$\endgroup\$ – NoOneIsHere May 29 '18 at 14:38
  • 1
    \$\begingroup\$ Ok, sorry. One more thing: if you need to recurse in an anonymous function, you need to explicitly name it (+2 bytes) \$\endgroup\$ – NoOneIsHere May 29 '18 at 14:42
  • 1
    \$\begingroup\$ can't that last "console.log" be replaced with "c"? \$\endgroup\$ – Sam Dean May 29 '18 at 14:51
  • 1
    \$\begingroup\$ Also @NoOneIsHere is right. You do need that f declaration. Voted down till updated to fix that. (Also my link needs an update too) \$\endgroup\$ – Muhammad Salman May 29 '18 at 14:57
  • 2
    \$\begingroup\$ The point I'm trying to make here is your code doesn't work if the function isn't called f, which you can't assume. \$\endgroup\$ – NoOneIsHere May 29 '18 at 14:58

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!

  • 1
    \$\begingroup\$ You can save a byte by using j=max(0,i+randint(-16,4)). \$\endgroup\$ – user48543 May 29 '18 at 15:19
  • \$\begingroup\$ Also, it's 'bugs in the code'. \$\endgroup\$ – user48543 May 29 '18 at 15:20
  • \$\begingroup\$ Using 0 to compare wiil make not all numbers possible. Thanks for nothing 'the' :D \$\endgroup\$ – Dead Possum May 29 '18 at 15:23
  • \$\begingroup\$ Same trick as my answer, 151 bytes \$\endgroup\$ – Jo King May 29 '18 at 15:24
  • \$\begingroup\$ They're not possible anyway. You're not allowed to go below 0. \$\endgroup\$ – user48543 May 29 '18 at 15:24

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)
disp('Take one down and patch it around')
disp('')until x<1

Try it online!


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!


Python 3, 156 138 bytes

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

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)

Try it online!


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

COBOL (GnuCOBOL), 317 294 279 270 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=i-(random*21- 4)if i<0 compute i=0 end-if perform a display""end-perform.a.display i" bugs in the code"

Try it online!


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

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 patch it around"   <-- Display this sentence
    compute i = i -                <-- Subtract from i some random value
        (random * 21 - 4)

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

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.

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

  • 1
    \$\begingroup\$ Hi. Welcome to PPCG. \$\endgroup\$ – Muhammad Salman May 31 '18 at 10:10
  • \$\begingroup\$ I think that minus 4 should be plus 4. I'm guessing you went for (i-(rand-4) == (i-rand+4). But there's no brackets so the sign needs to change. Also can the signs of the numbers be removed or is that a feature of the language? But nice work with a non gold friendly language! \$\endgroup\$ – Sam Dean May 31 '18 at 10:29
  • 1
    \$\begingroup\$ @SamDean Thanks! I fixed that mistake. I got to admit that the actual random calculated was inspired from Kevin Cruijssen's answer. But he uses a compound assignment operator (-= in i-=Math.random()*21-4), which implies parenthesis around the whole righthand operand. I forgot to make them explicit, but it is now fixed, I think. \$\endgroup\$ – MC Emperor May 31 '18 at 11:49
  • \$\begingroup\$ @MCEmperor looks good to me now! \$\endgroup\$ – Sam Dean May 31 '18 at 12:21
  • \$\begingroup\$ Can't you use +4 and save the brackets? \$\endgroup\$ – raznagul Jun 1 '18 at 13:08

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.

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
While c
Debug.? c &s &c &s &"Take one down and patch it around
Debug.? c &s
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).

  • 4
    \$\begingroup\$ Welcome to the site! \$\endgroup\$ – Wheat Wizard Jun 2 '18 at 3:50
  • 1
    \$\begingroup\$ You can get it down to 197 characters if you combine strings, use c instead of c>0 as your While condition, and use c=Iif(c<0,0,c) instead of If c<0 [...]: pastebin.com/nFGtGqdE \$\endgroup\$ – ErikF Jun 4 '18 at 19:33

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
        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
            ~ \\                  %extra newline as required
    %if b is equal or smaller than 0, set it to 0
    \b 0 
    ~ \\                          %then print like normal
    %extra print at the end
    \|                             %calling the function

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.
  • 1
    \$\begingroup\$ Welcome to PPCG. \$\endgroup\$ – Muhammad Salman Jun 2 '18 at 15:17
  • \$\begingroup\$ Welcome to PPCG! I haven't run your code but shouldn't it be \ifnum\value{b}<1 rather than <0? \$\endgroup\$ – JayCe Jun 4 '18 at 14:01
  • \$\begingroup\$ @JayCe: It doesn't really matter, once b is 0 it escapes the loop anyway. It may just be less intuitive that when b is 0 the else case is printed indeed, but effectively there is no difference I think. \$\endgroup\$ – Simon Klaver Jun 4 '18 at 15:37
  • \$\begingroup\$ @JayCe shortened the code, now it doesn't matter anymore ;) \$\endgroup\$ – Simon Klaver Jun 4 '18 at 16:49

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!

  • \$\begingroup\$ I think that limit's inclusive. It should be %21. \$\endgroup\$ – S.S. Anne Mar 18 '20 at 0:43

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


%macro t;
%let b=bugs in the code;
%let a=99;
  %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; 

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).

  • \$\begingroup\$ A few others have warnings so I'll go with they are allowed. \$\endgroup\$ – Sam Dean May 30 '18 at 9:20

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

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:

  "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]
    "   ' - 17'              =  5 bytes
    "   ' ran_int_min = -16' = 18 bytes
    "(saves 13 bytes)

        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.
    WRITE: / b,a,/,/ b,a. "\nxx bugs in the code\n\nxx bugs in the code

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


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!

  • \$\begingroup\$ Any chance you can remove the quotes at the start and end? \$\endgroup\$ – Sam Dean May 30 '18 at 9:15
  • 1
    \$\begingroup\$ @SamDean Oh that's just a compiler option I forgot about. I'll throw that in. \$\endgroup\$ – Οurous May 30 '18 at 21:59

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!

  • 1
    \$\begingroup\$ Welcome to PPCG :) \$\endgroup\$ – Shaggy Jun 5 '18 at 8:56

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!


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.


JavaScript, 138 bytes

_=>(I=i=>`Take one down and patch it around
${l=(i>0?i:0)+` bugs in the code


_=>(I=i=>`Take one down and patch it around
${l=(i>0?i:0)+` bugs in the code



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$

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

Jelly, 61 bytes


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)


;“,Ȥ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

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

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
Next c
Exit Sub
Debug.Print c & " bugs in the code"
End Sub

{EDIT} Added the missing rnd()*

Uses GoSub to print the triplicated line, because it's slightly shorter than assigning the line to a variable and Debug.Printing 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"
    Next c
    Exit Sub
d: 'This is our GoSub bit
    Debug.Print c & " bugs in the code"
End Sub
  • 1
    \$\begingroup\$ That's a very efficient way to do random numbers! \$\endgroup\$ – Sam Dean May 31 '18 at 13:40
  • \$\begingroup\$ @SamDean Not sure how I forgot to include the rnd() * in there - I think I was busy tallying up if it was less characters to Dim c% (i.e. "c is an Integer") and drop the Int() \$\endgroup\$ – Chronocidal May 31 '18 at 14:31
  • \$\begingroup\$ haha no worries! Nice to see a VBA answer as I haven't used it in years! \$\endgroup\$ – Sam Dean May 31 '18 at 14:50

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!

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!

  • \$\begingroup\$ Turns out I don't need to create tuples at all. \$\endgroup\$ – Jonathan Allan May 30 '18 at 23:25
  • \$\begingroup\$ 133 bytes \$\endgroup\$ – Jo King Jun 1 '18 at 7:59
  • \$\begingroup\$ @JoKing Thanks! (I really should've spotted that since it's more like what I do in my Jelly answer.) \$\endgroup\$ – Jonathan Allan Jun 1 '18 at 8:13
  • 2
    \$\begingroup\$ @JoKing ...which means we can force quit with a division by zero error to save --two-- six more :) \$\endgroup\$ – Jonathan Allan Jun 1 '18 at 8:28

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.

  • \$\begingroup\$ Hello, and welcome to PPCG! We do count trailing newlines, but if it works on Linux you can only count the \n (no \r). \$\endgroup\$ – NoOneIsHere May 31 '18 at 17:05
  • \$\begingroup\$ @NoOneIsHere Thanks :) I've updated my answer to clarify - I was referring to newlines on the output because the question specifies that having one is acceptable, but I wasn't sure about two. \$\endgroup\$ – DaveMongoose Jun 1 '18 at 8:37
  • \$\begingroup\$ I see. I think that's fine \$\endgroup\$ – NoOneIsHere Jun 1 '18 at 17:09

Zsh, 133 bytes

b="%d bugs in the code
";for ((n=99;n;)){printf $b$b"Take one down and patch it around
" 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)).
  • \$\begingroup\$ I think it should be -4. "-=" looks like its compound so it does the +4 first then subtracts it all. \$\endgroup\$ – Sam Dean Jun 1 '18 at 12:04
  • \$\begingroup\$ @SamDean oops, corrected. \$\endgroup\$ – muru Jun 1 '18 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.