86
\$\begingroup\$

Write a program that outputs the lyrics to 99 Bottles of Beer, in as few bytes as possible.

Lyrics:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

....

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

Rules:

  • Your program must log to STDOUT or an acceptable alternative, or be returned from a function (with or without a trailing newline).
  • Your program must be a full, runnable program or function.
  • Languages specifically written to submit a 0-byte answer to this challenge are allowed, just not particularly interesting.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

  • This is different from the output by HQ9+ or 99. Any answers written in these languages will be deleted.

As this is a catalog challenge, this is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64198; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 36670; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
25
  • 14
    \$\begingroup\$ Whoever closevoted this, the other one is a popularity contest... \$\endgroup\$ – TheDoctor Nov 18 '15 at 15:19
  • 22
    \$\begingroup\$ This is a subtask of the Create an HQ9+ Interpreter golf. \$\endgroup\$ – Geobits Nov 18 '15 at 15:25
  • 4
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I haven't VTCd it yet, still deciding how I feel about that. Either way, I think some answers (or snippets from them) from the other can be directly copy/pasted while remaining competitive, which is a usual test for dupe-ness. \$\endgroup\$ – Geobits Nov 18 '15 at 15:54
  • 13
    \$\begingroup\$ Note that quartata had already sandboxed a 99BB catalog several weeks ago and was planning to post it. \$\endgroup\$ – Alex A. Nov 18 '15 at 17:07
  • 14
    \$\begingroup\$ @GamrCorps Please do not unnecessarily change the rules after the challenge has started. None of the characters in the output should be optional. \$\endgroup\$ – feersum Nov 18 '15 at 18:42

162 Answers 162

1
\$\begingroup\$

Emacs Lisp, 290 Bytes

(defun b (n) (format "%d bottle%s of beer" n (if (eq n 1) "" "s")))
(defun bw (n) (concat (b n) " on the wall"))
(defun l (n) (concat (bw n) ", " (b n) ".\nTake one down, pass it around, " (bw (- n 1)) ".\n" (if (> n 1) (l (- n 1)) "Go to the store and buy some more.\n")))
(message (l 99))
\$\endgroup\$
3
  • 1
    \$\begingroup\$ You forgot to “go to the store and buy some more”. \$\endgroup\$ – manatwork Nov 23 '15 at 12:19
  • \$\begingroup\$ The first line would be shorter as (defun b (n) (format "%d bottle%s of beer" n (if (> n 1) "s" ""))) \$\endgroup\$ – manatwork Nov 23 '15 at 12:31
  • \$\begingroup\$ @manatwork Thanks for the help. Updated it. \$\endgroup\$ – Lord Yuuma Nov 23 '15 at 19:20
1
\$\begingroup\$

Perl 6, 213 bytes

my$b=' bottle';my$e=' of beer';my$o=" on the wall";for 99…1 {my$c=$_~$b~'s'x?($_-1)~$e;say "Take one down and pass it around, $c$o.\n"if $++;say "$c$o, $c."};say "Go to the store and buy some more, 99{$b}s$e$o."
my$b=' bottle';
my$e=' of beer';
my$o=" on the wall";
for 99…1 {
  my$c=$_~$b~'s'x?($_-1)~$e;
  say "Take one down and pass it around, $c$o.\n"if $++;
  say "$c$o, $c."
};
say "Go to the store and buy some more, 99{$b}s$e$o."
\$\endgroup\$
1
\$\begingroup\$

Lua, 267 263 bytes

q=" bottle"r=q.."s"s=" of beer"t=" on the wall"u="\nTake one down and pass it around, "v="\nGo to the store and buy some more, "w=r..s for n=99,1,-1 do io.write(n,w,t,", ",n,w,".",n>1 and u..n-1 ..(n>2 and w or q..s)or v.."99"..r..s,t,".\n\n")w=(n>2 and w or q..s)end

I didn't see lua under the answers yet, only golflua, correct me if im wrong.

Explatation:

q=" bottle"     -- assigning parts of the text to variables in as
r=q.."s"        -- long pices as it's practical
s=" of beer"
t=" on the wall"
u="\nTake one down and pass it around, "
v="\nGo to the store and buy some more, "
w=r..s          -- bracause r..s/r,s repeats 4 times its shorter to assign it to w

for n=99,1,-1 do
    io.write(n,w,t,", ",n,w,".",    --putting it together

        n>1 and u..n-1              -- "take one down..." or "go to the store..."
            ..(n>2 and w or q..s)   -- "bottels or bottle..."
        or v.."99"..r..s,t,".\n\n"  -- "n-1" or "99"
    )

    w=(n>2 and w or q..s)           -- this condition repeats 2 times, it changes "bottles" to "bottle"
end

Tryout link: Execute Lua Online.

