112
\$\begingroup\$

Introduction

Last year was my birthday (really!) and sadly I had to organise my own party. Well, now you know, couldn't you at least make the cake?

Challenge

Given an integer n as input, write a full program to output a birthday cake with n candles on.

Output

A piece of cake with one candle on is:

 $
 |
---
~~~
---

And a piece of cake with three candles on is:

 $ $ $
 | | |
-------
~~~~~~~
-------

I'm sure you can work it out from that

However, for input 0, you must output the following:

Congratulations on your new baby! :D

For input less than 0, you should output a candleless cake:

---
~~~
---

Nothing is allowed to be output to STDERR.

Trailing newlines and spaces are allowed.

Winning

Shortest code in bytes wins.

Leaderboard

var QUESTION_ID=57277;OVERRIDE_USER=30525;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<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="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><div id="language-list"> <h2>Winners 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><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>

\$\endgroup\$
  • 161
    \$\begingroup\$ Happy Birthday! \$\endgroup\$ – Dennis Sep 8 '15 at 6:40
  • 1
    \$\begingroup\$ is leading whitespace (for example 2 newlines) allowed for the candleless cake? \$\endgroup\$ – Level River St Sep 8 '15 at 7:16
  • 2
    \$\begingroup\$ @steveverrill Yes \$\endgroup\$ – anon Sep 8 '15 at 7:21
  • 2
    \$\begingroup\$ @PaŭloEbermann A cake of 3-width \$\endgroup\$ – anon Sep 8 '15 at 20:05
  • 4
    \$\begingroup\$ @jvriesem No. It's code for snippet. \$\endgroup\$ – sigod Sep 11 '15 at 10:54

45 Answers 45

2
\$\begingroup\$

K (ngn/k), 87 bytes

