text:
It's my Birthday :D
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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Happy Birthday!

is leading whitespace (for example 2 newlines) allowed for the candleless cake?

@steveverrill Yes

Just to make sure: Should all negative numbers produce the same 3-character-wide candleless cake, or a cake of the same width as the corresponding positive number?

@PaŭloEbermann A cake of 3-width

Nothing can be output to stderr only? What about outputting to System.err or file descriptor 2?

@immibis, isn't it the same?

I like the leaderboard. You should post the language and how many bytes it is.

@jvriesem I don't understand what you mean :/

@sigod One per execution...

@jvriesem No. It's code for snippet.

The leaderboard snippet is not working.

@Starx It appears to work for me. What's the problem for you?

It's an off-by-one error for me (:

Pyth, 73 72 71 69 67 bytes
?Qjb+m*+\ dQ"$|"*RhyeS,1Q"-~-""Congratulations on your new baby! :D

Try it online.
Output for n < 0 contains 2 leading newlines, as permitted in comments. To get rid of them, use
?QjbfT+jR*\ hQ"$|"*RhyeS,1Q"-~-""Congratulations on your new baby! :D

The smallest code, ofcourse, appears to be least human readable.

WTF is this??? LOL

CJam, 76 75 bytes
ri_W>\_1e>)" $ |--~~--"2/f*Wf<N*"Congratulations on your new baby! :D"?_8>?

Try it online in the CJam interpreter.
How it works
ri           e# Read an integer from STDIN.
_W>          e# Check if it is greater than -1.
\_           e# Swap input and Boolean and copy the input.
1e>)         e# Take the maximum of input and 1 and increment the result.
             e# Let's call the result R.
" $ |--~~--" e# Push that string.
2/           e# Split it into [" $" " |" "--" "~~" "--"].
f*           e# Repeat each chunk R times.
Wf<          e# Discard the last character of each repeated chunk.
N*           e# Join the repreated chunks, separating by linefeeds.

"Congratulations on your new baby! :D"

?            e# If the input is non-zero, select the cake; else, keep the string.
_8>          e# Push a copy and discard the first 8 characters (single candle).
?            e# Select the unmodified cake/string if the input was non-negative,
             e# a candleless cake otherwise.

JavaScript ES6, 136
Using alert for output - bad proportional font and the result is ugly. In the snippet below the alert is redirect to the snipped body, giving a better result.
The newline inside backticks is significant and counted.
Test running the snippet in Firefox.

/* Redefine alert for testing purpose */ alert=x=>O.innerHTML=x;

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

Less golfed
n=+prompt(); // get input and convert to number

if (n) { // if n != 0 prepare the cake
   output = [...'$|-~-'].map( // for each char of the five lines
     (c,i) => (i>1 ? c : ' '+c) // in line 0 and 1 symbols are space separated
     // if n < 0 repeat count is 0 for line 0 and 1, 3 for the other
     // if n > 0 repeat count is n for line 0 and 1, n+n+1 for the other
     .repeat(i>1 ? n>0 ? n-~n : 3 : n>0 && n) //
   ).join`\n`;
}
else {
    output = 'Congratulations on your new baby! :D');
}

alert(output);

Try this $('div pre code')[2].innerHTML ;)

R, 157
write(if(n<-scan()){
z=matrix(c("$","|","-","~","-"),N<-2*max(1,n)+1,5,T)
z[seq(1,N,1+(n>0)),1:2]=" "
z}else"Congratulations on your new baby! :D","",N,F,"")

I'm learning a lot on write parameters there. Brilliant one