Type lua in the comandline and then dofile("99bob.lua").

Testrun:

3 bottles of beer on the wall, 3 bottles of beer.                                                                                                                   
Take one down and pass it around, 2 bottles of beer on the wall.                                                                                                    

2 bottles of beer on the wall, 2 bottles of beer.                                                                                                                   
Take one down and pass it around, 1 bottle of beer on the wall.                                                                                                     

1 bottle of beer on the wall, 1 bottle of beer.                                                                                                                     
Go to the store and buy some more, 99 bottles of beer on the wall.

I tried to write the program golfed from the start, that probably wasn't a good idia.

Edit: thanks to manatwork for r=q.."s".

\$\endgroup\$
1
  • \$\begingroup\$ Even if a Lua solution would already exist, you are welcome to add another one if the algorithm is significantly different. r=" bottles"r=q.."s". \$\endgroup\$ – manatwork Dec 23 '15 at 15:43
1
\$\begingroup\$

JavaScript ES6, 298 bytes

for(var a=[" bottles of beer","on the wall","take one down and pass it around","go to the store and buy some more",99];0<a[4];)a[0]=1===a[4]?a[0].replace("s",""):a[0],console.log(a[4]+a[0]+" "+a[1]+", "+a[4]+a[0]+". "+(1===a[4]?a[3]:a[2])+", "+(0===a[4]-1?"99"+a[0]+"s":a[4]+a[0])+" "+a[1]),a[4]--;
\$\endgroup\$
1
\$\begingroup\$

C, 256 bytes

Nice round number.

*a=" bottles of beer",*b=" on the wall",*c="Take one down and pass it around, ",d=100;main(){while(--d){printf("%d%s%s, %d%s, \n",d,a,b,d,a);d-1&&printf("%s%d%s%s. \n",c,d,a,b);}puts("Go to the store and buy some more, 99 bottles of beer on the wall.");}

With whitespace:

*a=" bottles of beer",
*b=" on the wall",
*c="Take one down and pass it around, ",
d=100;main(){
    while(--d){
        printf("%d%s%s, %d%s, \n",d,a,b,d,a);
        d-1&&printf("%s%d%s%s. \n",c,d,a,b);
    }
    puts("Go to the store and buy some more, 99 bottles of beer on the wall.");
}

Fun fact: I accidentally posted this on stack exchange and then realised a few minutes later that it was on the wrong post. Ooops.

\$\endgroup\$
1
\$\begingroup\$

SELECT., 7313057 bytes

This is not a SELECT. program that prints the 99 bottles lyrics. It is a link to a pastebin of a python program that prints a SELECT. program that prints the 99 bottles lyrics. The latter program is over 7 megabytes long, and unsuitable for posting here.

http://pastebin.ca/3372405

The program that generated this program looks like this:

######GENERATION CODE######
init(185,49,1)
makenum(10)
square()
dec()
dec()
var("99")
loop("main",computei=True,savelist=["99"])
var("i")
go(1)
makeneg1()
multiply(-1)
go(1)
fetch("99")
add(-1)
var("num")
go(1)
makeone()
add(-1)
var("curnum")
go(1)
makenum(10)
go(-1)
intdiv()
go(-5)
var("mod")
go(5)
var("div")
ifnonpositive("tens")
els("tens",True)
digitprintXY(0,0)
endif("tens")
go(1)
fetch("mod")
var("mod")
digitprintXY(6,0)
go(1)
drawstringliteral("bottle",16,0)
go(1)
fetch("curnum")
go(1)
makeneg1()
add(-1)
var("onetest")
ifzero("plural")
go(1)
drawstringliteral("of beer on the wall,",51,0)
els("plural")
go(1)
drawstringliteral("s of beer on the wall,",46,0)
endif("plural")
go(1)
fetch("div")
ifnonpositive("tens")
els("tens",True)
digitprintXY(0,13)
endif("tens")
go(1)
fetch("mod")
digitprintXY(6,13)
go(1)
drawstringliteral("bottle",16,13)
go(1)
fetch("onetest")
ifzero("plural")
go(1)
drawstringliteral("of beer.",51,13)
els("plural")
go(1)
drawstringliteral("s of beer.",46,13)
endif("plural")
go(1)
drawstringliteral("Take one down and pass it around,",0,26)
go(1)
fetch("num")
ifzero("nomore")
go(1)
drawstringliteral("No more bottles ofbeer on the wall.",0,39)
els("nomore",True)
go(1)
makenum(10)
go(-1)
intdiv()
go(-5)
var("mod")
go(5)
ifnonpositive("tens")
els("tens",True)
digitprintXY(0,39)
endif("tens")
go(1)
fetch("mod")
digitprintXY(6,39)
go(1)
drawstringliteral("bottle",16,39)
go(1)
fetch("num")
go(1)
makeneg1()
add(-1)
ifzero("plural")
go(1)
drawstringliteral("of beer on the wall.",51,39)
els("plural")
go(1)
drawstringliteral("s of beer on the wall.",46,39)
endif("plural")
input()
clear()
endif("nomore")
go(1)
endloop("main",savelist=["99"])
go(1)
drawstringliteral("No more bottles of beer on the wall,",0,0)
go(1)
drawstringliteral("no morebottles of beer.",0,13)
go(1)
drawstringliteral("Go to thestore and buy some more,",0,26)
go(1)
drawstringliteral("99 bottles of beeron the wall.",0,39)
writetofile("99bottles.sel")
\$\endgroup\$
1
\$\begingroup\$