{$[x<0;3#'2_*:;x;,'/(1+2*x)#;:"Congratulations on your new baby! :D"]("  -~-";"$|-~-")}

Try it online!

edit: whoops, easy 1-byte reduction i missed


if 2 lines of whitespace is permitted where the candles would be in the x<0 case, we can save 2 bytes with

{$[x<0;3#'*:;x;,'/(1+2*x)#;:"Congratulations on your new baby! :D"]("  -~-";"$|-~-")}
\$\endgroup\$
1
\$\begingroup\$

Lua 5.2, 187 Bytes

p=print n=io.read"*n"r=string.rep
if n==0 then p"Congratulations on your new baby! :D"else
m=3*math.max(n,1)if n>0 then p(r(" $ ",n))p(r(" | ",n))end
p(r("-",m))p(r("~",m))p(r("-",m))end

Minimalistic version. I'm open for improvements :)

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

D, 276 264 257 251 249 234 231 229 bytes

import std.conv,std.range,std.algorithm,std.stdio:w=writeln;void main(string[]a){int n=a[1].to!int;n>0?"$|-~-".each!((i,c)=>repeat((i<2?" ":"")~c,i<2?n:2*n+1).joiner.w):n?"---
~~~
---".w:"Congratulations on your new baby! :D".w;}

You can test it on DPaste. Just enter desired N as command line argument on input tab. Or compile and run it in real command line: rdmd birthday_golf.d <N>

Not minified version:

import std.conv;
import std.range;
import std.algorithm;
import std.stdio;

void main(string[] args)
{
    int n = args[1].to!int;

    n > 0
        ?
            "$|-~-".each!((i, c) =>
                repeat((i < 2 ? " " : "") ~ c, i < 2 ? n : 2*n + 1).joiner.writeln)
        :
            n
                ? "---\n~~~\n---".writeln
                : "Congratulations on your new baby! :D".writeln
        ;
}
\$\endgroup\$
1
\$\begingroup\$

bash, 264 242 bytes

First of all: happy birthday, @BetaDecay :)

And now...

read n;p="printf ";e="echo ";x="exit";s="seq ";[ $n -eq 0 ]&&$e"Congratulations on your new baby! :D"&&$x;[ $n -gt 0 ]&&{ $p' %.s$ ' `$s 1 $n`;$e; $p' %.s| ' `$s 1 $n`;$e;};$p'%.s---' `$s 1 $n`;$e;$p'%.s~~~' `$s 1 $n`;$e;$p'%.s---' `$s 1 $n`
\$\endgroup\$
  • 1
    \$\begingroup\$ You young whippersnappers with your $() constructs. Don't forget the good ol' backtick (not sure how to quote them): read n;[ $n -eq 0 ]&&echo "Congratulations on your new baby! :D"&&exit;[ $n -gt 0 ]&&{ printf ' %.s$ ' seq 1 $n; echo; printf ' %.s| ' seq 1 $n; echo;};printf '%.s---' seq 1 $n;echo;printf '%.s~~~' seq 1 $n;echo;printf '%.s---' seq 1 $n (247 bytes) \$\endgroup\$ – Mike S Sep 10 '15 at 21:20
  • \$\begingroup\$ @MikeS Thank you! The last update has also other improvements. \$\endgroup\$ – Tarod Sep 11 '15 at 6:34
  • \$\begingroup\$ If you gzip the script and put a little header in front of it, you can actually get it down to 208 bytes. Unfortunately, since it's binary I have to deliver it in uuencoded format. Is this allowed? begin 644 c.uue M<V5D("]><V5D+V0@)#@?"!G=6YZ:7@+6,@?"!B87-H("US("TM(#L@97AI M=H?BP@(F-?R50#80!]S,\.P48!/"[IQA-U6F5J^V-MQ!)M[IJ$_F6[5<T MV&>W_B4JXC2'^<TXK4I0EI;ZD#*W<H&8(/0>8RR31*\V%M',4N44-UO%QE(- M2VAMXT#ZB$(5;1_3>13PR?!K7_%S?\;.&>(UAAB,ZCA$7H?O24"YQ/U==L3E <E[C*-PE""-$A#_'1>^__]E_[W@V096/,``$````` end \$\endgroup\$ – Mike S Sep 11 '15 at 13:44
  • \$\begingroup\$ To @Tarod But I didn't include your code in my gzipped file. The way to make it is this: Put your code into file a. gzip -c a > b . Create a file c with the following contents: sed /^sed/d $0|gunzip -c|bash -s --;exit. Now cat b >> c (you cannot edit c because vim at least munges the binary). Run c. BTW, you can change $n -eq 0 to $n = 0 and save 2 bytes above because bash has virtually no typing. Finally, if I DO use your code from above instead of what I have in the uue above, it's actually 215 bytes. Funny how gzip compresses. \$\endgroup\$ – Mike S Sep 11 '15 at 13:54
1
\$\begingroup\$

C, 729 bytes

I'm new to programming, and new to Stack Exchange, however I still wanted to give it a shot with whatever my professor has taught me as of now:

#include<stdio.h>
int main(void)
{char a[2][100]={" "}, b[3][100],i;int c;for(i=1;i<100;i+=2){a[0][i]='$';a[1][i]='|';}for(i=0;i<100;++i){b[0][i]='-';b[1][i]='~';b[2][i]='-';}puts("enter ur age");scanf("%d", &c);if (c==0)printf("congratulations on your new baby!");else if (c<0){for(i=0;i<3;++i){printf("%c", b[0][i]);}printf("\n");for(i=0;i<3;++i){printf("%c", b[1][i]);}printf("\n");for(i=0;i<3;++i){printf("%c", b[2][i]);}printf("\n");}else{for(i=0;i<2*c;++i){printf("%c", a[0][i]);}printf("\n");for(i=0;i<2*c;++i){printf("%c", a[1][i]);}printf("\n");for(i=0;i<=2*c;++i){printf("%c", b[0][i]);}printf("\n");for(i=0;i<=2*c;++i){printf("%c", b[1][i]);}printf("\n");for(i=0;i<=2*c;++i){printf("%c", b[0][i]);}printf("\n");}return(0);}

The readable version of it is,

#include<stdio.h>
int main(void)
{

    char a[2][100]={" "}, b[3][100],i;
    int c;

    for(i=1; i<100; i+=2)
    {
        a[0][i]='$';
        a[1][i]='|';        
    }

    for(i=0; i<100; ++i)
    {
        b[0][i]='-';
        b[1][i]='~';
        b[2][i]='-';
    }   
    puts("enter ur age");
    scanf("%d", &c);
    if (c==0)
    printf("congratulations on your new baby!");
    else if (c<0)
    {

        for(i=0;i<3;++i)
        {
            printf("%c", b[0][i]);
        }
        printf("\n");
        for(i=0;i<3;++i)
        {
            printf("%c", b[1][i]);
        }
        printf("\n");

        for(i=0;i<3;++i)
        {
            printf("%c", b[2][i]);
        }
        printf("\n");
    }
    else
    {
        for(i=0;i<2*c;++i)
        {
            printf("%c", a[0][i]);
        }
        printf("\n");
        for(i=0;i<2*c;++i)
        {
            printf("%c", a[1][i]);
        }
        printf("\n");
        for(i=0;i<=2*c;++i)
        {
            printf("%c", b[0][i]);
        }
        printf("\n");
        for(i=0;i<=2*c;++i)
        {
            printf("%c", b[1][i]);
        }
        printf("\n");
        for(i=0;i<=2*c;++i)
        {
            printf("%c", b[0][i]);
        }
        printf("\n");

    }

    return(0);
}
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 128 bytes

n=>n?[...n<0?(n=1,'  -~-'):'$|-~-'].map((c,i)=>(i<2?' '+c:c).repeat(i<2?n:n*2+1)).join`
`:'Congratulations on your new baby! :D'

Demo

let f =

n=>n?[...n<0?(n=1,'  -~-'):'$|-~-'].map((c,i)=>(i<2?' '+c:c).repeat(i<2?n:n*2+1)).join`
`:'Congratulations on your new baby! :D'

console.log(f(-1));
console.log(f(0));
console.log(f(1));
console.log(f(2));

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

Jelly, 49 46 bytes

Ḥ‘»3“-~-”ẋ€;@⁶p⁾$|¤ẋ€$Yµ“ŒḅœÑḄŻ:Ṁ¿Þ5sṭ+¬ḅḣ;»¹?

Try it online!

-3 bytes from Erik

\$\endgroup\$
  • \$\begingroup\$ The non-competing policy doesn't exist anymore. \$\endgroup\$ – Erik the Outgolfer Jan 26 '18 at 22:13
  • \$\begingroup\$ @EriktheOutgolfer Oh, didn't know about that. Answer fixed, thanks! \$\endgroup\$ – ellie Jan 27 '18 at 6:47
  • \$\begingroup\$ Oh, and a few bytes less. \$\endgroup\$ – Erik the Outgolfer Jan 27 '18 at 14:12
1
\$\begingroup\$

PHP, 197 185 bytes

<?php $t=($i=$argv[1])<0?3:2*$i+1;$n="
";$f='str_repeat';$d=$f('-',$t);$t=$f('~',$t);echo!$i?'Congratulations on your new baby! :D':($i>0?$f(' $',$i).$n.$f(' |',$i).$n:'')."$d$n$t$n$d";

Contributions:

  • -12 bytes from Jo.

More readable:

PHP, 197 bytes

<?php
$i=$argv[1];
$t=$i<0?3:2*$i+1;
$n="\n";
$f='str_repeat';
$d=$f('-',$t);
$t=$f('~',$t);
echo $i==0?'Congratulations on your new baby! :D':($i>0?$f(' $',$i).$n.$f(' |',$i).$n:'')."$d$n$t$n$d";
\$\endgroup\$
  • \$\begingroup\$ You can save 12 bytes with a few changes \$\endgroup\$ – Jo. Jan 27 '18 at 21:05
  • \$\begingroup\$ @Jo, haha, thanks. That certainly is a way to save some bytes. I like how you didn't use \n for the line break. I have updated. \$\endgroup\$ – Starx Jan 28 '18 at 13:12
1
\$\begingroup\$

05AB1E, 44 bytes

_i“Ûà€‰€ž€¢‡Í! :D“.ªëdi>V„ $„ |}…-~-`)εY∍û}»

Try it online!

_i                               # if input != 0:
  “Ûà€‰€ž€¢‡Í! :D“               #  dictionary string "congratulations on your new baby! :D"
                  .ª             #  sentence case
ë                                # else:
 di        }                     #  if input >= 0:
   >V                            #   set Y = input + 1 (by default, Y is 2)
     „ $                         #   push literal " $"
        „ |                      #   push literal " |"
…-~-                             #  push literal "-~-"
    `                            #  dump each character separately
     )                           #  wrap the entire stack in a list:
                                 #   [" $", " |", "-", "~", "-"] if input > 0
                                 #   ["-", "~", "-"] if input < 0
      ε   }                      #  for each item in that list:
       Y∍                        #   extend to length Y
         û                       #   palindromize
           »                     #  join the stack by newlines
                                 # implicit output
\$\endgroup\$
1
\$\begingroup\$

Zsh, 162 bytes

try it online!!

((!$1))&&<<<"Congratulations on your new baby! :D"&&exit
y=$[$1<0?2:2*$1] a=${(l:y:: $:)} b=${(l:y+1::-:)}
(($1>0))&&echo "$a\n${a//$/|}"
echo "$b\n${b//-/~}\n$b"
\$\endgroup\$
0
\$\begingroup\$

ECMAScript 2015 – 134 bytes

n=>n?[' $'.repeat(n=(n>0)*n),' |'.repeat(n),d='-'.repeat(c=n?1+2*n:3),'~'.repeat(c),d].join`
`:'Congratulations on your new baby! :D'
\$\endgroup\$
0
\$\begingroup\$

Python 2, 131 bytes

x,y,n="$|-~-","  -~-",input()
for i in zip(y,*[y,y]*(n<0)+[x,y]*n)if n else["Congratulations on your new baby! :D"]:print"".join(i)

Happy belated birthday to OP :D Haven't been here in ages, I need to warm up my golfing skills again...using my favorite 90 degree list rotation trick with zip() here. The 0 case kinda threw me off, without it this code is 83 bytes.

As a bonus, taking the whitespace out of the y variable results in some interesting cake variations. Removing one space results in:

 $ $ $ $ $
-|-|-|-|-|-
~-~-~-~-~-~
-~-~-~-~-~-

and with the whitespace stripped entirely:

-$-$-$-$-$-
~|~|~|~|~|~
-----------
\$\endgroup\$
  • \$\begingroup\$ Replace the second line with for i in(["Congratulations on your new baby! :D"],zip(y,*[y,y]*(n<0)+[x,y]*n))[n!=0]:print"".join(i). -1 bytes. \$\endgroup\$ – Erik the Outgolfer Sep 13 '16 at 18:10
0
\$\begingroup\$

C#, 467 Bytes

I know I won't win, but I think I at went overboard with while loops.

using System;class P{static void Main(string[]a){int i=int.Parse(a[0]);if(i==0){Console.Write("Congratulations on your new baby! :D");}else{int e=i;while(i-->0){Console.Write(" $");}if(e > 0){i = e;Console.Write("\n");while(i-- > 0){Console.Write(" |");}Console.Write("\n");i = e;} else {i=(e=1);}Console.Write("-");while(i-->0){Console.Write("--");}i=e;Console.Write("\n~");while(e-->0){Console.Write("~~");}Console.Write("\n-");while(i-->0){Console.Write("--");}}}}

Non minified version:

using System;
class P {
    static void Main(string[] a) {
        int i = int.Parse(a[0]);
        if(i == 0) {
            Console.Write("Congratulations on your new baby! :D");
        } else {
            int e = i;
            while(i-- > 0) {
                Console.Write(" $");
            }
            if(e > 0) {
                i = e;
                Console.Write("\n");
                while(i-- > 0) {
                    Console.Write(" |");
                }
                Console.Write("\n");
                i = e;
            } else {
                i = (e = 1);
            }
            Console.Write("-");
            while(i-- > 0) {
                Console.Write("--");
            }
            i = e;
            Console.Write("\n~");
            while(e-- > 0) {
                Console.Write("~~");
            }
            Console.Write("\n-");
            while(i-- > 0) {
                Console.Write("--");
            }
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

C, 196 bytes

Prints leading spaces before empty candle cake. According to comments in the challenge, that's okay.

i,n;main(c,v)char**v;{c=atoi(v[1]);n=c<0;if(c)for(c=n?1:c;i++<10*c+10;)putchar(i%(2*c+2)?i<4*c+5?n|i%2?32:i<2*c+2?36:'|':i/(2*c+2)==3?'~':45:10);else puts("Congratulations on your new baby! :D");}

Ungolfed:

i,n;

int main(int c, char **v)
{
    c = atoi(v[1]);
    n = c < 0;
    if(c)
        for(c=n?3:c;i++<10*c+10;)
            putchar(i%(2*c+2) /* print '\n' at the end of each row */
                    ? i<4*c+5 /* first two rows are candles, last 3 are cake */
                        ? n || i % 2 /* alternate between space and candle */
                                ? ' '
                                : i<2*c+2 /* first row is '$', second is '|' */
                                    ? '$'
                                    : '|'
                        : i / (2*c+2) == 3 /* alternate rows between '-' and '~' */
                            ? '~'
                            : '-'
                    : '\n');
    else
        puts("Congratulations on your new baby! :D");
}
\$\endgroup\$
0
\$\begingroup\$

Java 7, 197 198 bytes

String c(int y){String a=" ",b=a,c="---",n="\n";for(int i=0;i<y;a+="$ ",b+="| ")if(y>0&i++>0)c+="--";c=c+n+c.replace('-','~')+n+c;return y<0?c:y>0?a+n+b+n+c:"Congratulations on your new baby! :D";}

Ungolfed:

String c(int y){
   String a = " ",
          b = a,
          c = "---",
          n = "\n";
    for(int i = 0; i < y; a += "$ ",
                          b += "| "){
      if(y > 0 & i++ > 0){
        c += "--";
      }
    }
    c = c + n + c.replace('-', '~') + n + c;
    return y < 0
            ? c
            : y > 0
               ? a + n + b + n + c
               : "Congratulations on your new baby! :D";
  }

Test code:

Try it here.

class M{
  static String c(int y){String a=" ",b=a,c="---",n="\n";for(int i=0;i<y;a+="$ ",b+="| ")if(y>0&i++>0)c+="--";c=c+n+c.replace('-','~')+n+c;return y<0?c:y>0?a+n+b+n+c:"Congratulations on your new baby! :D";}

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println();
    System.out.println(c(3));
    System.out.println();
    System.out.println(c(25));
    System.out.println();
    System.out.println(c(0));
    System.out.println();
    System.out.println(c(-1));
  }
}

Output:

 $ 
 | 
---
~~~
---

 $ $ $ 
 | | | 
-------
~~~~~~~
-------

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
 | | | | | | | | | | | | | | | | | | | | | | | | | 
---------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------------------

Congratulations on your new baby! :D

---
~~~
---
\$\endgroup\$

Your Answer

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