Ruby, 120 bytes
Revision 1 (120 bytes)
18 bytes saved thanks to manatwork
n=gets.to_i
puts ['Congratulations on your new baby! :D',%w{\ $ \ | - ~ -}.map{|e|e.ljust 2*n+1,e},'---
~~~
---'][n<=>0]

Revision 0 (138 bytes)
n=gets.to_i
n>0&&[' $',' |',?-,?~,?-].each{|e|puts''.rjust(2*n+1,e)}
puts ['Congratulations on your new baby! :D','','---
~~~
---'][n<=>0]

For positive numbers: this iterates through a string corresponding to each line of the cake. These are used as pad strings to right justify the empty string to length 2*n+1. This avoids any complications with having to print an odd number of characters, when the natural repetition is equal to the pitch of the candles (i.e. 2 characters.) n>0&& is necessary to avoid outputting a single column in case of input zero.
For all numbers: "n<=>0" finds the sign of the input. The baby message is output for n=0, and an empty string for positive n (as correct output has already been given above.) For negative n, Ruby interprets the -1 as meaning the last element of the array, and outputs the candleless cake.

Aren't there too many puts? `n=gets.to_i
puts ['Congratulations on your new baby! :D',%w{\ $ \ | - ~ -}.map{|e|''.rjust 2*n+1,e},'---
---'][n<=>0]`

One more: ''.rjust → e.ljust.

@manatwork thanks, I should have spotted that, but I did this very quick. I didn't know about backslash space with %w. And e.just: very clever.

R, 228 226 220 221 Bytes

Last edit to correct the candleless cake, was as wide as the positive one on negative cases, thanks @CathG and @jbaums for the feedback
n=scan()
s=strsplit
p=paste0
a=b='-~-'
if(!n)cat('Congratulations on your new baby! :D')else{
if(n>0){a=p('  ',a);b=p('$|',b)}else n=1
a=s(a,'')
b=s(b,'')
d=data.frame(rep(c(a,b),n),a)
cat(do.call(p,d),sep="\n")}

A couple of bytes can be saved: <- can be =, and you can use a=b='-~-'.

Ho, thanks @jbaums forget the first = and didn' tthough of the dual assignation

You have a bracket issue somewhere, I get Error: unexpected '}'

@flodel corrected. Copy/paste issue

MATLAB / Octave, 194 198 195 189 171 167 bytes
Happy birthday to you Beta Decay! :)
Thanks to HamtaroWarrior for shaving off 4 bytes!

n=input('');m='$|'.';d='  '.';if(n==0)disp('Congratulations on your new baby! :D'),break;elseif(n<0)m=d;n=1;end,disp([[d repmat([m d],1,n)];repmat('-~-'.',1,2*n+1)]);

Sample Runs
I placed this into a script file called happy_birthday.m, then ran it a few times in the command prompt.  Take note that when you enter in a negative number, there are two leading carriage returns, but that's allowed in this challenge:
>> happy_birthday
-1

---
~~~
---
>> happy_birthday
0
Congratulations on your new baby! :D
>> happy_birthday
1
 $
 |
---
~~~
---
>> happy_birthday
2
 $ $
 | |
-----
~~~~~
-----
>> happy_birthday
3
 $ $ $
 | | |
-------
~~~~~~~
-------
>> happy_birthday
4
 $ $ $ $
 | | | |
---------
~~~~~~~~~
---------
>> happy_birthday
5
 $ $ $ $ $
 | | | | |
-----------
~~~~~~~~~~~
-----------

Code with spacing and explanations
% Get the input number from the user
n=input('');

% If the number is positive, the core candle sequence is going to be a column vector of a $ followed by a | character
m='$|'.';

%// Array of one column and it has two spaces - going to use more than once
d = '  '.';

% If the number is 0, display the congratulations message and get out
if(n==0)
    disp('Congratulations on your new baby! :D')
    break;

% m stores the core candle sequence for displaying on the screen
% If the number is negative, the core candle sequence is going to be a column of two blank spaces
elseif(n<0)
    m=d;
    n=1; % n is set to 1 as this is the number of "blank candles" we want to display
end

% This displays candles and the base together
% The top half is the displaying of the candles
% It is a column vector of spaces, followed by pairs of $,| in a column
% and another column of spaces - repeated n times
% The bottom half is the displaying of the cake
% The bottom half is a column vector of -,~,- for the base of the cake
% and is repeated 2*n + 1 times to match the candle display
disp([[d repmat([m d],1,n)];repmat('-~-'.',1,2*n+1)]);

The displaying part at the end is probably the most obfuscated part of the code.  This is going to display a 5 row character matrix where the first two rows consists of the candles and the last three rows consists of the base of the cake.
The basis for the top half of the display is either two spaces in a column followed by another two spaces in another column in the case that the age is negative, or a $,- in a column followed by two spaces in another column.  This is a 2 x 2 character matrix.  The basis for the bottom half of the display is a single column vector of -,~,- which is a 3 x 1 character matrix.
The display command first tackles the first two rows of the cake by placing two spaces in the first column, followed pairs of a column of $,- or a column of spaces if n is negative, which gets changed to n=1, and another column of two spaces repeated for a total of n times.  The next three rows simply replicate the -,$,- column vector for 2*n + 1 times to align the candles together with the base, thus completing the picture.
Try it online!
You can try this online using IDEOne's Octave compiler: http://ideone.com/4qXDdJ - however, there is a slight bug when reading in values from standard input.  As such, the script is slightly modified where you have to change the value of n at the beginning of the code.  Fork a new version of the script and change this to whatever integer value suits you in order to see what the output looks like.

Pity you can't save the dot in '  '.' !

@LuisMendo - I know!... though I'm sure you don't object to the use of the transpose that way :)

Hahaha. I was once told here that this site is for abusing the language. And I follow that rule faithfully!

@LuisMendo - I really wanted to get rid of the dot... but couldn't because MATLAB interprets that as a single quotation in the string :(. Would have saved me a few bytes... but after many iterations, this was the best I could come up with.

@LuisMendo - managed to shrink it down to 171!

Why don't you set m='$|'.' at the beggining, then only change to m=d if n<0? This way you could get rid of the else & end in else m='$|'.';end

@HamtaroWarrior good tip!

R, 279 bytes
Interactive version (286 bytes):
b<-function(){
n=scan()
if(n==0)cat("Congratulations on your new baby! :D\n")
if(n>0){k=2*n+1;m=rep("-",k);cat(paste(c(rep(c(" ","$"),l=k),"\n",rep(c(" ","|"),l=k),"\n",m,"\n",rep("~",k),"\n",m,"\n"),collapse=""))}
if(n<0){m=rep("-",3);cat(paste(c(m,"\n",rep("~",3),"\n",m,"\n"),collapse=""))}
}

Not interactive version (279 bytes):
b<-function(n){
if(n==0)cat("Congratulations on your new baby! :D\n")
if(n>0){k=2*n+1;m<-rep("-",k);cat(paste(c(rep(c(" ","$"),l=k),"\n",rep(c(" ","|"),l=k),"\n",m,"\n",rep("~",k),"\n",m,"\n"),collapse=""))}
if(n<0){m=rep("-",3);cat(paste(c(m,"\n",rep("~",3),"\n",m,"\n"),collapse=""))}
}

JavaScript, 143 153 Bytes
for(v in k=' $ 0 | 0---0~~~0---'.split(+!(n=+prompt(c=''))))c+=k[v].repeat(n<0?1:n)+'\n';alert(n>0?c:n?c.slice(8):'Congratulations on your new baby! :D')
To see output in mono space font replace 'alert' by 'console.log'

Welcome to PPCG! :)

Sadly this displays the congratulation message for negative input too.

@BetaDecay tnx :-)

Manatwork's right :/ I don't know enough JS to help

@manatwork yes you right! i misunderstood!

@manatwork i fix that with 10 more characters :-D

Moonscript, 141 bytes
n=0+io.read!
m=3
f=(s='-')->print s\rep m
if n>0
 m=n
 m=1+2*m,f' $',f' |'
if n==0 print"Congratulations on your new baby! :D"else f f!,f'~'

Welcome to Programming Puzzles and Code Golf!

rs, 117 bytes
^0$/Congratulations on your new baby! :D
-.+/-1
$$r=)^^(\1)\n
$$m=-(--)^^(\1)\n
(\d+)/ ($ $r (| $r$m~(~~$r$m
^-[^-]+/

Live demo and test cases.

Mouse, 164 161 bytes
?N:N.0=["Congratulations on your new baby"33!'" :D"$]N.0>[#P,32!'36,N.;#P,32!'124,N.;]N.0<[1N:]2N.*1+D:#P,45,D.;#P,126,D.;#P,45,D.;$P0I:(I.2%=0=^1%!'I.1+I:)"!"@

Mouse is clearly not an ideal choice for this task, but it was fun.
Ungolfed:
? N.                               ~ Read N from STDIN
N. 0 = [                           ~ Have a baby for N == 0
  "Congratulations on your new baby" 33 !' " :D" $
]
N. 0 > [                           ~ If N > 0...
  #P, 32 !' 36, N.;                ~ Print the candle flames
  #P, 32 !' 124, N.;               ~ Print the candle sticks
]
N. 0 < [                           ~ If N < 0...
  1 N:                             ~ Set N = 1
]
2 N. * 1 + D:                      ~ Assign D = 2N + 1
#P, 45, D.;                        ~ Print the top cake layer
#P, 126, D.;                       ~ Print the middle layer
#P, 45, D.;                        ~ Print the bottom
$P                                 ~ Define the printing macro...
  0 I:                             ~ Initialize I to 0
  ( I. 2% = 0 = ^                  ~ While I != the second input
    1% !'                          ~ Print the first input
    I. 1 + I:                      ~ Increment I
  )
  "!"                              ~ Print a newline
@

The stack can contain only integers. !' takes an integer off the stack and prints the ASCII character with that code.

Ceylon, 322 307 300 282 278 260 bytes
shared void run(){if(exists t=process.readLine(),exists n=parseInteger(t)){String r(String s)=>s.repeat(n);print(n>0thenr(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-"else(n<0then"---\n~~~\n---"else"Congratulations on your new baby! :D"));}}

The not yet golfed original (assuming negative cakes have width 3 instead of –2·n+1):
shared void birthdayCake() {
    if (exists text = process.readLine(), exists number = parseInteger(text)) {
        switch (number <=> 0)
        case (equal) {
            print("Congratulations on your new baby! :D");
        }
        case (smaller) {
            print("---\n~~~\n---");
        }
        case (larger) {
            print(" $".repeat(number));
            print(" |".repeat(number));
            print("--".repeat(number) + "-");
            print("~~".repeat(number) + "~");
            print("--".repeat(number) + "-");
        }
    }
}

This features the condition list in the if statement, each condition defining a value usable in the following conditions and in the body. Because they have the exist, the condition is only fulfilled when the values is not null, and thus the compiler knows the values is not null for the following code. (If nothing is entered (EOF), readline returns null. If parseInteger hits a non-integer, it also returns null. Our program then does nothing. As the behavior for those cases was not defined, I guess this is okay.)
Also we have the <=> operator, which maps to the Comparable.compare method, and returns a Comparison object, i.e. one of equal, smaller and larger. The compiler knows that those exhaust the Comparison type, so no else clause is needed in our switch statement.
The repeat method of class String does what one would expect. It is actually inherited from the same-named method in interface Iterable (as a string is, beside other stuff, just a list of characters).
Replacing my identifiers by one-letter ones and removing unneeded white space gives 322 characters:
shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n<=>0)case (equal){print("Congratulations on your new baby! :D");}case(smaller){print("---\n~~~\n---");}case(larger){print(" $".repeat(n));print(" |".repeat(n));print("--".repeat(n)+"-");print("~~".repeat(n)+"~");print("--".repeat(n)+"-");}}}

Replacing the series of print by explicit \ns (and one single print) brings it down to 307:
shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n<=>0)case(equal){print("Congratulations on your new baby! :D");}case(smaller){print("---\n~~~\n---");}case(larger){print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}}}

I tried alias-importing of repeat as r, but it doesn't help (the import declaration adds 40 characters, and we can only save 25 by replacing repeat with r).
What slightly helps, is using n.sign instead of n<=>0. While these two expressions have the same textual length, they have different types: the latter one is of type Comparison mentioned before (which has the three values smaller, larger and equal), the former one has type Integer, with the values -1, 1, 0 ... and because Integer has many more values, we also need an else clause. This is 300 characters long:
shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n.sign)case(0){print("Congratulations on your new baby! :D");}case(-1){print("---\n~~~\n---");}case(1){print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}else{}}}

Here with whitespace:
shared void b() {
    if (exists t = process.readLine(), exists n = parseInteger(t)) {
        switch (n.sign)
        case (0) {
            print("Congratulations on your new baby! :D");
        }
        case (-1) {
            print("---\n~~~\n---");
        }
        case (1) {
            print(" $".repeat(n) + "\n" +
                        " |".repeat(n) + "\n" +
                        "--".repeat(n) + "-\n" +
                        "~~".repeat(n) + "~\n" +
                        "--".repeat(n) + "-");
        }
        else {}
    }
}

We can safe some more by resigning about our switch statement and using if, coming to 282 characters(=bytes):
shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){if(n==0){print("Congratulations on your new baby! :D");}else if(n<0){print("---\n~~~\n---");}else{print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}}}

Formatted:
shared void b() {
    if (exists t = process.readLine(), exists n = parseInteger(t)) {
        if (n == 0) {
            print("Congratulations on your new baby! :D");
        } else if (n < 0) {
            print("---\n~~~\n---");
        } else {
            print(" $".repeat(n) + "\n" +
                        " |".repeat(n) + "\n" +
                        "--".repeat(n) + "-\n" +
                        "~~".repeat(n) + "~\n" +
                        "--".repeat(n) + "-");
        }
    }
}

We can safe another byte by swapping the cases around, since > is shorter than ==.
Another "annoyance" is the repeated repeat(n) – we can define a local function (a closure, it remembers n from the defining block) with a shorter name:
String r(String s) => s.repeat(n);

This is a shorter way of writing this:
String r(String s) {
    return s.repeat(n);
}

We could use function instead of the return type for type inference, but this is not shorter. This gives us 278 bytes:
shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){if(n>0){String r(String s)=>s.repeat(n);print(r(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-");}else if(n<0){print("---\n~~~\n---");}else{print("Congratulations on your new baby! :D");}}}

Formatted:
shared void b() {
    if (exists t = process.readLine(), exists n = parseInteger(t)) {
        if (n > 0) {
            String r(String s) => s.repeat(n);
            print(r(" $") + "\n" + r(" |") + "\n" + r("--") + "-\n" + r("~~") + "~\n" + r("--") + "-");
        } else if (n < 0) {
            print("---\n~~~\n---");
        } else {
            print("Congratulations on your new baby! :D");
        }
    }
}

Actually, using the then and else operators instead of the if statements allows us to save some calls of print (and some braces):
shared void run() {
    if (exists t = process.readLine(), exists n = parseInteger(t)) {
        String r(String s) => s.repeat(n);
        print(n > 0 then r(" $") + "\n" +
                        r(" |") + "\n" +
                        r("--") + "-\n" +
                        r("~~") + "~\n" +
                        r("--") + "-"
                    else (n < 0
                        then "---\n~~~\n---"
                        else "Congratulations on your new baby! :D"));
    }
}

This is just 261 bytes:
shared void run(){if(exists t=process.readLine(),exists n=parseInteger(t)){String r(String s)=>s.repeat(n);print(n>0thenr(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-"else(n<0then"---\n~~~\n---"else"Congratulations on your new baby! :D"));}}
(I used run instead of b for the function name because this way it can be run with ceylon run without passing a function name.)
My Github repository has a commented version of this.

JavaScript ES6, 154 chars
alert((n=+prompt())?((n>0?` $
 |
`:(n=1)&&"")+`--
~~
--`).replace(/../gm,x=>x.repeat(n)).replace(/(.).*/gm,"$&$1"):"Congratulations on your new baby! :D")

And one more (154 too)
alert((n=+prompt())?` $
 |
--
~~
--`.slice(n<0?(n=1)-9:0).replace(/../gm,x=>x.repeat(n)).replace(/(.).*/gm,"$&$1"):"Congratulations on your new baby! :D")

To see output in monospace font (and move ouptut to the console) use
alert=x=>console.log(x)

CoffeeScript, 160 bytes
f=(i,l=[" $ "," | ",_="---","~~~",_])->if!i then"Congratulations on your new baby! :D"else (if i<0then[_,l[3],_]else i++;(Array(i).join r for r in l)).join "\n"

Ungolfed:
f=(i)->
  l = [" $ "," | ","---","~~~","---"] # The layers
  if i == 0
    return "Congratulations on your new baby! :D"
  else if i < 0
    return [l[2], l[3], l[2]].join("\n")
  else
    i++
    return (Array(i).join(r) for r in l).join("\n")

Use it like:
f(10) # In the CoffeeScript console
alert(f(~~prompt("Y"))) # Browser, alert popup
console.log(f(~~prompt("Y"))) # Browser, log to console, and thus has monospace font

Try it online: link (Contains some custom display code, so everything looks soo nice...)
Ooops, almost forgot it! Happy birthday, @BetaDecay!

C, 392 bytes
(known segmentation fault if no arguments are given)
#include <stdio.h>
#define P(s) printf(s);
#define F for(i=0;i<n;i++)
#define A(s, e) F{P(s)}P(e "\n")
int main(int c, char**v){int i,n=atoi(v[1]);if(n<0){n=3;A("-",)A("~",)A("-",)}else if(!n)P("Congratulations on your new baby! :D\n")else{A(" $",)A(" |",)A("--","-")A("~~","~")A("--","-")}}

Unminified and copiously spaced
#include <stdio.h>
#define P(s) printf ( s ) ;
#define F for ( i = 0 ; i < n ; i++ )
#define A(s, e) F { P ( s ) } P ( e "\n" )
int main ( int c, char ** v )
{
        int i, n = atoi ( v [ 1 ] ) ;
        if ( n < 0 )
        {
                n = 3 ;
                A ( "-", )
                A ( "~", )
                A ( "-", )
        }
        else if ( ! n )
                P ( "Congratulations on your new baby! :D\n" )
        else
        {
                A ( " $", )
                A ( " |", )
                A ( "--", "-" )
                A ( "~~", "~" )
                A ( "--", "-" )
        }
}

Without C boilerplate the #defines's and main body total 247.

Welcome to PPCG! This is a really good answer--I especially like the macro abuse with A. I do see a couple more spaces that could be removed, and you can get rid of i by using c for the loop variable instead. Also, at least with gcc, including stdio.h or specifying the return type of main() isn't necessary: the compiler complains about it, but hey, this is code golf. ;)

Powershell, 139 134 132 126 bytes
$n=$args[0];if($n){$d=3;if($n-gt0){' $'*$n;' |'*$n;$d=$n*2+1}'-'*$d;'~'*$d;'-'*$d}else{'Congratulations on your new baby! :D'}

You can save 5 bytes by using $input instead of $args[0] (question doesn't say to use arguments instead of stdin), and you can use unary + to convert to a number: $n=+$input;

+$input did not seem to work - it complained that $input is an enumerator and does not have an addition operator. However, $args[0] can and should be an actual int, allowing us to at least drop the [int].

So, this is really old, but you can save a couple bytes by moving the input into the if and swapping the else for an ;exit -- 122 bytes -- if($n=$args[0]){$d=3;if($n-gt0){' $'*$n;' |'*$n;$d=$n*2+1}'-'*$d;'~'*$d;'-'*$d;exit}'Congratulations on your new baby! :D'

Python 2, 150 bytes
m=input()
n=m-1
p="---"+"--"*n
g="\n~~~"+"~~"*n+"\n"
if m>0:print" $"*m,"\n"," |"*m
s=p+g+p
print s if m!=0 else"Congratulations on your new baby! :D"

Close to author's Python :(

Perl, 139 127 117 bytes
Does not require '-n' or '-p' options.
Revision 3 (with thanks to Dom Hastings below):
$==<>;map{print$_ x(!$=||(/ /?$=:($=<1||$=)*2+1)).$/}!$=?'Congratulations on your new baby! :D':split 0,' $0 |0-0~0-'

Revision 2:
$n=<>;map{print$_ x($n==0?1:(/ /?$n:($n<1?1:$n)*2+1)).$/}$n==0?('Congratulations on your new baby! :D'):(' $',' |','-','~','-')

Revision 1:
$n=<>;map{print$_ x(($l=length())>2?1:($l==2?$n:($n<1?1:$n)*2+1)).$/}$n==0?('Congratulations on your new baby! :D'):(' $',' |','-','~','-')

Here's a version of revision 3 that doesn't have the leading blank new lines on negative input - 132 bytes.
$==<>;map{print$_ x(!$=||(/ /?$=:($=<1||$=)*2+1)).(/ /&&$=<0?'':$/)}!$=?'Congratulations on your new baby! :D':split 0,' $0 |0-0~0-'

Hey there, welcome! Thought I'd share a couple of ways you can save some bytes! You can drop the brackets around "Congratulations..." and if you replace ' $',' |','-','~','-' with split 0,' $0 |0-0~0-' you can drop those brackets too. Another save is replacing $n=<>;$n==0 with ($n=<>)==0. Also your ?1: could be || as you'd be saying $n==0 (which is 1) or your calculation. Hope that helps!

Hey there, thanks for that. Those brackets are a good one, and reminding me of the semantics of || is very helpful - it reminded me of $= to basically chomp the input, eliminating the requirement for specific 0 value tests.
I'm not sure what you mean by $n=<>;$n==0 - my golf doesn't have that, and given I handle the input=0 case as input into the map{}(), I'm not sure how this would apply?
Anyway, taking your comments and using $= as my variable, this has been golfed down to 117 parbytes. Thanks very much!

No problem at all! Glad to have helped! What I mean was that you have $n=<>; at the beginning and then $n==0 at the back of the map{}... so I think you could have the check as ($n=<>)==0 but if you're using $= instead you might be able to shrink it more! I always forget which of $- or $= can't be negative so I didn't want to mention it and be wrong! :)

golflua, 113 characters
\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$

Sample run:
bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< 5
 $ $ $ $ $
 | | | | |
-----------
~~~~~~~~~~~
-----------

bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< 0
Congratulations on your new baby! :D

bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< -5
---
~~~
---

Python 2, 158 bytes

i=input()
l='\n'
s=''
if i==0:s='Congratulations on your new baby! :D'
elif i<0:s='---\n~~~\n---'
else:n=i*2+1;a=l+'-'*n;s=' $'*i+l+' |'*i+a+l+'~'*n+a
print s

Pip, 74 + 1 = 75 bytes
Takes the age as a command-line argument. Requires the -n flag.
Y^"-~-"a?a<0?yX3(s.^"$|")XaALyX2*a+1"Congratulations on your new baby! :D"

Github repository for Pip
The command-line argument is stored in a. We split "-~-" into a list of characters and Yank it into the variable y. The rest of the program is a big ternary expression:

a?  If a is truthy (i.e. not zero):

a<0?yX3  If a is negative, return y with each element repeated 3 times: ["---";"~~~";"---"]
Else (a is positive):

(s.^"$|")Xa  Split "$|" into a list of characters, prepend a space (s) to each, and repeat each resulting element a times
yX2*a+1  Repeat each element of y 2*a+1 times
AL  Append the two lists

Else (a is zero), return the congratulations string

At the end of the program, the -n flag ensures that lists are printed with elements on separate lines, thus displaying a properly layered cake.
Here are the steps for an input of 2:
Candles
["$";"|"]
[" $";" |"]
[" $ $";" | |"]

Cake
["-";"~";"-"]
["-----";"~~~~~";"-----"]

Put it together
[" $ $";" | |";"-----";"~~~~~";"-----"]

Final output
 $ $
 | |
-----
~~~~~
-----

Happy birthday!

05AB1E, 45 44 bytes
_i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍»

Try it online!
_i                               # if input != 0:
  “Ûà€‰€ž€¢‡Í! :D“               #  dictionary string "congratulations on your new baby! :D"
                  ćuì            #  uppercase the first character
ë                                # 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

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"]("  -~-";"$|-~-")}

Perl, 144 bytes
143 bytes of code, plus one extra byte for the -n switch to capture stdin.
if($_!=0){print$_>0?" \$"x$_.$/." |"x$_.$/:""x($_=1);$_=$_*2+1;print"-"x$_.$/."~"x$_.$/."-"x$_;exit}print"Congratulations on your new baby! :D"

print"-~-"=~s!.!$&x($_*2+1).$/!ger for the cake?

If you change the switch to -p this will also work: $_=$_!=0?($_>0?' $'x$_.$/." |"x$_:""x($_=1))."-~-"=~s!.!$/.$&x($_*2+1)!ger:"Congratulations on your new baby! :D"

SpecBAS, 164
Uses the apostrophe shortcut to move to new line
INPUT n: IF n=0 THEN PRINT "Congratulations on your new baby! :D" ELSE IF n<0 THEN PRINT "---"'"~~~"'"---" ELSE PRINT " $"*n'" |"*n'"-";"--"*n'"~";"~~"*n'"-";"--"*n

Formatted for easier reading
INPUT n
IF n=0 THEN PRINT "Congratulations on your new baby! :D"
ELSE IF n<0 THEN PRINT "---"'"~~~"'"---"
ELSE PRINT " $"*n'" |"*n'"-";"--"*n'"~";"~~"*n'"-";"--"*n

Python 3, 169 bytes
n=int(input())
m=max(n*2+1,3)
f=' {}'*n+'\n'+' {}'*n+'\n'+'-'*m+'\n'+'~'*m+'\n'+'-'*m
if n==0:f='Congratulations on your new baby! :D'
print(f.format(*['$']*n+['|']*n))

Julia, 143 bytes
n=int(readline())
p=println
l="\n"
n>0&&p(" \$"^n*l*" |"^n)
d=2(n<0?1:n)+1
p(d>1?"-"^d*l*"~"^d*l*"-"^d:"Congratulations on your new baby! :D")

Pretty straightforward. Ungolfed:
# Read n from STDIN and convert to an integer
n = int(readline())

# Print the candles for positive n
n > 0 && println(" \$"^n * "\n" * " |"^n)

# Define d as the width of the cake
d = 2(n < 0 ? 1 : n) + 1

# Newborns can't eat cake
if d > 1
    println("-"^d * "\n" * "~"^d * "\n" * "-"^d)
else
    println("Congratulations on your new baby! :D")
end

Lua, 299 Bytes
a=0+io.read() b=string.rep p=print if a==0 then p("Congratulations on your new baby! :D") else p(b(" ",a)..b("$ ",a)..("\n")..b(" ",a)..b("| ",a)) if a<0 or a==1 then p("---\n~~~\n---") else p(b(" ",a-1).."-"..b("-",2*a).."\n"..b(" ",a-1).."~"..b("~",2*a).."\n"..b(" ",a-1).."-"..b("-",2*a))end end

Welcome to PPCG! Your code as it stands seems to give an error (attempt to compare string with number), but adding 0+ before io.read() fixes it for me. You can also save quite a few bytes by assigning print and string.rep to single-character variables.

@DLosc thanks good idea :) and yeah u were right with the error sorry about that

Mathematica, 164 Bytes
Completely missed the candle-less cakes for n < 0, adding an additional 15 characters
r[a_,b_]:=StringRepeat[a,Abs@b];c=" $ ";t="---";m="~~~";f[n_]:=If[n>0,r[c,n]~~"\n",""]~~r[t,n]~~"\n"~~r[m,n]~~"\n"~~r[t,n];f[0]:="Congratulations on your new baby! :D"

Welcome to PPCG, this challenge is known as code golf, where you try and make your code as short as possible. This can be done by removing unnecessary whitespace and shortening variable names.

Thanks @BetaDecay I was getting a fast version up.. minimising now. Cheers :D

No problem. Looks good :)

pb, 567 bytes
^w[B=45]{vb[-1]^b[0]>w[B!0]{t[B]b[0]>}<}w[B!0]{>}b[65]w[X!0]{w[B!65]{t[B]<t[B*10+T]b[0]>b[T]>}b[0]<t[B]b[0]<[X]>b[T]}^<<t[B]<b[B+T]w[B!0]{<vw[X!3]{b[0]vb[0]vb[0]^^>}^<<t[B]vvw[T!0]{b[124]^b[36]v>>t[T-1]}v<w[X!-1]{b[45]vb[126]vb[45]^^<}}^[Y]^<[X]>w[B=0]{>vvw[X!-1]{b[0]vb[0]^<}^>}t[111]b[67]>b[T]>b[110]>b[103]>b[114]>b[97]>b[116]>b[117]>b[108]>b[97]>b[116]>b[105]>b[T]>b[110]>b[115]>>b[T]>b[110]>>b[121]>b[T]>b[117]>b[114]>>b[110]>b[101]>b[119]>>b[98]>b[97]>b[98]>b[121]>b[33]>>b[58]>b[68]

I have some regrets.
There are some ways that this could be better. For example, upon figuring out that the input is negative, I then proceed to deduce which negative number it is. This is unnecessary, and maybe one day I'll dive back into this code to stop it.
Don't try to run this in pbi's "watch" mode, if you input a negative it'll crash when it tries to print chr(-1).
Here's the explained version version where I took notes while writing the program. If you'd like to better understand how it works... good luck, and let me know if you figure it out.
# parse number

^w[B=45]{vb[-1]^b[0]>     # if negative, put a -1 at (0, 0)
    w[B!0]{t[B]b[0]>} # move all digits left
<}
w[B!0]{>}b[65]        # put an "A" at the end of the number
w[X!0]{w[B!65]{             # while there's no "A" at the second digit
    t[B]<t[B*10+T]      # set T to (first digit * 10) + second digit
    b[0]                # destroy first digit
    >b[T]               # override 2nd digit with T
    >}                  # point at second digit to restart loop
b[0]<t[B]b[0]<[X]>b[T]} # draw the negative cake
^<<t[B]<b[B+T]w[B!0]{ # if it's positive
    <vw[X!3]{b[0]vb[0]vb[0]^^>} # erase the cake
    ^<<t[B]vvw[T!0]{b[124]^b[36]v>>t[T-1]} # draw the candles
    v<w[X!-1]{b[45]vb[126]vb[45]^^<}       # draw the cake
}^[Y]^<[X]>w[B=0]{>vvw[X!-1]{b[0]vb[0]^<}^>} # erase the part of the cake that would show up
# hardcoded string for input 0
t[111]b[67]>b[T]>b[110]>b[103]>b[114]>b[97]>b[116]>b[117]>b[108]>b[97]>b[116]>b[105]>b[T]>b[110]>b[115]>>b[T]>b[110]>>b[121]>b[T]>b[117]>b[114]>>b[110]>b[101]>b[119]>>b[98]>b[97]>b[98]>b[121]>b[33]>>b[58]>b[68]

ScriptCS (C# script), 221 bytes
Obviously this won't win any prizes, but...
var n=int.Parse(Env.ScriptArgs[0]);Console.WriteLine(n==0?"Congratulations on your new baby! :D":string.Join("\n",new[]{" $"," |","-","~","-"}.Select((s,i)=>string.Concat(Enumerable.Repeat(s,i>1?(n>0?n:1)*2+1:n>0?n:0)))))

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

Try it online!
-3 bytes from Erik

The non-competing policy doesn't exist anymore.

@EriktheOutgolfer Oh, didn't know about that. Answer fixed, thanks!

Oh, and a few bytes less.

Vyxal, 56 bytes
[0>`  -~-
`$[`$|-~-
`+|2]*`  -~-`+↵§|`Ṅƛ on λ¢ λɽ ÷Ḃ! :D

Try it Online!

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

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`

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)

@MikeS Thank you! The last update has also other improvements.

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

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.

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:
-$-$-$-$-$-
~|~|~|~|~|~
-----------

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.

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
        ;
}

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);
}

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

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";

You can save 12 bytes with a few changes

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

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"

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("--");
            }
        }
    }
}

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'

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");
}

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