Groovy, 213 bytes

Quite simple, probably much more golfing could be done.

b={" $it bottles of beer.\n"}
print ((99..1).collect{"$it bottle${it>1?'s':''} of beer on the wall,"+b(it)+(it>1?"Take one down and pass it around,"+b(it-1):"Go to the store and buy some more,"+b(99))}.join('\n'))
\$\endgroup\$
1
\$\begingroup\$

Jolf, 193 bytes

Try it here! I can still probably golf a byte or two...

Ώ³γhHΖp{" Ξ\x000k"γΆΆγ"% of beer on the wall, "ζγ"% of ΞΓi
"ζ?wγΆ"Ξ    ψone Ξp«Ξit ΞpDΖ"wγ"% of ΞΙon the Ξy
"p{" Ξ\x000k"wγ"Go to the Ξrand buy ΞzδΞB\x00Ε 99 Ξώof ΞΙon the Ξy"1Μw_z~1dΏH

Here's the main concept: this defines a function Ώ that returns the bottle line of an input, calls it 1 for a default, and:

Μw_z~1dΏH
Μ           maps
 w_z~1      0..99 reversed
      dΏH   with that function

Ugh that hurt my head.

\$\endgroup\$
1
\$\begingroup\$

XSLT 1.0 (no EXSLT), 845 bytes

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><template match="/"><call-template name="b"/></template><template name="b"><param name="n" select="99"/><if test="$n>0"><variable name="o"><if test="$n>1"><value-of select="$n -1"/></if><if test="$n=1">99</if></variable><variable name="p"><if test="$n>1">s</if></variable><variable name="q"><if test="$n!=2">s</if></variable><variable name="z"><if test="$n=1">Go to the store and buy some more</if><if test="$n>1">Take one down and pass it around</if></variable><variable name="w" select="concat($n,' bottle',$p,' of beer')"/><value-of select="concat($w,' on the wall, ',$w,'.&#10;',$z,', ',number($o),' bottle',$q,' of beer on the wall.&#10;')"/><call-template name="b"><with-param name="n" select="$n -1"/></call-template></if></template></transform>

With a bit less golf in it:

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <output method="text"/>
    <template match="/">
        <call-template name="b"/>
    </template>
    <template name="b">
        <param name="n" select="99"/>
        <if test="$n>0">
            <variable name="o">
                <if test="$n>1">
                    <value-of select="$n -1"/>
                </if>
                <if test="$n=1">99</if>
            </variable>
            <variable name="p">
                <if test="$n>1">s</if>
            </variable>
            <variable name="q">
                <if test="$n!=2">s</if>
            </variable>
            <variable name="z">
                <if test="$n=1">Go to the store and buy some more</if>
                <if test="$n>1">Take one down and pass it around</if>
            </variable>
            <variable name="w" select="concat($n,' bottle',$p,' of beer')"/>
            <value-of select="concat($w,' on the wall, ',$w,'.&#10;',$z,', ',number($o),' bottle',$q,' of beer on the wall.&#10;')"/>
            <call-template name="b">
                <with-param name="n" select="$n -1"/>
            </call-template>
        </if>
    </template>
</transform>

Notes

Text compression

The use of variables as abbreviations isn't as extensive as in other languages; for example, note the repetition of ' bottle' as a constant. In XSLT, the binding of an XPath expression or some arbitrary text to a variable name requires at least 29 characters of overhead, excluding the name and content itself:

<variable name="name" select="expr"/>
<variable name="name">text</variable>

Say, for example, that one would like to replace all instances of the XPath string literal ' bottle' (8 chars) with $b (2 chars). Each substitution saves 6 characters. However, given the definition <variable name="b"> bottle</variable> (38 chars), there is no net profit unless there are 7 or more such sequences to replace.

The use of the <variable/> element is limited to evaluating conditions. The version of XPath used with XSLT 1.0 does not have its own if/else constructs, but XSLT itself does, and <variable/> is necessary to retrieve the results in a useful form.

$n -1

The expression $n -1 appears twice. The space after the $n is required since - is a valid name character in XPath.

Inequalities

Wherever practical, any instance where != originally appeared was changed to use > instead. If the program counted down to 0 instead of resetting to 99 after 1, the plural check for $n would be incorrect at 0.

Tail recursion

The template named b recurses, counting the variable n down by one each time. XSLT provides looping constructs, but they are for traversing structures found in the input document. A task like this one would be substantially easier if we had an input doc containing the countdown (<doc><value>99</value><value>98</value><value>97</value>...</doc>) but at that point we're cheating (or we at least have to count the input doc in our byte count).

Run

Run using xsltproc:

xsltproc 99.xsl 99.xsl

Yes, 99.xsl is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Bad memories. At least it's good from something. \$\endgroup\$ – primo Jul 4 '16 at 18:04
1
\$\begingroup\$

C#, 267 bytes

()=>{for(int x=99;x>0;){string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n":$"Go to the store and buy some more, 99{b}s{w}."));}};

C# lambda where the output is stdout and without output. You can try it on .NetFiddle.

Code :

()=>{
    for (int x=99;x>0;) {
        string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;
        System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1
            ?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n"
            :$"Go to the store and buy some more, 99{b}s{w}."));
}};

Kudos to Igby Largeman for his solution. I think it is better than mine (shorter if it had use a lambda too).

\$\endgroup\$
1
\$\begingroup\$

Common Lisp (Lispworks), 431 bytes

(defun f()(do((i 99(- i 1)))((= i 2))(format t"~S bottles of beer on the wall, ~S bottles of beer.~%Take one down and pass it around, ~S bottles of beer on the wall.~%~%" i i(- i 1)))(format t"2 bottles of beer on the wall, 2 bottles of beer.~%Take one down and pass it around, 1 bottle of beer on the wall.~%~%1 bottle of beer on the wall, 1 bottle of beer.~%Go to the store and buy some more, 99 bottles of beer on the wall.~%"))

Ungolfed:

(defun 99-Bottles-of-Beer ()
  (do ((i 99 (- i 1))) ((= i 2))
    (format t "~S bottles of beer on the wall, ~S bottles of beer.~%Take one down and pass it around, ~S bottles of beer on the wall.~%~%" i i (- i 1)))
  (format t "2 bottles of beer on the wall, 2 bottles of beer.~%Take one down and pass it around, 1 bottle of beer on the wall.~%~%1 bottle of beer on the wall, 1 bottle of beer.~%Go to the store and buy some more, 99 bottles of beer on the wall.~%"))
\$\endgroup\$
1
\$\begingroup\$

Maple, 233 bytes

Added (unnecessary) newlines for code readability:

seq(printf("%d %s of beer on the wall,\n%d %s of beer.\nTake one down, pass it around,\n%d %s of beer on the wall.\n\n",
         i,`if`(i<>1,"bottles","bottle"),
         i,`if`(i<>1,"bottles","bottle"),
         i-1,`if`(i-1<>1,"bottles","bottle")),
i=99..1,-1);
\$\endgroup\$
1
\$\begingroup\$

R, 138 225 bytes

a='bottles of beer on the';for(i in 99:1)cat("",i,a,"wall,",i,"bottles of beer.\n","Take one down and pass it around,",i-1,a,"wall.\n\n")

a='bottles of beer on the'
for(i in 99:2)
    cat("",i,a,"wall,",i,"bottles of beer.\n","Take one down and pass it around,",i-1,a,"wall.\n\n")
cat(1,a,"wall,","1 bottle of beer.\nGo to the store and buy some more,",99,a,"wall.")

EDIT-- missed the change in the last verse.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ There's still a little bit to fix: it prints 1 bottles (<- with s) in the end of the second last verse and at the beginning of the last verse. \$\endgroup\$ – nimi Aug 5 '16 at 18:45
1
\$\begingroup\$

dc, 269 237 bytes

299si[lid1-dsi3/li3>vdn[ bottle]P1<n]sm[[s]P]sn[ of beer]so[ on the wall]sp[, ]sq46sr10ss[[Take one down and pass it around]Pq]st[d4<t[Go to the store and buy some more]P]su[99+]sv[lmxloPlpPlqPlmxloPlrPlsPluxlqPlmxloPlpPlrPlsdPP3<z]dszx

Shaved off about 30 bytes by replacing two counters w/ 1 299/3 counter; couple of unnecessary variable loads replaced w/ stack duplications; code point 46 instead of [.].

\$\endgroup\$
0
1
\$\begingroup\$

Windows Batch, 279 bytes

some optimization later

@echo off
set A=99
set B= bottle
set C=s of beer
set D= on the wall
:l
echo %A%%B%%C%%D%, %A%%B%%C%.
set/a A-=1
if %A%==1 set C=%C:~1%
if %A%==0 (echo Go to the store and buy some more, 99%B%s%C%%D%.
exit)else (echo Take one down and pass it around, %A%%B%%C%%D%.
echo.)
goto l

(my first post here, code actually from 2016)

\$\endgroup\$
2
  • \$\begingroup\$ Works, but you're not handling dropping the 's' when the bottles are singular \$\endgroup\$ – Chirishman Jun 14 '17 at 22:32
  • \$\begingroup\$ @Chirishman if %A%==1 set C=%C:~1% drops the s when bottles are singular \$\endgroup\$ – loadingnow Jun 22 '17 at 3:23
1
\$\begingroup\$

Ohm, 166 164 131 bytes (CP437)

Ohm has been updated a lot since I first posted this! Now I'm using some new features.

98@R≥î:_Θ▀a▀_Ωü▀5≡axÿx}iöܪ├┬ï°∙╟╕Ö√²┬zτα█▀_≤îΘ..ÑÑ;1Θ▀a▀1Ω▀â"190└δ*6²H"╥╨;√⌡ÄwîFδh#|a≡Ω█≡5▓Θ╕Ç≈└hÑqûI▀J
D≤y.sa·▀╖+╫Ä▀a
Θ▀Ö$k·}Qy╦▀