---
~~~
---

Canvas, 52 bytes
‽“ｐｂｎ@；║Ｌ↶Ｆ{８ø⇵ohＵY÷²[Ｌ┘↗ＨＺ4ｖｙ）Ｃg⁰‟ｔ｝$¶|∙---¶~~~─∔ｒ×

Try it here!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
My god, it's full of spaces!
Some people insist on using spaces for tabulation and indentation.
For tabulation, that's indisputably wrong. By definition, tabulators must be used for tabulation.
Even for indentation, tabulators are objectively superior:

There's clear consensus in the Stack Exchange community.
Using a single space for indentation is visually unpleasant; using more than one is wasteful.
As all code golfers know, programs should be as short as possible. Not only does it save hard disk space, compilation times are also reduced if less bytes have to be processed.
By adjusting the tab width1, the same file looks different on each computer, so everybody can use his favorite indent width without modifying the actual file.
All good text editors use tabulators by default (and definition).
I say so and I'm always right!

Sadly, not everybody listens to reason. Somebody has sent you a file that is doing it wrongTM and you have to fix it. You could just do it manually, but there will be others.
It's bad enough that spacers are wasting your precious time, so you decide to write the shortest possible program to take care of the problem.
Task
Write a program or a function that does the following:

Read a single string either from STDIN or as a command-line or function argument.
Identify all locations where spaces have been used for tabulation or indentation.
A run of spaces is indentation if it occurs at the beginning of a line.
A run of two or more spaces is tabulation if it isn't indentation.
A single space that is not indentation may or may not have been used for tabulation. As expected when you use the same character for different purposes, there's no easy way to tell. Therefore, we'll say that the space has been used for confusion.
Determine the longest possible tab width1 for which all spaces used for tabulation or indentation can be replaced with tabulators, without altering the appearance of the file.
If the input contains neither tabulation, nor indentation, it is impossible to determine the tab width. In this case, skip the next step.
Using the previously determined tab width, replace all spaces used for tabulation or indentation with tabulators.
Also, whenever possible without altering the appearance of the file, replace all spaces used for confusion with tabulators. (If in doubt, get rid of spaces.)
Return the modified string from your function or print it to STDOUT.

Examples

All spaces of
a    bc   def  ghij

are tabulation.
Each run of spaces pads the preceding string of non-space characters to a width of 5, so the correct tab width is 5 and the correct output2 is
a--->bc-->def->ghij

The first two spaces of
ab  cde f
ghi jk lm

are tabulation, the others confusion.
The correct tab width is 4, so the correct output2 is
ab->cde>f
ghi>jk lm

The last space remains untouched, since it would be rendered as two spaces if replaced by a tabulator:
ab->cde>f
ghi>jk->lm

All but one spaces of
int
    main( )
    {
        puts("TABS!");
    }

are indentation, the other is confusion.
The indentation levels are 0, 4 and 8 spaces, so the correct tab width is 4 and the correct output2 is
int
--->main( )
--->{
--->--->puts("TABS!");
--->}

The space in ( ) would be rendered as three spaces if replaced by a tabulator, so it remains untouched.
The first two spaces of
  x yz w

are indentation, the others confusion.
The proper tab width is 2 and the correct output2 is
->x>yz w

The last space would be rendered as two spaces if replaced by a tabulator, so it remains untouched.
The first two spaces of
  xy   zw

are indentation, the other three are tabulation.
Only a tab width of 1 permits to eliminate all spaces, so the correct output2 is
>>xy>>>zw

All spaces of
a b c d

are confusion.
There is no longest possible tab width, so the correct output2 is
a b c d

Additional rules

The input will consist entirely of printable ASCII characters and linefeeds.
You may assume that there are at most 100 lines of text and at most 100 characters per line.
If you choose STDOUT for output, you may print a single trailing linefeed.
Standard code-golf rules apply.

1 The tab width is defined as the distance in characters between two consecutive tab stops, using a monospaced font.
2 The ASCII art arrows represent the tabulators Stack Exchange refuses to render properly, for which I have submitted a bug report. The actual output has to contain actual tabulators.

+1 for finally putting this nonsensical space/tab issue to rest :D

programs should be as short as possible I believe I have found Arthur Whitney's long-lost brother!!

@Dennis "That said, only a moron would use tabs to format their code." Clear consensus, eh?

Tabs are unholy demonspawn that deserve to have their bits ripped apart and their ASCII code disgraced until their incompetent lack-of-a-soul has been thoroughly ground into a pulp. Errr, I mean, +1, nice challenge, even though it reeks of blasphemy. ;)

I was crying each time a colleague add a tab in my beautiful space indented code. Then I discovered CTRL+K+F in Visual Studio. I do it each time I open a modified file. My life is better now.

Let's use 4 spaces for the 1st level and a tab for the 2nd, or 1 space for the 1st level for code golfing.

I don't understand "The last space remains untouched, since it would be rendered as two spaces if replaced by a tabulator:" in your second example. Why is it ghi>jk lm and not ghi>jk>lm or ghi jk lm, when both are confusion spaces?

@Fatalize Because a tabulator advances always to the next tab stop. With a tab width of 4, a single tabulator can replace 1, 2, 3 or even 4 spaces, depending on where it occurs.

Emacs-lisp, 8 bytes: (tabify)  (not really, of course, but this is close).

Pyth, 102 103 bytes
=T|u?<1hHiGeHGsKmtu++J+hHhGlhtH+tG]+HJ.b,YN-dk<1u+G?H1+1.)Gd]0]0cR\ .zZ8VKVNp?%eNT*hNd*/+tThNTC9p@N1)pb

Try it Online
Interesting idea, but since tabs in the input break the concept, not very usable.
Edit: Fixed bug. many thanks @aditsu

It crashes on "a b c d"

@aditsu crap! Thanx for the heads-up. I need better test cases :P

PowerShell, 414 409 bytes
function g($a){if($a.length-gt2){g $a[0],(g $a[1..100])}else{if(!$a[1]){$a[0]}else{g $a[1],($a[0]%$a[1])}}}{$a[0]}else{g $a[1],($a[0]%$a[1])}}}
$b={($n|sls '^ +|(?<!^)  +' -a).Matches}
$n=$input-split"`n"
$s=g(&$b|%{$_.Index+$_.Length})
($n|%{$n=$_
$w=@(&$b)
$c=($n|sls '(?<!^| ) (?! )'-a).Matches
$w+$c|sort index -d|%{$x=$_.Index
$l=$_.Length
if($s-and!(($x+$l)%$s)){$n=$n-replace"(?<=^.{$x}) {$l}",("`t"*(($l/$s),1-ge1)[0])}}
$n})-join"`n"

I went ahead and used newlines instead of ; where possible to make display easier. I'm using unix line endings so it shouldn't affect the byte count.
How To Execute
Copy code into SpaceMadness.ps1 file, then pipe the input into the script. I will assume the file that needs converting is called taboo.txt:
From PowerShell:
cat .\taboo.txt | .\SpaceMadness.ps1