Try it online!

Explanation

The main wire contains a lot of compressed strings, which are delimited by .

Main wire:

98@R    Push the range 98...1.
≥î      Increment each.
:       Map each number n:
 _Θ      Call the second helper wire on n.
 ▀a▀     Push ", ".
 _Ω      Call the first helper wire on n.
 ü       Push a space.
 ▀...▀   Push "of beer.\nTake one down and pass it around, "
 _≤îΘ    Call the second helper wire on n-1.
 ..ÑÑ    Push a period and two newlines.
;       (end map)
1Θ      Call the second helper wire on 1.
▀a▀     Push ", "
1Ω      Call the first helper wire on 1.
▀...▀   Push " of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall."
J       Join the entire stack together. Implicitly output.

First helper wire:

D       Duplicate TOS.
≤       Decrement.
y       Get sign (0 or 1).
.sa·    Repeat 's' that many times.
▀╖+╫Ä▀  Push " bottle"
a       Swap top two elements.

Second helper wire:

Θ           Call the first helper wire.
▀Ö$k·}Qy╦▀  Push " of beer on the wall"
\$\endgroup\$
1
\$\begingroup\$

Ly, 272 bytes

(99)1[psu" bottles of beer on the wall, "&olu" bottles of beer.\n"&ol1-sp"Take one down and pass it around, "&olu" bottles of beer on the wall.\n"&ol1G]pu" bottle of beer on the wall, 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall."&o

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PowerShell (204 bytes)