From command prompt:
type .\taboo.txt | powershell.exe -File .\SpaceMadness.txt

I tested it with PowerShell 5, but it should work on 3 or higher.
Testing
Here's a quick PowerShell scrip that's useful for testing the above:
[CmdletBinding()]
param(
    [Parameter(
        Mandatory=$true,
        ValueFromPipeline=$true
    )]
    [System.IO.FileInfo[]]
    $File
)

Begin {
    $spaces = Join-Path $PSScriptRoot SpaceMadness.ps1
}

Process {
     $File | ForEach-Object {
        $ex = Join-Path $PSScriptRoot $_.Name
        Write-Host $ex -ForegroundColor Green
        Write-Host ('='*40) -ForegroundColor Green
        (gc $ex -Raw | & $spaces)-split'\r?\n'|%{[regex]::Escape($_)} | Write-Host -ForegroundColor White -BackgroundColor Black
        Write-Host "`n"
    }
}

Put this in the same directory as SpaceMadness.ps1, I call this one tester.ps1, call it like so:
"C:\Source\SomeFileWithSpaces.cpp" | .\tester.ps1
.\tester.ps1 C:\file1.txt,C:\file2.txt
dir C:\Source\*.rb -Recurse | .\tester.ps1

You get the idea. It spits out the contents of each file after conversion, run through [RegEx]::Escape() which happens to escape both spaces and tabs so it's really convenient to see what's actually been changed.
The output looks like this (but with colors):
C:\Scripts\Powershell\Golf\ex3.txt
========================================
int
\tmain\(\ \)
\t\{
\t\tputs\("TABS!"\);
\t}