$b='bottles of beer';$w="on the wall";$p="Take one down and pass it around";99..2|%{"$_ $b $w, $_ $b.`n$p, $($_-1) $w.`n"};$b=$b.remove(6,1);"1 $b $w, 1 $b.`nGo to the store and buy some more, 99 $b $w."

Edit (now 198 bytes as per @BradC comments, thx buddy!):

$b=' bottles of beer';$w=" on the wall";$p="Take one down and pass it around";99..2|%{"$_$b $w, $_$b.`n$p, $($_-1)$w.`n"};$b=$b.remove(6,1);"1$b$w, 1$b.`nGo to the store and buy some more, 99$b$w."
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice. I think you can save a couple of bytes by including a space at the beginning of both @b and @w. \$\endgroup\$ – BradC Aug 9 '17 at 21:10
1
\$\begingroup\$

Python, 172 bytes

a="\n%s bottles of beer on the wall"
t="\n\nTGaok et oo nteh ed oswtno raen da npda sbsu yi ts oamreo umnodr e"
d=99
while d:print(a%d*2)[:-12]+t[d==1::2]+a%(d-1or 99);d-=1

Try it online!

Explanation:

a="\n%s bottles of beer on the wall"

Stores the first line of the lyrics with a formatted argument.

t="\n\nTGaok et oo nteh ed oswtno raen da npda sbsu yi ts oamreo umnodr e"

Stores the third line. The characters at even indices make up Take one down and pass it around, and the characters at odd indices make up Go to the store and buy some more.

d=99

Counter variable for the current number of bottles, initialized to 99.

while d:                                           d-=1

In Python (and most other languages), a non-zero integer is truthy, while 0 is falsey. This while loop (although kind of hacky) repeats until d is 0, subtracting 1 from d every time.

        print             +          +            ;

I used only one print statement to save bytes, and just added multiple strings together.

             (a%d*2)[:-12]

Formats the first line with the number of bottles, repeats it, and chops off the on the wall part from the first line to make the second line.

                           t[d==1::2]

Extended slicing. Takes every other character, starting from the first character if d is not 1, but starting from the second character is d is 1. In Python, booleans can be implicitly converted to integers, so true would turn into 1, and false would turn into 0.

                                      a%(d-1or 99)

Just the first line again, except this time with one less bottle. Again, anything except 0 is truthy, so if d-1 is 0, it will give 99 instead.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Appears not to handle plural for n=1 (1 bottle of beer on the wall, 1 bottle of beer.) properly. \$\endgroup\$ – jq170727 Oct 22 '17 at 19:51
1
\$\begingroup\$

Python 3, 243 bytes

b=lambda x,y: f'{x} bottle{("","s")[x>1]} of beer{(""," on the wall")[y]}'
p=print
for i in range(99,0,-1):
 p(f'{b(i,1)}, {b(i,0)}.')
 p((f'Go to the store and buy some more, {b(99,1)}.',f'Take one down and pass it around, {b(i-1,1)}.')[i>1])

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ You should include the code in your answer. TIO has a nifty auto-formatter for PPCG if you click the link icon at the top of the page \$\endgroup\$ – Jo King Oct 23 '18 at 23:14
  • 1
    \$\begingroup\$ 225 bytes \$\endgroup\$ – Jo King Oct 23 '18 at 23:40
  • \$\begingroup\$ Hah - yeah, this is tougher than it looks :) \$\endgroup\$ – dana Oct 23 '18 at 23:51
1
\$\begingroup\$

Stax, 82 bytes

äÇEà╧<à■≤ÄâDφl%H/╢S▌╙♂Å5ε─U¥ΦioJ╦D╖↨{)X╗√╛ⁿ?fJ∞L^╧êτ╝♪p1j■GTq⌂ÿ█♀├=δMséaΦ≡&NQ▌←²╠↕

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

Powershell, 208 207 bytes

-1 byte, thanks @Veskah

inspired by Veskah's answer.

$l,$e,$o=" bottles of beer"," bottle of beer"," on the wall"
99..1|%{"$_$l$o, $_$l."
if($_---le2){$l,$e=$e,$l}"$(("Take one down and pass it around, $_","Go to the store and buy some more, 99")[!$_])$l$o.
"}

Psssh, is a swap a clever stuff? :)

\$\endgroup\$
4
  • \$\begingroup\$ It's about 19 bytes more clever than mine. \$\endgroup\$ – Veskah Oct 24 '18 at 20:28
  • 1
    \$\begingroup\$ Make that 12, you reminded me that strings can be multi-lined for free \$\endgroup\$ – Veskah Oct 24 '18 at 20:38
  • 1
    \$\begingroup\$ Looks like you can save a byte by doing if(){}"stuff". Seems if blocks don't need a newline or semi-colon after to work. \$\endgroup\$ – Veskah Oct 25 '18 at 21:10
  • \$\begingroup\$ Indeed. Thanks! \$\endgroup\$ – mazzy Oct 25 '18 at 21:13
1
\$\begingroup\$

Python 3, 288 266 253 (credit: Jo King) 251 242 bytes

b=lambda x:"%s bottle%s of beer"%(x,"s"*(x>1));o="on the wall"
for i in range(99,0,-1):print("\n%s %s, %s.\n%s"%(b(i),o,b(i),["Take one down and pass it around, %s %s."%(b(i-1),o),"Go to the store and buy some more, %s %s."%(b(99),o)][i==1]))
\$\endgroup\$
5
  • \$\begingroup\$ There is already a shorter Python 3 answer :P \$\endgroup\$ – ASCII-only Feb 28 '19 at 3:38
  • \$\begingroup\$ it doesn't work in python 3, and fails with a TypeError: 'NoneType' object is not subscriptable \$\endgroup\$ – xcrafter_40 Feb 28 '19 at 3:44
  • 1
    \$\begingroup\$ 223 \$\endgroup\$ – ASCII-only Feb 28 '19 at 4:25
  • \$\begingroup\$ 210 bytes \$\endgroup\$ – Jo King Feb 28 '19 at 4:48
  • 1
    \$\begingroup\$ except " instead of ' in ' on the wall' for consistency :P \$\endgroup\$ – ASCII-only Feb 28 '19 at 5:01
1
\$\begingroup\$

Bash, 169 bytes

eval 'a="'{1..99}' bottle$s of beer"
b="$a on the wall";f=$b,\ $a.$o;o="
Take one down and pass it around, $b.

$f";s=s';echo "$f
Go to the store and buy some more, $b."

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Assembly (MIPS, SPIM), 676 623 575 570 bytes