Explanation
The very first line defines a greatest common factor/divisor function g as succinctly as I could manage, that takes an array (arbitrary number of numbers) and calculates GCD recursively using the Euclidean algorithm.
The purpose of this was to figure out the "longest possible tab width" by taking the index + length of every indentation and tabulation as defined in the question, then feeding it to this function to get the GCD which I think is the best we can do for tab width. A confusion's length will always be 1 so it contributes nothing to this calculation.
$b defines a scriptblock because annoyingly I need to call that piece of code twice, so I save some bytes that way. This block takes the string (or array of strings) $n and runs a regex on it (sls or Select-String), returning match objects. I'm actually getting both indentations and tabulations in one here, which really saved me extra processing by capturing them separately.
$n is used for different things inside and outside the main loop (really bad, but necessary here so that I can embed it in $b's scriptblock and use that both inside and outside the loop without a lengthy param() declaration and passing arguments.
$s gets assigned the tab width, by calling the $b block on the array of lines in the input file, then summing the index and length of each match, returning the array of the sums as an argument into the GCD function. So $s has the size of our tab stops now.
Then the loop starts. We iterate over each line in the array of input lines $n. The first thing I do in the loop is assign $n (local scope) the value of the current line for the above reason.
$w gets the value of the scriptblock call for the current line only (the indentations and tabulations for the current line).
$c gets a similar value, but instead we find all the confusions.
I add up $w and $c which are arrays, giving me one array with all of the space matches I need, sort it in descending order by index, and begin iterating over each match for the current line.
The sort is important. Early on I found out the hard way that replacing parts of a string based on index values is a bad idea when the replacement string is smaller and changes the length of the string! The other indexes get invalidated. So by starting with the highest indexes on each line, I make sure I only make the string shorter from the end, and move backwards so the indexes always work.
Into this loop, $x is in the index of the current match and $l is the length of the current match. $s can in fact be 0 and that causes a pesky divide by zero error so I'm checking for its validity then doing the math.
The !(($x+$l)%$s) bit there is the single point where I check to see if a confusion should be replaced with a tab or not. If the index plus the length divided by the tab width has no remainder, then we're good to go in replacing this match with a tab (that math will always work on the indentations and tabulations, because their size is what determined the tab width to begin with).
For the replace, each iteration of the match loop works on the current line of the input, so it's a cumulative set of replaces. The regex just looks for $l spaces that are preceded by $x of any character. We replace it with $l/$s tab characters (or 1 if that number is below zero).
This part (($l/$s),1-ge1)[0] is a fancy convoluted way of saying if (($l/$s) -lt 0) { 1 } else { $l/$s } or alternatively [Math]::Max(1,($l/$s)). It makes an array of $l/$s and 1, then uses -ge 1 to return an array containing only the elements that are greater than or equal to one, then takes the first element. It comes in a few bytes shorter than the [Math]::Max version.
So once all of the replaces are done, the current line is returned from the ForEach-Object (%) iteration, and when all of them are returned (an array of fixed lines), it's -joined with newlines (since we split on newlines in the beginning).
I feel like there's room for improvement here that I'm too burnt out to catch right now, but maybe I'll see something later.

 Tabs 4 lyfe

PHP - 278 210 bytes
The function works by testing each tab width, starting with a value of 100, the maximal length of a line and therefore the maximal tab width.
For each tab width, we split each line into "blocks" of that length. For each of this blocks:

If, by concatenating the last character of the previous block with this block, we find two consecutive spaces before a character, we have an indentation or a tabulation that can't be transformed to space without altering the appearance; we try the next tab width.
Otherwise, if the last character is a space, we strip spaces at end of the block, add a tabulator and memorise the whole thing.
Otherwise, we just memorise the block.

Once each blocks of a line have been analysed, we memorise a linefeed. If all the blocks of all the lines were analysed with success, we return the string we've memorised. Otherwise, if each strictly positive tab width have been tried, there was neither tabulation, nor indentation, and we return the original string.
function($s){for($t=101;--$t;){$c='';foreach(split('
',$s)as$l){$e='';foreach(str_split($l,$t)as$b){if(ereg('  [^ ]',$e.$b))continue 3;$c.=($e=substr($b,-1))==' '?rtrim($b).'   ':$b;}$c.='
';}return$c;}return$s;}

Here is the ungolfed version:
function convertSpacesToTabs($string)
{
    for ($tabWidth = 100; $tabWidth > 0; --$tabWidth)
    {
        $convertedString = '';
        foreach (explode("\n", $string) as $line)
        {
            $lastCharacter = '';
            foreach (str_split($line, $tabWidth) as $block)
            {
                if (preg_match('#  [^ ]#', $lastCharacter.$block))
                {
                    continue 3;
                }

                $lastCharacter = substr($block, -1);
                if ($lastCharacter == ' ')
                {
                    $convertedString .= rtrim($block) ."\t";
                }
                else
                {
                    $convertedString .= $block;
                }
            }

            $convertedString .= "\n";
        }

        return $convertedString;
    }

    return $string;
}

Special thanks to DankMemes for saving 2 bytes.

You can save 2 bytes by using for($t=101;--$t;) instead of for($t=100;$t;--$t)

CJam, 112
qN/_' ff=:e`{0:X;{_0=X+:X+}%}%_:+{~;\(*},2f=0\+{{_@\%}h;}*:T;\.f{\~\{@;1$({;(T/)9c*}{\;T{T%}&S9c?}?}{1$-@><}?}N*

Try it online
I had to answer this challenge, because I must do my part to help rid the world of this abomination. Tabs are obviously superior, but sadly, some people just can't be reasoned with.
Explanation:
qN/          read input and split into lines
_            duplicate the array (saving one copy for later)
' ff=        replace each character in each line with 0/1 for non-space/space
:e`          RLE-encode each line (obtaining chunks of spaces/non-spaces)
{…}%         transform each line
  0:X;       set X=0
  {…}%       transform each chunk, which is a [length, 0/1] array
    _0=      copy the first element (the length)
    X+:X     increment X by it
    +        and append to the array; this is the end position for the chunk
_            duplicate the array (saving one copy for later)
:+           join the lines (putting all the chunks together in one array)
{…},         filter the array using the block to test each chunk
  ~          dump the chunk (length, 0/1, end) on the stack
  ;          discard the end position
  \(         bring the length to the top and decrement it
  *          multiply the 2 values (0/1 for non-space/space, and length-1)
              the result is non-zero (true) iff it's a chunk of at least 2 spaces
2f=          get all the end positions of the multiple-space chunks
0\+          prepend a 0 to deal with the empty array case
{…}*         fold the array using the block
  {_@\%}h;   calculate gcd of 2 numbers
:T;          save the resulting value (gcd of all numbers) in variable T
\            swap the 2 arrays we saved earlier (input lines and chunks)
.f{…}        for each chunk and its corresponding line
  \~         bring the chunk to the top and dump it on the stack
              (length, 0/1, end position)
  \          swap the end position with the 0/1 space indicator
  {…}        if 1 (space)
    @;       discard the line text
    1$(      copy the chunk length and decrement it
    {…}      if non-zero (multiple spaces)
      ;      discard the end position
      (T/)   divide the length by T, rounding up
      9c*    repeat a tab character that many times
    {…}      else (single space)
      \;     discard the length
      T{…}&  if T != 0
        T%   calculate the end position mod T
      S9c?   if non-zero, use a space, else use a tab
    ?        end if
  {…}        else (non-space)
    1$-      copy the length and subtract it from the end position
              to get the start position of the chunk
    @>       slice the line text beginning at the start position
    <        slice the result ending at the chunk length
              (this is the original chunk text)
  ?          end if
N*           join the processed lines using a newline separator

PowerShell, 165 160 153 152 142 138 137 bytes
param($s)@((0..99|%{$s-split"(
|..{0,$_})"-ne''-replace(' '*!$_*($s[0]-ne32)+' +$'),"`t"-join''})-notmatch'(?m)^ |\t '|sort{$_|% Le*})[0]

Try it online!
Less golfed:
param($spacedString)

$tabed = 0..99|%{
    $spacedString `
        -split "(\n|..{0,$_})" -ne '' `
        -replace (' '*!$_*($spacedString[0]-ne32)+' +$'),"`t" `
        -join ''
}

$validated = $tabed -notmatch '(?m)^ |\t '

$sorted = $validated|sort{$_|% Length}    # sort by a Length property

@($sorted)[0]  # $shortestProgram is an element with minimal length

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Calculate A(N) / B(N) with C(N) digits
Consider three number sequences, \$A\$, \$B\$ and \$C\$:

\$A\$: A sequence based on recurrence relations, \$f(n) = f(n-1)+f(n-2)\$, starting with \$f(1) = 3, f(2) = 4\$. So, the sequence begins like this: \$3, 4, 7, 11, 18, 29, 47, 76, ...\$
\$B\$: The composite numbers, that is all integers that aren't primes (or 1): \$4, 6, 8, 9, 10, 12, 14, 15, 16, ...\$
\$C\$: The digits of \$\pi\$: \$3, 1, 4, 1, 5, 9, 2, 6, 5, ...\$

Given a positive integer \$N < 50\$, either as function argument or STDIN, return the decimal value of the fraction \$\frac{A(N)}{B(N)}\$ with \$C(N)\$ digits after the decimal point. Normal rules for rounding applies (round up if the \$N+1\$'th digit is 5 or higher). If the Nth digit of \$\pi\$ is zero, an integer should be printed. scientific notation / Standard form is accepted for numbers higher than 1000.
This is code golf, so the shortest answer in bytes wins.
Some examples:
N = 1: 0.750
N = 2: 0.7
N = 3: 0.8750
N = 4: 1.2
N = 6: 2.416666667
N = 10: 11.056
N = 20: 764.8750

Of course, standard code golf rules applies.
The function must terminate in less than two minutes on any modern laptop.

When you say C(n) digits, do we have to include trailing 0's?

To which input does the time limit apply?

@Dennis, do you mean to which N? If so, up to N = 49. Or something else?

JavaScript has a limited floating point accuracy of 16. Past that you'll start getting inaccurate results. Is this okay?

@vihan My solution (unpublished ATM) stores the first 49 digits of pi in a string. And you don't need any more than 9 digits of accuracy in the result, if you're worried about that.

@vihan, I think ETHproductions answered it well. You only need to output 9 digits after the decimal points. Those 9 should be exact. There are algorithms for calculating only the N'th digit of pi (I'll admit: I don't know how big accuracy you need to calculate the 49th). You can also follow ETHprocuctions tips.

Pyth, 60 57 58 bytes
.[K`.Rchu,eGsGQjT7e.ftPZQ)Je/u+/*GHhyHy^TQr^T3ZZT\0+xK\.hJ

Test harness
It's pretty straightforward - calculate pi, the fibonacci series and the composites, round to C(n) digits, pad to C(n) digits plus the location of the decimal point digits, done.
A(n): hu,eGsGQjT7
B(n): e.ftPZQ)
C(n): e/u+/*GHhyHy^TQr99ZZT
60 -> 57: Cleaned up the n = 1 special case in the pi calculation.
57 -> 58: Wasn't using high enough precsion for pi for the entire input range - increased 99 iterations to 1000 iterations.
Note on rounding: This uses Python's "nearest even" rounding system, rather than the OP specified "towards infinity" system. However, the difference only matters if the digits immediately following the rounding point are 5000..., e.g. 1.25 rounded to 1 digit. I checked the input range, and this never happens, so the correct result is alway returned.

PowerShell, 420 Bytes (ayyyyyyyy) 378 Bytes
param($n);[int[]]$p="03141592653589793238462643383279502884197169399375"-Split'';$a=@(0,3,4);for($i=3;$i-lt50;$i++){$a+=$a[$i-1]+$a[$i-2]};$c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111";$b=@(0);for($i=4;$i-le70;$i++){if($c[$i]-eq'1'){$b+=$i}};[double]$r=$a[$n]/$b[$n];$q=$p[$n+1];$s="";(0..($q-1))|%{$s+="0"};([math]::Round($r,$q,[MidpointRounding]::AwayFromZero)).ToString("0.$s")

Thanks to isaacg for saving 41 bytes, for calculating how the question does rounding. Means I didn't have to include the horrendous [MidpointRounding]::AwayFromZero and didn't need to explicitly cast as a [double].
This one was great fun!
Expanded:
# Take input N
param($n)

# First digits of pi, stored as integer array
[int[]]$p="03141592653589793238462643383279502884197169399375"-Split''

# Fibonacci sequence A(N)
$a=@(0,3,4)
for($i=3;$i-lt50;$i++){
  $a+=$a[$i-1]+$a[$i-2]
}

# Zero-indexed bitmask for if the n-th integer is composite (1) or not (0)
$c=[char[]]"00001010111010111010111011111010111110111010111011111011111010111110111"

# Populate B(N) as an array using the $c mask
$b=@(0)
for($i=4;$i-le70;$i++){
  if($c[$i]-eq'1'){
    $b+=$i
  }
}

# Calculation Time!
$r=(a($n))/$b[$n]

# A small golf, as $p[$n+1] gets used a couple times
$q=$p[$n+1]

# Need to generate a string of zeroes for padding
$s=""
(0..($q-1))|%{$s+="0"}

# Round the number, then send it to a string so we get the necessary number of zeroes
([math]::Round($r,$q)).ToString("0.$s")

Recursion in PowerShell is ... slow, shall we say, so we have to build A(N) the other direction and store it into an array, then index it.

OLD
Also, holy cow, did the output requirements kill this. PowerShell defaults to rounding-to-nearest a/k/a banker's rounding, which necessitates utilizing the extraordinarily verbose [MidpointRounding]::AwayFromZero to switch rounding styles. On top of that, we then needing to pad trailing zeroes, if any. Those two requirements combined to turn the last couple of lines from 20 Bytes [math]::Round($r,$q) to 102 Bytes (from the $s="" to +$s)) ... wow.

Great description/commenting! 32 chars for [MidpointRounding]::AwayFromZero alone is almost too good/bad to be true... =)

See my note on rounding in my answer. PowerShell default rounding should be fine.

Javascript (ES6), 302 bytes
One word: Unfinished.
x=>{a=[0,3,4],b=[0],c='03141592653589793238462643383279502884197169399375';for(i=1;i<x;a[i+2]=a[i]+a[++i]);for(i=1,p=[];++i<70;v=p.every(x=>i%x),(v?p:b).push(i));r=''+Math.round(a[x]/b[x]*(l=Math.pow(10,c[x])))/l;if(x==33)return r;r.indexOf`.`<0&&(r+='.');while(!r[r.indexOf`.`+ +c[x]])r+='0';return r}

The first 49 digits of pi are stored in a string, and the other two sequences are auto-generated. This has been golfed about halfway; I'm (almost) sure I could squeeze another 50 bytes out of it.
Works for all the test cases, and should work for the rest. Crashes on anything more than 49 or less than 0 (it should never encounter these situations anyway). I especially like its result for 0:
NaN.

Why is this unfinished?

@BetaDecay I meant I haven't finished golfing it yet. I will as soon as I have the time.

Octave, 276 236 Bytes
First of all I thought it would be cool to make use of some unlimited accuracy in these mathematical tools (and to refresh some knowledge about it) so I started writing some algorithms and then ended finally found out that the pi value is not so accurate that I will have to use the array again. So again, no great success:
function c(A)p="3141592653589793238462643383279502884197169399375";f=ones (1,50);f(1)=3;f(2)=4;for i=3:53f(i)=f(i-1)+f(i-2);end
i=0;x=1;while i<A
x++;for j=2:x/2
if mod(x,j)==0 i++;break;end end end
printf(["%." p(A) "f\n"],f(A)/x);end

Still quite readable, isn't it?
Usage
copy-paste function into octave, call function c with argument of required value:
>>> c(1)
0.750
>>> c(49)
407880480.04348

Optimizations:

Substitute endif, endfor and similar with end which works the same way
decreasing variable i by one save one byte
remove num2str(str2num(p(A))) nonsense :)

I like that you posted a Octave solution (I'm a MATLAB guy myself!). Note that this code is Octave only, not MATLAB. MATLAB uses end, not endif, so many bytes saved. If you also happen to have the symbolic toolbox for MATLAB, you can use vpa to get enough decimal points for pi: vpa(sym(pi),49). I don't have it at this laptop, so I'm not sure if the sym is necessary there, but should save quite some bytes anyways =) And readable is not necessarily a good thing in code golf =)

x++ is also not a MATLAB command. I didn't know there were such large differences between the two... IMO, it shouldn't be. I think all code written in Octave should be portable to MATLAB (but not necessarily the other way around as MATLAB has more options).

Approved your edit. I don't have matlab around here so I was unable to test it. I was searching for solution to get more pi decimals in octave, but nothing was shorter than just array, unfortunately. But ommiting while from endwhile and similar works fine, so I'm updating the answer with few less characters :)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Lookup without conditional statements
This challenge was inspired by programming an Arduino microcontroller. I have 6 LEDs and 6 buttons connected to various pins on the board. In the code, each button and LED is assigned an ID number (1-6). Pin numbers (ranging from 0-13) corresponding to the ID numbers are looked up using a switch statement. Purely for amusement, I was wondering if these switches could be circumvented with an arithmetic/other function just to horrify future code maintainers.
The challenge
Provide the function/functions that take the ID number (integer) as a parameter and return the pin number (integer) for the 6 LEDs and/or the 6 buttons, without using conditional statements (no if, no switch and no ternary).
Return values for LEDs:
ID    Pin
1      3
2      5
3      6
4      9
5     10
6     11

Return values for buttons:
ID    Pin
1      2
2      4
3      7
4      8
5     12
6     13

Bonus challenge
Provide a single function that takes an ID number (integer) and second parameter (any type) indicating whether LED or button pins are requested, and returns the corresponding pin (integer).
Rules
This is not an Arduino-specific challenge. Use any language, do whatever you want.
Edit: at the suggestion of steveverril, this is now a code golf challenge.
Good luck!
(If you're still reading: although patently absurd and arbitrary by programming standards, the mappings are based on the Arduino Micro's pinout. Pins 0 and 1 are reserved for serial communication, LEDs are assigned to the 6 lowest-numbered PWM-capable pins, buttons are assigned to remaining pins)

WeIcome to PPCG! I didn't downvote, but I think this would go better as a codegolf. Popularity contest is very broad in a situation like this. BTW, you can post questions at our sandbox http://meta.codegolf.stackexchange.com/q/2140/15599 to have them reviewed prior to posting

When you say "no if", can I use use a conditional expression as an integer? E.g. 1+(1==1)?

Yes, those are fine. Only the three statements mentioned in the challenge (if, switch and ternary) are off limits.

Related

@steveverrill thank you for the suggestion, challenge is now code golf. Had I met the reputation requirement of +5 for meta, I would have posted in the Sandbox :) So double thank you for not downvoting a lowly +1 rep casual.

C, 28 bytes each
p(i){return"@cefijk"[i]&15;}
b(i){return"@bdghlm"[i]&15;}

This is basically the same as the answer by kirbyfan64sos, but uses a char array instead of integers, and has a dummy first byte so there is no need to subtract 1 from the function parameter.

Haskell, 24 bytes each
l 1=3
l n=n+l(div(n+2)3)

to check:
> map l [1..6]
[3,5,6,9,10,11]

.
b 1=2
b n=n+b(div(n+1)2)

to check:
> map b [1..6]
[2,4,7,8,12,13]

bonus, Haskell, 36 bytes
a f 1=f+2
a f n=n+a f(n+f+1`div`f+2)

to check:
> map (a 0) [1..6]
[2,4,7,8,12,13]
> map (a 1) [1..6]
[3,5,6,9,10,11]

0 for buttons, 1 for LEDs.

In the bonus, you should be able to use a f n=n+a f(n+f+div 1f+2).

Yuck! I know it's not in the spirit of codegolf, but this is way too late and too minor to edit a perfectly good solution. Appreciate the attention (to detail) though

How is it ever too late?

C (math), 32 / 27 26 bytes (45 for bonus challenge)
Several people have posted various table-lookup solutions, but that seemed to me like taking the easy way out.. I wanted to see how well I could do with purely mathematical operations:
p(i){return~i&1|i*2^i*!(i%5-1);}
b(i){return i/5*5+1^p(i);}

It wasn't clear whether one function calling the other was acceptable or not; if not, one can use this alternate definition of b(i) (33 bytes) instead:
b(i){return(i&1|i*2)+i/5-!(i/2);}

Bonus Challenge (45 bytes):
f(i,t){return(i&1|i*2)+i/5-!(i/2)^t+i/5*5*t;}

(pass t=0 for buttons, t=1 for LEDs)

C, 36 bytes each (49 bytes for the bonus challenge)
p(i){return 3500459>>(4*(7+~i))&15;}
b(i){return 2390221>>(4*(7+~i))&15;}

I'm sorry...I just couldn't help it... Ok, I put a real solution now.
Bonus challenge, 49 bytes
f(i,t){return(2390221+t*1110238)>>(4*(7+~i))&15;}

Use f(button,0) and f(pin,1).
Live demo at Ideone.

Originals:
p(i){int a[]={3,5,6,9,10,11};return a[i-1];}
b(i){int a[]={2,4,7,8,12,13};return a[i-1];}

If I wanted sensible answers, I wouldn't be posting in PPCG now would I :P
Interestingly, using this in the actual Arduino program results in a larger size for the compiled binary (which, given ~28K of storage space on the board, is something to be avoided).

How about p(i){return"@cefijk"[i]&15;}b(i){return"@bdghlm"[i]&15;}?

@squeamishossifrage You should post those as your own answer. They're better than mine is. :)

@kirbyfan64sos Oh ok then

Pyth - 12 bytes each
Base encodes the array.
@jC"Ý"14tQ (buttons)
@jC"\r'"12tQ (leds)

The last one is actually twelve bytes except I can't write a carriage return so i escaped it.
Test Suite for Buttons.
Test Suite for LEDS.

I think the OP intended for this to be a function ("Provide the function/functions"); with that it should be trivial to get the bonus: something like M@jC@"\rÝ"H+12*G2, which uses 0 for pins and 1 for buttons should work.

Pyth, Bonus only: 20 bytes
M@jC"5i«$xÍ"16+*6HtG

param#2 is 0 for LEDs, 1 for Buttons.  To get Pin# for LED4,g4 0
I would have posted this as a comment to Maltysen's entry, but I just started, so lack the required reputation. I've just started using PYTH tonight, and admit that I shamelessly adapted his method of efficiently encoding a list.
If this was inappropriate, my deepest apologies, and I'll remove my entry.

Hey Brian Tuck! I'm glad you've started using my language. This reuse of Maltysen's idea was probably fine, since base encoding isn't exactly a new idea. Giving credit, which you did, is important, however. By the way, Pyth shouldn't be written in all caps - it's not an acronym, it's just a name.

MIPS, 16 bytes
Bit shifting and bitmask. Input in $a0, output in $v0.
sll     $t0, $a0, 2
li      $t1, 0xba96530
srlv    $t0, $t1, $t0
andi    $v0, $t0, 0xf

For bonus, use immediate 0xdc87420

Aren't we supposed to count the size of the source when golfing? :)

F#, 28+28 bytes
I wanted to try this without a lookup table.
let L x=1+x*2-x%4/3-x/5-x/6
let B x=x*2+x/3-x/4+x%6/5*2

SWI-Prolog, 34 bytes each
l(I,P):-nth1(I,[3,5,6,9,10,11],P).
b(I,P):-nth1(I,[2,4,7,8,12,13],P).

l/2 is for LEDs, b/2 is for buttons.
Bonus, 66 bytes
a(I,S,P):-nth1(I,[3:2,5:4,6:7,9:8,10:12,11:13],A:B),(S=0,P=A;P=B).

S = 0 for LEDs, anything else for Buttons.

q/k (18 bytes each)
Simply a case of indexing:
L:0N 3 5 6 9 10 11
B:0N 2 4 1 8 12 13

Example:
q) L[2]
5
q) B[6]
13

Bonus (1 byte, given L & B defined)
@

Example:
q) @[`L;2]
5
q) @[`B;6]
13

This is deceptively clever use of symbols! +1

CJam, 10 bytes each
These are anonymous functions. The links to the online interpreter show then within a small test harness that executes the function for all input values.
Function 1 (LEDs):
{5*3|4+3/}

Try it online
Function 2 (buttons):
{_6|5+*5/}

Try it online
I wrote a small program that generates and evaluates these expressions. For both of them, it found a number of solutions with 8 characters (counting the expression only without the braces), but none with less.

Javascript (ES6), 26/27 bytes
LEDs:
a=>`0
`.charCodeAt(a)

Buttons:
a=>`0\r`.charCodeAt(a)

If the above doesn't run (which is likely), here's a hexdump:
00000000: 6C 3D 61 3D 3E 60 30 03 - 05 06 09 0A 0B 60 2E 63 |l=a=>`0      `.c|
00000010: 68 61 72 43 6F 64 65 41 - 74 28 61 29 0A 62 3D 61 |harCodeAt(a) b=a|
00000020: 3D 3E 60 30 02 04 07 08 - 0C 5C 72 60 2E 63 68 61 |=>`0     \r`.cha|
00000030: 72 43 6F 64 65 41 74 28 - 61 29                   |rCodeAt(a)|

I couldn't get the second one to work with a raw CR so I had to use \r
Bonus, 41 bytes
(a,b)=>`0
\r`.charCodeAt(a+b*6)

Hexdump
00000000: 28 61 2C 62 29 3D 3E 60 - 30 03 05 06 09 0A 0B 02 |(a,b)=>`0       |
00000010: 04 07 08 0C 5C 72 60 2E - 63 68 61 72 43 6F 64 65 |    \r`.charCode|
00000020: 41 74 28 61 2B 62 2A 36 - 29                      |At(a+b*6)|

Second parameter is 0 for LEDs, and 1 for buttons.

JavaScript 113 74 66 59 52 33 (one function)
Using bit shift to get 4bit values. Must be called with p(n, 195650864 or 231240736).
/*
  11   10    9    6    5    3
1011 1010 1001 0110 0101 0011 0000 = 195650864

  13   12    8    7    4    2
1101 1100 1000 0111 0100 0010 0000 = 231240736

                   b >> i * 4 xxxx
                         & 15 1111
                              yyyy (matching 1s)
*/
// Where b = 195650864 for pins and 231240736 for buttons.
function p(i,b){return b>>i*4&15}

Alternate.
/*
Using bitwise * 4 for bitwise only.
function p(i,b){return b>>(i<<2)&15}
*/

Brainf**k, 107 bytes
,>++++++++[>+>++++++<<-<------>]<[>+++<-[>++<-[>+<-[>+++<-[>>>+>+<<<[-]+<-]]]]]>>[<++++++>-]<.>>>[-[-]<-.>]

This being my first hand-coded BF program, I don't doubt that there are several optimizations to be made. But it's still awesome. :)
I'm not sure if [] counts as a conditional, though... :/

We have a challenge full of BF optimisers at your disposal if you wanted to use one ;)

@BetaDecay They look great, but none of them actually make my code any shorter... :/

Hm, that's a shame :P

POWERSHELL - 27-27-72
LED use 1..6 as args
:\>wc -c LED.PS1 & cat LED.PS1 & echo.& powershell -nologo -f LED.PS1 1
27 LED.PS1
(0,3,5,6,9,10,11)[$args[0]]
3

button use 1..6 as args
:\>wc -c button.PS1 & cat button.PS1 & echo.& powershell -nologo -f button.PS1 6
27 button.PS1
(0,2,4,7,8,12,13)[$args[0]]
13

LED or BUTTON use b 1 ; l 2 ; b 6 ; l 5 etc as args
:\>wc -c ledbutt.PS1 & cat ledbutt.PS1 & echo.& powershell -nologo -f ledbutt.PS1 b 5
72 ledbutt.PS1
$a=@{"b"=(0,3,5,6,9,10,11);"l"=(0,2,4,7,8,12,13)};$a[$args[0]][$args[1]]
10
:\>powershell -nologo -f ledbutt.PS1 l 5
12
:\>powershell -nologo -f ledbutt.PS1 b 3
6
:\>powershell -nologo -f ledbutt.PS1 l 2
4

Octave, 40 bytes (bonus challenge)
Using an anonuymous function:
@(x,y)[3 2;5 4;6 7;9 8;10 12;11 13](x,y)

After defining this function, call this function as ans(x,y), where x is the pin/button number and y indicates pin or button with values 1 and 2 respectively.
Try it online

JavaScript(ES6) 18,22,44
Edit Shorter but boring

// LED
l=i=>1-~' 134789'[i]
// Buttons
b=i=>[,2,4,7,8,12,13][i]

// bonus
f=(i,t)=>1-~[' 134789',[,0,2,5,6,10,11]][t][i]

//Test

out=x=>O.innerHTML+=x+'\n'

for(i=1;i<=6;i++) out(i +' -> '+l(i) + ' '+b(i) +' '+f(i,0)+' '+f(i,1))

Perl 4 (37 and 31 bytes)
LEDs (37 bytes):
$c=pop;$c*2+($c~~[1,2,4,6]&&5.5<=>$c)

... but it uses a lookup table.
Buttons (31 bytes, no lookup):
$c=pop;2*($c+($c==5))+($c%3==0)

Python, 31 Bytes Each
Not exactly creative or anything, but it works!
l=lambda x:int(" 3569AB"[x],16)
b=lambda x:int(" 2478CD"[x],16)

Bonus, 44 Bytes
k=lambda x,y:int("3569AB2478CD"[x-1+6*y],16)

y should be 0 for LEDs, and 1 for buttons.

Python, 60 + 58 = 118 bytes
p=lambda i:(2**i)*(i<3)+1+(i>2)*(5+3*(i-3))-(i>4)*(i-3+~i%2)
b=lambda i:2**i-(i>2)-(i>3)*(2**(i-1)-1)-4*(i>4)-15*(i==6)

These are awful. i don't even know what I'm doing here...
But they're pretty interesting nonetheless! :D

Ruby, 45 Bytes
->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}

Test Inputs:
->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 1,0
=> 3

->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 3,1
=> 7

Forth, 26 bytes each, 34 for bonus
Similar to the C version by squeamish.
: P " CEFIJK" + C@ F AND ;
: B " BDGHLM" + C@ F AND ;

Bonus:
: A " CEFIJKBDGHLM" + + C@ F AND ;

Use 0 for LEDs and 6 for buttons. And the parameter order doesn't matter

Pyth, 19 bytes each
L.&.>3500459*4-6b15
L.&.>2390221*4-6b15

For pins and buttons, respectively.


text:
Role-Playing Game Dice-Rolling
Background
When playing an RPG such as Dungeons & Dragons, Pathfinder, or Paranoia, players each need a set of dice. You are hosting one such game this weekend, and some of the friends you invited have never played an RPG before. They don't want to commit to buying their own set of dice until they know they'll use them (if they want to keep playing). This is fine and dandy with you, but you're not going to let them use your lucky set of dice that you pre-rolled the ones out of...
Goal
...so you are going to write a program or function that simulates the dice-rolling for them.
Dice are often described in the format: <How many dice>d<Number of sides> A common set of dice for RPG use includes: 1d4, 1d6, 1d8, 2d10 (also used as 1d% or 1d100), 1d12, and 1d20.
Your code must accept a string of any number of the above dice specifiers separated by spaces or commas as input. It must then output the result of each individual die-roll separated by spaces, with parentheses around groups; then the sum of each grouping on the next line, separated by spaces; and finally, the total sum on a third line. Single-die groups don't have parentheses. Dice must always be in the same order as provided in the input.
The percent die, whether written as 1d% or 1d100, should be calculated as the concatenation of 2d10 (just 2 rolls, each from 0-9, but a final result of zero is instead counted as 100), but each occurrence will be displayed as if a single roll. 2d10 in the input will still be treated and displayed as 2 individual rolls. It can be easy to get confused by percent dice, here's a good explanation.
Edit: To clarify, the number of rolls may exceed 9.
Examples
Input:
1d4 3d6 2d8

Possible Output:
3 (1 5 2) (8 4)
3 8 12
23

Input:
1d20 1d% 2d10 1d100 5d12

Possible Output:
16 100 (9 4) 42 (5 1 7 7 11)
16 100 13 42 31
204

Rules

Standard loopholes are disallowed.
Printable ASCII in code, only.
code-golf - shortest code wins.
-10 bytes if the rolls are actually random, rather than pseudo-random.

So, wait. Am I right that the d10s are 0-9 but the others are 1-n? Or do they also go 0 to (n-1)? Clearly the d100s are supposed to have values 1-100.

Very closely related.

@DLosc I was only specifying how to calculate a d%. 1d10 is still in the range 1-10.

@mbomb007 I didn't say duplicate. ;)

For the percentage die, couldn't a program just generate a single (pseudo-)random number between 1 and 100? If so, what's the reason for  calculating it as the concatenation of 2d10 and special-casing 00?

I imagine because that's how it's handed in DnD.

Yes, but this is code golf. If generating a number in the right range is equivalent and takes fewer bytes, can my program just do that?

@DLosc I guess so. Makes the most sense.

Will the number of rolls always be single-digit?

@Trebuchette No. I didn't show it in my examples, but the number of rolls can be more than a single digit.

Pyth, 48 bytes
-jdm?td(.*dhdJ.bmOSYNmm.xsk100cd\dcz))\,jdsMJssJ

Test Suite
Tricks / golfs in this code:

Everything that's not a number will be treated as 100, not just %.
To get the parentheses, I make the list into a tuple, then subtract out the commas.
This is the first time I've used .b, the binary map, which was added 3 days ago.
The code contains 6 different map functions.

This shows one use for not exorcising tuples, or at least making it .(

Pyth - 56 bytes
Nothing fancy, many nested maps. As OP said above in comments, we don't need to do the concatenating thing, just recognizing % is enough.
jdm?tld++\(j\ d\)j\ dKmmhOeGh=GsMcsXd\%]100\dczdjdJsMKsJ

Test Suite.

Lua, 183 bytes
a=arg[1]:gsub("(%g+)d(%g+)",function(r,d)d=d=="%"and 100 or d n=tonumber(r)s=n>1 and"("or""for i=1,r do s=s..math.random(d)..(i<n and" "or"")end return s..(n>1 and")"or"")end)print(a)

Pyth, 59 bytes
JmhMOMd.b*N]?YY100mvdcXz",d%"" ,0";-jdm?td(.*dhdJ\,jdsMJssJ

Test Suite
Unfortunately, neither isaacg's nor Maltysen's answer handles commas properly.  When/if isaacg fixes it, I'm sure his will remain smaller.

R, 200 bytes
for(d in strsplit(scan(,""),"d")){d=gsub("%","100",d);u=d[1]>1;cat(if(u)"(",paste(i<-sample.int(d[2],d[1],T),collapse=" "),if(u)")"," ",sep="");F=c(F,sum(i))};cat("\n");cat(F[-1],"\n");cat(sum(F[-1]))

Try it online!
for(d in strsplit(scan(,""),"d")){
    d=gsub("%","100",d)                                # replace "%"
    u=d[1]>1                                           # whether to print parenthesis
    cat(if(u)"(",
        paste(i<-sample.int(d[2],d[1],T),collapse=" "),# dice rolls
            if(u)")",
            " ",
            sep="")
        F=c(F,sum(i))}
cat("\n")
cat(F[-1],"\n")                                        # sum of rolls of a certain type
cat(sum(F[-1]))                                        # sum of all dice rolls.

This can be shortened for sure... this is a naïve implementation with a for loop.