.data
a: .asciiz " bottle"
c: .asciiz " bottles"
e: .asciiz " of beer.\n"
f: .asciiz " of beer on the wall, "
g: .asciiz " of beer on the wall.\n"
h: .asciiz "Take one down and pass it around, "
i: .asciiz "Go to the store and buy some more, "
.text
.globl main
main:
li $8 99
li $11 1
y:
la $9 f
jal t
la $9 e
jal t
addi $8 -1
beq $8 $0 v
la $4 h
syscall
la $9 g
jal t
li $2 11
li $4 10
syscall
j y
t:
move $4 $8
li $2 1
syscall
li $2 4
beq $8 $11 q
la $4 c
j r
q:
la $4 a
r: 
syscall
move $4 $9
syscall
jr $ra
v:
la $4 i
syscall
li $8 99
la $9 g
jal t
li $2 10
syscall

Try it online!

Turns out it's actually cheaper to declare "bottle" and "bottles", as well as strings with newlines and commas directly in place, and just select between them. Also, using all the syscalls is actually cheaper than the alternative, though only because the the call pointer register is hidden. MIPS' need for newlines actually makes this surprisingly readable, if you know the opcodes. For those of you trying to decipher it, t is a function to print the variations of " bottle[s] of beer...," and $9 stores the address of the string to finish that phrase. One annoying caveat was the fact that all the verses require a newline between them, but the end cannot have two newlines (afaik). So theres a section at the end of the loop that prints a single character, which happens to be newline (decimal 10).
Edit: saved 5 bytes by using $9 instead of $10. I had originally used $9, but optimized it out, and forgot to shift the registers optimally. Also, this submission took forever because I was editing it in place.

\$\endgroup\$
1
1
\$\begingroup\$

Whitespace, 1977 1342 1013 877 bytes

(very much whitespace)

Try it online!

Finally, under 1000 bytes.

-635 bytes by manually correcting the automatic whitelips labels

-329 bytes by offsetting the letters and using 0 for spaces

-136 bytes by pushing whole sentences in one big integer and using divmod to calculate the letters.

visible code:

sssttsssttl push 99

lssssl      label main:
lsttl       call wall
lststl      call comma_space
lsttsl      call beer
lstsl       call stop_nl
ssstl       push 1
tsst        sub
lstttl      call take
lststl      call comma_space
lsttl       call wall
lstsl       call stop_nl
ssststsl    push newline (10)
tlss        printc
lslssl      jump main

lssttl      label take:
sls         dup
ltssssl     jz store
ssstststssl "T"
tlss        printc
ssstsstsstttssttsssttsststtstststststssststssttsttttttstsssstttstsssttstttssstssssttsssssssssttsstttststttsssttsssttststtstsssttttstssssttsstssssttl
            "ake one down and pass it around"
lsll        jmp print

lsssssl     label store:
sll         drop
sssttsssttl push 99
ssstssstttl "G"
tlss        printc
ssstsstststttttsttssssststtstttttssttsstsststttssssttsssttsssssttstssttstststtsttsttstssssstsssttstsstttttttssssttsttsttstststsststtssttsstssttttsttstttl
            "o to the store and buy some more"
lstl        call print
lststl      call comma_space
lsttl       call wall
lstsl       call stop_nl
lll         end

lsssl       label stop_nl:
ssststttsl  "."
tlss        printc
ssststsl    <lf>
tlss        printc
ltl         return

lssstl      label comma_space:
ssststtssl  ","
tlss        printc
sssl        0
lsll        jmp print

lsstl       label wall:
lsttsl      call beer
ssststssststssssttttttsstttsstststttstssttsstsssssstttttttsl
            " on the wall"
lsll        jmp print

lsstsl      label beer:
lststtl     call bottles
ssstssstssssstsssttsttsttstttssstttsttttsl
            " of beer"
lsll        jmp print

lsssttl     label bottles:
sls         dup bottlecount
tlst        printi
sssttsststsstssssstttsttssttttssssl
            " bottle"
lstl        call print
sls         dup bottlecount
ssstl       push 1
tsst        sub
ltststl     jz return
ssstssttl   's'

lssl        label print:
sssttstsl   26
stsstl      copy 1
stsstl      copy 1
tstt        mod
sls         dup
ltstssl     jz space
ssstssssssl push 64
tsss        add
lsstssl     label space:
ssstsssssl  push 32
tsss        add
tlss        printc
tsts        div
sls         dup
ltsstsl     jz end_print
lsll        jump print
lssstsl     label end_print:
sll         drop
lsststl     label return:
ltl         return
\$\endgroup\$
1
\$\begingroup\$

Wren, 246 bytes

System.print((99..1).map{|i|"~ on the wall, ~.\n%(i>1?"Take one down and pass it around":"Go to the store and buy some more"), %(i>1?i-1:99) bottle%(i!=2?"s":"") of beer on the wall.".replace("~","%(i) bottle%(i>1?"s":"") of beer")}.join("\n\n"))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Keg, 222 bytes

c&(c|&:.& bottle&:&1>[s] of beer on the wall\, ^(,)&:.& bottle&:&1>[s] of beer\.
^(,)&:&1=[Go to the store and buy some more|Take one down\, pass it around]\, ^(,)&:&1=[\9\9|&;:.&] bottle&:&1>[s] of beer on the wall\.

^(,

Try it online!

Explanation

  • First it stores the current counter into the accumulator
  • Then it prints all verses accordingly until the last verse
  • Finally this hard-codes the final verse

Let's see if I can get this any shorter.

\$\endgroup\$
2
  • \$\begingroup\$ Consider adding a short explanation to your answer. Code-only answers may be automatically flagged as low-quality. See other answers for examples. \$\endgroup\$ – mbomb007 Jun 6 '19 at 19:16
  • \$\begingroup\$ This can easily be shortened using the register commands. But I'm on mobile right now, so I'll probably give a shortened version later. About 12 bytes can be golfed. \$\endgroup\$ – lyxal Jan 3 '20 at 22:01
1
\$\begingroup\$

Unix TMG, 231 byte

o:parse(v)[n<143?]\o;v:b l b={3< on the wall, >3<.>*2 1< on the wall.>**};b:decimal(n)([n>1?]={<s>}|={})={2< bottle>1< of beer>};l:[--n?]={<Take one down and pass it around, >}|[n=143]={<Go to the store and buy some more, >};n:143;

Expanded:

o: parse(v) [n<143?]\o;
v: b l b = {3 < on the wall, > 3 <.> * 2 1 < on the wall.> * * };
b: decimal(n) ([n>1?]={<s>}|={}) = {2 < bottle> 1 < of beer>};
l: [--n?] = {<Take one down and pass it around, >}
 | [n=143] = {<Go to the store and buy some more, >};
n: 143;

The fact that this 1972 language uses octal instead of decimal doesn't help in this challenge 😂

\$\endgroup\$
3
  • 1
    \$\begingroup\$ If it can't be written without the newlines then the newlines should be counted. \$\endgroup\$ – S.S. Anne Feb 2 '20 at 22:21
  • \$\begingroup\$ This seems to be 235 bytes, not 231 \$\endgroup\$ – Jo King Feb 3 '20 at 1:30
  • \$\begingroup\$ @JoKing, deleted the newlines. Thanks, it works without them. \$\endgroup\$ – Andriy Makukha Feb 3 '20 at 3:57
1
\$\begingroup\$

Python, 357 339 310 bytes

After shaving off the fat to meet the expected output it didn't save as many bytes as I had expected:

def B(n):A='bottle';return A if n==1 else A+'s'
A=99
while A>=1:F='of';D=F+' beer';E='more';C=D+' on the wall';G='no '+E;H=f"Take one down and pass it around, {A-1 if A>1 else G} {B(A-1)} {C}\n"if A!=1 else f"Go to the store and buy some {E}, 99 {B(2)} {C}.";print(f"{A} {B(A)} {C}, {A} {B(A)} {D}.\n"+H);A=A-1

The following code is for code-golf output:

This is the lowest I can hit so far

def B(n):A='bottle';return A if n==1 else A+'s'
A=99
while A>=0:G='of';D=G+' beer';E='more';C=D+' on the wall';F='no '+E;print(f"{A} {B(A)} {C}, {A} {B(A)} {D}.\nTake one down and pass it around, {A-1 if A>1 else F} {B(A-1)} {C}.\n"if A!=0 else f"No {E} {B(2)} {C}, {F} {B(2)} {D}.\nGo to the store and buy some {E}, 99 {B(2)} {C}.");A=A-1

Here's the sort of bigger version:

def get_bottles(num_bottle):
    p = "bottle"

    return p if num_bottle == 1 else p + "s"


bottleNo = 99

while bottleNo >= 0:
    of = "of"
    beer = of + " beer"
    more = "more"
    botw = beer + " on the wall"
    noMore = "no " + more

    print(f"{bottleNo} {get_bottles(bottleNo)} {botw}, {bottleNo} {get_bottles(bottleNo)} {beer}.\nTake one down and "
          f"pass it around, {bottleNo - 1 if bottleNo > 1 else noMore} {get_bottles(bottleNo - 1)} {botw}.\n" if
          bottleNo != 0
          else f"No {more} {get_bottles(2)} {botw}, {noMore} {get_bottles(2)} {beer}.\nGo to the store "
               f"and buy some {more}, 99 {get_bottles(2)} {botw}.")

    bottleNo = bottleNo - 1
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You went through the trouble of making all your variables into one character, but forgot num_bottle. If you do that there as well, you could shave off a few bytes \$\endgroup\$ – GamrCorps May 31 '20 at 14:21
  • \$\begingroup\$ Good catch, that saved me 18 chars. Thanks! \$\endgroup\$ – SZT May 31 '20 at 14:26

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.