title: Fun with Matching Braces

text:
# Question
Title: Fun with Matching Braces
The contest is to make a program or function that takes an arbitrary string resembling source code and checks to see if the "braces" follow the basic rules for brace matching. That is, the number of left braces and right braces have to match, and you can't have a right brace without a corresponding prior left brace.

You may choose to use any "brace" among `(` `[` `{` `<`

Your program must output/return a true-y value or 'Y' if the input is legal and a false-y value or 'N' if the input is illegal.

**Scoring**

Your score is the number of bytes in your source minus bonuses.

**Bonuses**

* -20 per each additional brace type handled among `(` `[` `{` `<`
* -30 if you handle multiple brace types and don't allow mismatched braces like `<(>)`
* -50 points if you handle `/* */` or `//` comments (the same way C or Java does)
* -20 points if you handle both types of comments
* -50 if you ignore braces inside `'` and `"` quotes. To get the points you also have to check that quotes properly match. Eg: `("')"')` is not a valid "program" but `("')")` is. You do not have to worry about escaped characters. `"\""` is an illegal program if you go for this bonus.

So if your program is 327 ASCII characters long, handles `(` and `[`, doesn't check mismatching, and handles `//` comments and quotes, you get:

327 - 20 * 1 - 0 - 50 - 0 - 50 = **207** points

**EDIT:** Added bonuses for ignoring braces inside `'` and `"` quotes
**EDIT 2:** Return values cannot be any string. Must be true/false 1/0 'Y'/'N' ect.
**EDIT 3:** Since there is some confusion, here is some pseudo-BNF to give an idea of what is expected.

Grammar for minimal program:
exprs = expr exprs
expr = ( exprs ) || not\_braces\* || nil

Grammar for all bonuses:
exprs = expr exprs
expr = ( exprs ) || \[ exprs \] || { exprs } || \< exprs \> || // not\_newline\* \n || /\* not\_end\_comment\* \*/ || not\_braces\* || nil

Note that if you do the bonuses, you will both accept and reject things that the basic program would not.

# Answer
> 5 votes
# Perl, (~~136~~ ~~130~~ 129 chars - (20\*3) - 30 - 50 - 20 - 50) == -81

\<3 recursive REs.

```
$/=$_;print!(<>!~m#^(([^][<{('"/)}>]|'[^']*'|"[^"]*"|/((?![*/])|\*((?!\*/).)*\*/|/[^\n]*+)|<(?1)>|\((?1)\)|\[(?1)]|{(?1)})*)$#s)

```

# Answer
> 7 votes
## PHP, -4 (156 - 20\*3 - 30 - 50 - 20)

```
<?php $x=preg_replace("!(//.*|/\*.*\*/|[^()[\]{}<>])!sm",'',$argv[1]);while(strlen($x)!=strlen($x=str_replace(str_split('()[]{}<>',2),'',$x)));print $x?0:1;

```
1. It removes comments
2. It filters out all characters different than (, ), \[, \], {, }, \<, \>
3. It replaces all (), \[\], {}, \<\> pairs until there are no matches
4. Prints 1 if the string is empty, 0 otherwise

(*Edit: changed the regex; the source code is now 156 instead of 175*)

# Answer
> 6 votes
# GolfScript, 38 chars − 3 × 20 − 30 = −52 points

```
0\{")]>}([<{"?.4/"4^^{0}*

;"n/=~}/;]!

```

Prints `1` if all the braces in the input are correctly balanced, `0` otherwise.

Bonus points for:

* handling all four types of braces: 3 × 20 points
* not allowing mismatched braces: 30 points

This solution uses the GolfScript internal stack to keep track of which braces have been seen so far. When an opening brace is encountered, it is pushed onto the stack; when a closing brace is encountered, the code checks if there's a matching opening brace on the stack. If there is, it is popped off; otherwise a sentinel value (0) matching no brace is push onto the stack, ensuring that it cannot ever be popped off.

One such sentinel value is pushed onto the stack at the beginning, to guard against stack underflow if there are too many closing braces. At the end, the program simply checks whether the stack is empty except for the initial sentinel value.

# Answer
> 3 votes
# Lua - 51

```
print(not not("("..io.read"*a"..")"):match"^%b()$")

```

What this program is doing, is wrapping the input string in `()`, then it matches it against a pattern (not a regex). The pattern matches beginning of string followed by string containing balanced parentheses, followed by end of string.
On a successful match, the whole string is returned, which is turned into `true` by `not not`. If match is unsuccessful, `nil` is returned, which turns info `false` because of `not not`.

# Answer
> 3 votes
## C, 70 62 61

```
A;main(c){for(;~c&~A;c=getchar())A-=c==41,A+=c==40;exit(!A);}

```

Alternatively, supporting all bracket types: 147 - (3\*20) = 87

```
A,B,C,D;main(c){for(;~(c=getchar())&~A&~B&~C&~D;)c-40?c-41?c-91?c-93?c-'{'?c-'}'?c-60?c-62||D--:D++:C--:C++:B--:B++:A--:A++;puts(A|B|C|D?"N":"Y");}

```

The program reads in a single character at a time. Every time a `(` is found a counter is incremented. Similarly, every time a ')' is found a counter is decremented. If the counter ever drops below `0`, we know a `)` was found without a prior `(`. When we reach EOF, if the counter equals `0`, we have success!

EDIT: A big thanks to @ugoren!

# Answer
> 2 votes
## GolfScript 37

```
{[40.)]&},.,,\`{\>}+%{0\~}%(!\{0<},!&

```

Suppose the input to the program is `'(123(abc)(hello))'`. First, filter out all characters that are not `(` (ASCII 40) or `)` (ASCII 41):

```
{[40.)]&},  #Stack is now '(()())'

```

Next, generate an array from `0` to the length of the array:

```
.,, #Stack is now '(()())' [0, 1, 2, 3, 4, 5]

```

Now, generate all suffixes of the filtered string

```
\`{\>}+% #Stack is now ['(()())', '()())', ')())', '())', '))', ')' ]

```

Recall that in GolfScript, `(` decrements integers and `)` increments them.

So, checking if the parentheses are valid is equivalent to checking if that no suffix, when treated as a code block and applied to 0, dips below 0 (so that there are more close braces than open braces) and that the whole string, when treated as a code block and applied to 0, return 0 (so that there is an equal number of open and close parenthesis).

So, apply each suffix to `0`:

```
{0\~}% #Stack is now [0, 1, 2, 1, 2, 1]

```

And then check that the first element (where the entire string treated as a function) returns 0, and that no elements are below 0 (recall that the empty array `[]` is falsey in GolfScript):

```
 (!\{0<},!&

```

# Answer
> 2 votes
## Common Lisp (???)

The idea here was to highlight the flexibiliity of the Lisp reader and actually allow other characters as list delimiters. Unfortunately, it seems like too much of the other parts of the language syntax (e.g., using `'foo` as an abbreviation for `(quote foo)` and different comment syntaxes (`;` rather than `//` for end-of-line comments, and `#| … |#` instead of `/* … */`)) probably disqualify this from being a "working" entry.

```
(defun check-source (x)
  (labels ((s (x y)
             (set-macro-character x y))
           (r (e)
             (s e (get-macro-character #\) nil))
             (lambda (s c)
               (read-delimited-list e s t)))
           (p (b e)
             (s b (r e))))
    (map 'nil #'p "[{<" "]}>")
    (listp (read-from-string (concatenate 'string "(" x ")")))))

```

```
(defun check-source(x)(labels((s(x y)(set-macro-character x y))(r(e)(s e(get-macro-character #)()))(lambda(s c)(read-delimited-list e s t)))(p(b e)(s b(r e))))(map'nil #'p"[{<""]}>")(listp(read-from-string(concatenate'string"("x")")))))

```

This uses the standard Lisp reader (which already handles `(` and `)`, of course), and defines each new set of a delimiters as another list construction syntax. These are automatically matched (i.e., mismatches result in an error). This doesn't handle `/* ... */` and `//` comments, but it handles `#| ... |#` and `//` comments. Double quoted strings are handled, including escapes.

# Answer
> 1 votes
## Javascript: ~~392~~ ~~383~~ ~~387~~ 345 characters - 210 bonus = 135 points

```
function x(a){z=1;k="",a=a.replace(/\/\*.*?\*\/|\/\/.*?\n|".*?"|'.*?'/mg,"").split('');try{for(d in a){eval("c=a[d]//%(')k='(%[')k='[%{')k='{%<')k='<%)_(#%]_[#%}_{#%>_<#".replace(/#/g,"')k=k.substr(1);else z=0//").replace(/%/g,"'+k\nif(c=='").replace(/_/g,"')if(k.charAt(0)=='"))}}catch(e){z=0}return''==k&z==1&a.indexOf("'")<0&a.indexOf('"')<0}

```

It is a function that returns 0 if the input is not valid and 1 if it is.

First, it uses regular expressions to remove the `/* ... */`, `// ... \n`, `' ... '` and `" ... "` sequences.

Second, it decompresses and run a code that iterates the input string, char-by-char, looking for `(`, `[`, `{` and `<`, stacking them into a string `k`. When he founds `)`, `]`, `}` and `>`, it looks the top of the stack and if they match, he pops the stack, otherwise he sets a variable `z` to zero. If any exception happens, `z` is set to zero.

In the end, he checks if the stack is empty and no `'` or `"` are left, returning 1 if this is the case and 0 otherwise.

Thanks to @Charles for pointing out bugs in earlier versions.

# Answer
> 1 votes
## flex, (70+4)-50=24

```
%{
a;
%}
%%
"(" a++;
")" a?a--:exit(0);
"//".*
.
<<EOF>> exit(!a);
%%

```

In order for compilation to succeed, you need to use flag `-lfl` so I added 4 to my character count.

```
flex flex.l
gcc lex.yy.c -lfl

```

The code reads character by character, incrementing a counter if a `(` is detected and decrementing a counter if a `)` is detected. If the counter is zero when a `)` is detected, then we know we don't have a matching `(` and can exit. Simple `//` comments are matched (and ignored) via a regular expression for the minus fifty bonus.

# Answer
> 1 votes
# Bash: 369 bytes - 110 bonus = 259

```
e=exit;function f(){ s=$1;a=X;until [ "$a" = "" ];do a=${s::1};s=${s:1}
if [ "$a" = \( ];then f "$s" \)||$e 1
elif [ "$a" = [ ];then f "$s" ]||$e 1
elif [ "$a" = \< ];then f "$s" \>||$e 1
elif [ "$a" = { ];then f "$s" }||$e 1
elif [ "$a" = \) ]||[ "$a" = ] ]||[ "$a" = \> ]||[ "$a" = } ]
then [ $a = "$2" ]&&return||$e 1;fi;done;[ "$2" = "" ]||$e 1;};f "$1"&&$e 0||$e 1

```

Scoring:

* Handles all four brace types, **4x -20 = -80**
* handles mismatched brackets, **-30**

There's probably room to further golf the chain of elifs into && and ||'s, but some odd behaviour started creeping in when I tried so I gave up :)

# Answer
> 1 votes
# JavaScript (ES6), ~~92~~ 115 Bytes

Oh look, I beat the other JavaScript answer without any bonuses.

```
c=s=>{d=0;s=s.split("");for(z=0;z<s.length;z++){if(s[z]=="{")d++;if(s[z]=="}")--d;if(d<0)a="N"}return a||d?"N":"Y"}

```

Ungolfed, dev-friendly, and ES5-(-friendly) version:

```
function check(str){
    depth = 0;
    str = str.split("");
    for(var z=0;z<str.length;z++){
        if(str[z]=="{") str[z]+=depth++;
        if(str[z]=="}") str[z]+=--depth;
        if(depth<0) return "unmatched";
    }
    return depth;
}

```

Returns a version of the string with the "depth" of the bracket afterword. I am using this function for evaluation purposes. I might try for some bonuses later.

# Answer
> 0 votes
# Bash - 4 chars

```
cc f

```

Assuming `f` is your c source code file

If you want it to print 'yes' or 'no', 43 chars:

```
cc f;if $?=0;then echo yes;else echo no;fi

```

# Answer
> 0 votes
# Python 2.7: 171 bytes - 60 - 30 = 81 points

```
import sys
b=[]
for c in sys.stdin.read():
 if c in '([{<':b+=[c]
 if c in ')]}>':
    if b[-1]!='([{<'[list(')]}>').index(c)]:print 0==1;break
    b.pop()
else:print len(b)==0

```

Handles all bracket types and doesn't allow mismatched brackets.

# Answer
> 0 votes
## VB.net 93c

This check to see if BrainF\*ck code has balanced square braces.

```
Function(c$)c.Aggregate(Of Int32)(0,Function(s,i)If(s<0,s,If(i="["c,s+1,If(i="]"c,s-1,s))))=0

```

# Answer
> 0 votes
# Python, 7 bytes

```
eval(i)

```

Where `i` is the input. It handles `{`, `[` and `(`, ignores braces in quotes, and, does to allow mismatched braces.

On an error, a Syntax error is generated!

Example:

```
>> eval('([{"("}])')

>> eval('([{(}])')
            ^
SyntaxError: invalid syntax

```

Edit: This is just a fun partial solution. It does not handle cases such as `[` inside `{`, and `{}[]` etc.

# Answer
> 0 votes
**C# - 380 characters**

Continuously reads the user's input until they quit, each time giving back true or false as to whether their input is valid.

```
using C = System.Console;

namespace P
{
    class P
    {
        static void Main(string[] a) { while(true) C.WriteLine(F(C.ReadLine())); }
        static bool F(string x)
        {
            int l = 0, r = 0;
            foreach (var c in x) { if (c == '[') l++; if (c == ']') { r++; if ( r > l ) return false; }
            return l == r;
        }
    }
}

```

**Condensed form - 239 characters**

```
using C = System.Console;
namespace P{class P{static void Main(string[] a){while(true)C.WriteLine(F(C.ReadLine()));}static bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}}return l==r;}}}

```

And lastly
**the function itself - 112 characters (condensed form)**

```
bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}return l==r;}

```

# Answer
> 0 votes
## Perl, 106 bytes − (3\*20 + 30 + 50 + 0 + 0) bonus = −34 points

```
$_=join"",<>;$a='[^()<>{}[\]]*';while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}exit!/[()<>{}[\]]/

```

Input is expected from STDIN (multiple lines) and the return is given as exit code, 1 for successful validation and 0 for unmatched braces. Example for calling:

```
perl bracevalidator.pl<inputfile;echo $?

```

The following is supported/validated:

* Balanced braces: `(`..`)`, `<`..`>`, `{`..`}`, `[`..`]`.
* No mismatch for different brace types.
* C++ style comments `//`.

The idea is to match the innermost balanced braces first and removes them from the string until all brace pairs are gone. If a brace is left, then the return value is 0, otherwise all braces are properly nested and 1 is returned.

First the whole file is read in variable `$_`:

```
$_join'',<>;

```

Variable `$a` serves as abbreviation for the brace free stuff between an innermost brace pair:

```
$a='[^()<>{}[\]]*';

```

The main loop removes the C++ comments and the brace pairs bottom-up:

```
while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}

```

Then the remaining string is checked for any remaining brace:

```
exit!/[()<>{}[\]]/

```

# Answer
> 0 votes
# EcmaScript 6:

```
!(_=x[z='replace'](/("|').*?\1|\/\*.*?\*\/|[^({<[\]>})]/g,''),_.length-_[z](/[^({<[]/g,'').length)

```

# Answer
> 0 votes
# TI-BASIC, 39 bytes

```
cumSum(iPart(2sin(2seq(inString("()",sub(Ans,X,1)),X,1,length(Ans
not(min(Ans or Ans(dim(Ans

```

`cumSum(` keeps a running total of the number of braces, then the second line checks if both the minimum and the last element are zero.

Two tricks used:

* `iPart(2sin(2*` maps `{0,1,2}` to `{0,1,-1}` so I don't need to match `{` and `}` separately.
* I `or` the last element with the whole list, rather than `min(Ans)`, to save a close-paren.

---
Tags: code-golf, balanced-string
---


title: Quiche Lorraine

text:
# Question
Title: Quiche Lorraine
Since it was Pi day recently, I have noticed a number of challenges that ask you to calculate pi.

Of course, a quiche lorraine is *not quite* a pie (you can claim a Bonus Score¹ of +1 if you guessed the challenge off of the title). As such, your job is to **write an algorithm** or **method** that *looks* like it approximates Pi at first glance, but is **guaranteed not to converge** towards Pi.

This is an underhanded challenge, so make sure it will output 3.14... for a simple test case, e.g. with 10 iterations of your algorithm. This is also a popularity challenge, so don't go for the obvious `echo(pi)` and say that IEEE 754 floating point rounds some digits up or down.

Winner gets a quiche lorraine².

*¹ Warning: not actually a bonus score. By claiming the score, you agree to bake me a pie before Pi Day, 2016*

² *Warning: quiche lorraine is used as a metaphor for having your answer marked as 'accepted'*

# Answer
> 77 votes
## Algorithm

Using the well-known result:

we define in Python 3:

```
from math import sin
from functools import reduce
from operator import mul

def integrate(f, a, b, n):
   h = (b-a)/n
   i = h * sum(f(a+i*h+h/2) for i in range(n))
   return i

def sinc(x):
   return sin(x)/x

def borwein(n):
   def f(x):
     g = lambda i: sinc(x/(2*i+1))
     return reduce(mul, map(g, range(n)), 1)
   return f

```

## Testing

```
>>> for i in range(1,10):
...   pi = 2 * integrate(borwein(i), 0, 1000, 1000)
...   print("x[{}] = {}".format(i, pi))
x[1] = 3.140418050361841
x[2] = 3.141593078648859
x[3] = 3.1415926534611547
x[4] = 3.1415926535957164
x[5] = 3.1415926535895786
x[6] = 3.1415926535897953
x[7] = 3.1415926535897936
x[8] = 3.1415926535435896 # ???
x[9] = 3.141592616140805  # ?!!

```

## Spoiler

> The Borwein integral is math's idea of a practical joke. While the identity above holds up to sinc(x/13), the next value is actually:

# Answer
> 59 votes
To find pi, we will integrate this well known differential equation:

With an initial condition

It is well known that this initial value problem converges to π as t increases without bound. So, all we need is to start with a reasonable guess for something between 0 and 2π, and we can perform numerical integration. 3 is close to π, so we will pick y = 3 to start.

```
class PiEstimator {

    static final int numSteps = 100;
    static final double dt = 0.1, tMax = numSteps * dt;

    static double f(double y, double t){ return Math.sin(y) * Math.exp(t); }

    public static void main(String[] args){
        double y = 3;
        int n = 0;

        for(double t = 0; t < tMax; t+=dt){
            if(n%5 == 0) System.out.println(n + ": " + y);
            n++;
            y += f(y,t)*dt;
        }
    }
}

```

Here are some results at each for different numbers of steps:

```
0: 3.0
5: 3.0682513992369205
10: 3.11812938865782
15: 3.1385875952782825
20: 3.141543061526081
25: 3.141592653650948
30: 3.1415926535886047
35: 3.1415926535970526
40: 3.1415926517316737  // getting pretty close!
45: 3.1416034165087647  // uh oh
50: 2.0754887983317625
55: 49.866227663669584
60: 64.66835482328707
65: 57.249212987256286
70: 9.980977494635624
75: 35.43035516640032
80: 51.984982646834
85: 503.8854575676292
90: 1901.3240821223753
95: 334.1514462091029
100: -1872.5333656701248

```

How it works:

> That differential equation is well known because it is extremely difficult to integrate correctly. While for small t values naive integration will produce acceptable results, most integration methods exhibit extreme instability as t gets very large.

# Answer
> 6 votes
Code:

```
var pi = function(m) {
  var s2 = 1, s1 = 1, s = 1;
  for (var i = 0; s >= 0; ++i) {
    s = s1 * 2 - s2 * (1 + m*m);
    s2 = s1;
    s1 = s;
  }
  return i*m*2;
};

```

I basically discovered this sequence by accident. It starts out as `1, 1` and every term after that `s(n)` is given by `s(n) = 2*s(n - 1) - s(n - 2) * (1 + m*m)`. The end result is the smallest `n` such that `s(n) < 0` multiplied by `2m`. As `m` gets smaller, it should get more and more accurate.

```
pi(1/100) --> 3.14
pi(1/1000) --> 3.14
pi(1/10000) --> 3.1414
pi(1/100000) --> 3.14158
pi(1/1000000) --> 3.141452 // what?
pi(1/10000000) --> 3.1426524 // .. further away from pi

```

I'm pretty sure these are floating point errors as `(1 + m*m)` gets close to one, but I'm not sure. Like I said, I stumbled on this by accident. I'm not sure of its official name. Don't try this with an `m` too small or it will run forever (if `1 + m*m == 1` due to `m` being so small).

If anyone knows the name of this sequence or why it behaves like this, I would appreciate it.

---
Tags: popularity-contest, math, underhanded, pi
---


title: The Great British Cake Off

text:
# Question
Title: The Great British Cake Off
I hear *somebody* was very selfish on their birthday, demanding cake from everyone and there were no plans to share! 🎂

It's bound to be somebody's birthday today, so why not bake them a cake. Use your favourite programming language to make a delicious cake, with a nice "Happy Birthday" message as the output. (Might I suggest Chef!)

Your cake should

* Mimic a real world recipe (if you can link to it, brilliant!)
    + a list of newline separated ingredients suitable for making a cake
    + a newline separated list of steps for the method
    + how many people it serves
* Stay as close to correct ingredient ratios as possible.
* Output minimally "Happy Birthday" when served.

The best cakes will be:

* **Delicious** \- since this is a , the community will decide what is delicious
* **Personalised** \- try baking a custom happy birthday message to somebody specific. (If you can't find a PPGC user, why not a celebrity?)
* **Balanced** \- Try to use a suitable number of ingredients for the amount of servings the recipe prepares. `1000 eggs, serves 1` for one serving is probably just a *teensy bit* big, **huge**,

# absolutely colossal!
* **Outlandish** \- You can bake more than just a basic sponge, for example, include some icing, a drizzle, serve with sauce, decorations, etc.
* **Visually appealing** \- images are good either in the source code as ascii or in the output. The first "byte" is with the eyes after all.

And don't forget, good bakers **don't cut corners** and do things properly. (*Don't just use no-op code to make it look like a recipe then print, make sure your code means something*) I encourage voters to view these recipes negatively.

## Happy Baking!

# Answer
# ECMAScript 2015, serves 10

```
Don  =([_])=> alert(_.replace(/^.*(?=, )/,'Happy Birthday'))

ReadMoreAbout  =classic=  victoria  =sandwich=  on  =bbcgoodfood=      ~`

⚠  Remember that OCR technologies aren't perfect, and that scanning old,
⚠  smudgy recipes does not always go as smoothly as we'd expect or hope.
⚠  This recipe is not wonderful, but please, thoroughly enjoy making it.

`

try/* to do this properly! */{
  // Link to recipe:
  bbcgoodfood.com/recipes/1997/classic-victoria-sandwich
  'Makes 10 slices'

  Ingredients:
    ForThecake:
      - 200 | grammes | castorSugar
      - 200 | grammes | softenedButter
      -   4 | whole   | eggs
      - 200 | grammes | self-raising_flour
      -   1 | tsp     | bakingPowder
      -   2 | tbsp    | milk

    For_theFilling:
      -  100 | grammes | butter, softened
      -  140 | grammes | icing.sugar, sifted
      -    a | drop    | vanilla- extract (optional)
      -  240 | grammes | jar.good-quality_strawberryJam
      -                  icingSugar, to.decorate

  Method:
    1. ^`Heat oven to 190C/fan 170C/gas 5. Butter two 20cm sandwich tins
         and line with non-stick baking paper. In a large bowl,
         beat all the cake ingredients together until you have a smooth, soft batter.`
    2. ^`Divide the mixture between the tins, smooth the surface with a spatula
         or the back of a spoon, then bake for about 20 mins until golden
         and the cake springs back when pressed. Turn onto a cooling rack
         and leave to cool completely.`
    3. ^`To make the filling, beat the butter until smooth and creamy,
         then gradually beat in icing sugar. Beat in vanilla extract if you’re
         using it. Spread the butter cream over the bottom of one of the sponges,
         top it with jam and sandwich the second sponge on top.
         Dust with a little icing sugar before serving.
         Keep in an airtight container and eat within 2 days.`

  * HappyBirthdayǃ
} catch (cake) {
  Don`t drop that! It's your cake, Uncle Chris! This cake is one day late – sorry about that.
`}

```

**Valid ES6 code; no corners cut!**

It works in Firefox Developer Edition.

> It is all valid code; the `try` only serves to catch the `ReferenceError` caused by the variables not being defined.
> 22 votes

# Answer
## BF

Inspired by mbomb007s answer, I've made them a cake.

I'm afraid I lost the recipe (it's around here somewhere, but I'd probably have to break my own rules on cutting corners to post it); here is the finished product.

                                    +
                                    [
                       (
               )                    )             (
                       )           (o)    )
               (      (o)    )     ,|,            )
              (o)     ,|,          |~\    (      (o)
              ,|,     |~\    (     \ |   (o)     ,|,
              \~|     \ |----(o)->++|+\<]>,|,     |+.
              |`\-----|`\@@@-|-@@@@\.-@@@\~|[++>-\ |-
             -\-|-o@@@\ |@@@<]>@@@@|.\@@@|.\@@@o+|+\++
            ++|+\@@@@@|+\@@@|+\@@@@\.|@@@\-[@@@@@\-|o--
           ->@\+|@@@@@\<|@@@]>|@@@@@@@@@@|+\@@@@@|+\@@o.
          [->+|+\+@@@@@@@@@@|<]@@@@@@@@@@\>|@@@@@\+|+@@@.
          +@@@@@@@@@@@@@@@@@\+|@@@@@@@@@@|+\@@@@@@@@++++.
          @@++@@@@@@@@@@@@@@|+\@@@@@@@@@@@@@@@@@@@@+++++
          +.@@@++@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@o@@.-@
          --@@--@@-@@@@@@@@@@@@@@@@@@@@@@@@@@@@-@@-@@--@
          --@@.-@@@@---.@@@@--@@@@@-.+[@@@@@o---@@@>+<:]
          >::::::+::::::++@@.::@@@:::::@@@@:::::@@:::::%
          %%::::::::::::@@::::::@:::::::@@::::::::::::%%
          ::%%%::::::::::@::::::::::::::@::::::::::%%%::
       º# ::%::%%%%%%:::::::::::::::::::::::::%%%%%::%::##º
     º### ::::::%%:::%:%%%%%%%%%%%%%%%%%%%%%:%:::%%::::: ###º
   º##### ::::::%:::::%%::::::%%%%:::::%%::::%:::::::::: #####º
  º###### `:::::::::::%:::::::%:::::::::%::::%:::::::::' ######º
 º########  ``::::::::::::::::::::::::::::::::::::''  #########º
  º##########   ```::::::::::::::::::::::::::'''   ###########º'
    `º#########-[---->+<]>++.[-->+++<]>..+++++++. ###########º'
      ` º#################################################º '
          ` º#######################################º '
             ` º#################################º '
                   ` º######################º '
</code></pre>

Outputs:

```
happy birthday 007

```

So conveniently it works for James Bond, but not until 11th November.
> 22 votes

# Answer
# Python 2, serves 0

First of all, sorry, this isn't a REAL world cake.

However, it is in one of the best games of all time, Portal.

This recipe is based on what the Intelligence Core says are the ingredients.

```
""" Happy Birthday, Chell!
* * * * * * * * * * * """
# Here are all the ingrediants for portal cake
candles = 1 # There is most certainly only one candle for her.
fish_shaped_dirt = 32 # There isn't an official amount of dirt to add, 32 seems like a nice number.

#Full of lies
lie = float('inf')

serves = None

# Show the tester the documentation on how to use this
print __doc__,

# Now, we are going to repeat these steps until chell stops lying.
while lie:
    # She did it again, so now we need to do the whole thing once more.
    print "\r",
    # Check how many candles her cake will have
    if candles:
        # We had better take them away from her. Maybe it will stop her lying so much
        candles = 0
    else:
        # Maybe if we give her a candle, she will listen
        candles = 1
    # See, her chances of lying go down when we give her candles!
    lie -= candles
    # Add the fish shaped dirt. But ONLY if we're giving her a candle.
    print chr(fish_shaped_dirt)*candles,
    # Add all the other rubbish
    print __doc__[25:],
    #Flush it into the relaxation vault
    import sys
    sys.stdout.flush()
    # Wait and ask her if she liked it.
    import time
    time.sleep(1)

```

# Output

```
 Happy Birthday, Chell!
 * * * * * * * * * * *

```

Followed by

```
 Happy Birthday, Chell!
  * * * * * * * * * * *

```

Then repeats indefinitely
> 16 votes

# Answer
# Brainf\***

I like ice cream cake, which doesn't require baking. Also, it's my birthday, so don't tell me what kind of cake I can have.

```
Buy an ice cream cake:
    +   +   +    +   +   +
    |   |   |    |   |   |
[-]-[------->+<]>-.[--->++++<]
|><>+.-[++>-----<]>..+++++++++
|><.-[---->+<]>++.+[->++<]>.-[
|><--->+<]>--.+++++++++.++.---
|><---------.----.---.+[--->+<
|><]>+++.-[---->+<]>+++---+++|
then serve it.

```

I like to pretend that the `>+<]>`'s are fish-shaped crackers.
> 16 votes

# Answer
# Pip, serves 2

For those of us whose birthday tastes are a little more global...

```
Our dessert tonight: " Birthday " Dosa!
(adapted from vegrecipesofindia.com/masala-dosa-recipe-how-to-make-masala-dosa-recipe)

1 cup rice: ("mmm, rice")
1 cup ukda chawal: [don't know what that is but it sounds good]
1/2 cup urad dal: ["dal" means lentils in Hindi]
1/4 cup poha: ["poha" is another kind of rice]
1/4 tsp methi seeds: ("!")
salt to taste: ["Happy" time]
water as needed: [you'll need some water]

Are you ready to cook? Yes? OK then:

1. rinse the rice and urad dal separately first.:
2. soak the ukda chawal, rice and poha.
3. in another bowl soak the urad dal-methi in enough water.
4. grind the urad dal with methi to a fine and fluffy batter.
5. grind the rice and poha to a smooth batter.
6. mix both the rice and urad dal batter with salt.
7. cover and let the batter ferment for 8-9 hours.

is it Ready? Y(es) or N(o)

Answer should be: y.
    take batter out and:

1. heat a flat cast-iron griddle and smear some oil on it.
3. spread the dosa batter in a circular way on the griddle; add some oil on top.
4. flip and cook the other side.
5. serve dosa hot with coconut chutney and sambar. (yum)

Recipe serves ___:
           `(?<=2) ?`
Actually, it serves exactly 2--half feR "ME" and half feR:_" YOU"!
Yeah! Happy birthday  !

```

### Output

```
Happy Birthday 2 YOU!

```

or, if you cook it:

Now I'm hungry.
> 8 votes

# Answer
# Chef, serves 16.

Based off of this. I couldn't find an interpreter online, so I closely followed the specs found here.

## "Golfed" version

```
"Happy" Birthday Cake.

This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.

Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space

Cooking time: 25 minutes.

Pre-heat oven to 162 degrees Celsius.

Method.
Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add corn starch to the mixing bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put space into mixing bowl. Put happiness into the mixing bowl. Remove water from the mixing bowl. Combine vanilla extract into the mixing bowl. Add happiness to the mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add butter to the mixing bowl. Add happiness to the mixing bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove water from mixing bowl. Add happiness to the bowl. Put space into the mixing bowl. Combine water into the mixing bowl. Remove water from mixing bowl. Remove semisweet chocolate from mixing bowl. Add happiness to the bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the bowl. Put 2% milk into the mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Add sugar to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Put eggs in mixing bowl. Add happiness to the mixing bowl. Add happiness to the mixing bowl. Put happiness into the mixing bowl. Put happiness into the mixing bowl. Remove sugar from the bowl. Remove baking soda from the bowl. Put space into mixing bowl. Put vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine vanilla extract into the mixing bowl. Combine salt into mixing bowl. Add happiness to the mixing bowl. Add salt to the mixing bowl. Put eggs into the mixing bowl. Add happiness to the mixing bowl. Add butter to the mixing bowl. Add water to the mixing bowl. Put space into the mixing bowl. Add baking soda to the mixing bowl. Liquefy contents of the mixing bowl. Serves 16.

```

Output: `Happy Birthday, me!`.

Here is the explanation for each step:

```
"Happy" Birthday Cake.

This recipe was recovered from an *erm* ANCIENT cave, in which the culture consumed enormous amounts of eggs and water, and did so through their caves. Modern ingredients have been added in an endevour to make the cake better.

Ingredients.
48 teaspoons 2% milk
1 cup butter
1 l semisweet chocolate
73 eggs
2 teaspoons vanilla extract
1 cup sugar
1 teaspoon baking soda
5 teaspoons salt
24 g happiness
3 teaspoons water
8 ml corn starch
32 g space

Cooking time: 25 minutes.

Pre-heat oven to 162 degrees Celsius.

Method.

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72 (H)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24= 97 (a)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add corn starch to the mixing bowl.             +8 =112 (p)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add corn starch to the mixing bowl.             +8 =112 (p)

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72
Add happiness to the mixing bowl.                +24= 96
Add happiness to the mixing bowl.                +24=120
Add sugar to the mixing bowl.                   +1 =121 (y)

Put space into mixing bowl.                     32      ( )

Put happiness into the mixing bowl.              24
Remove water from the mixing bowl.              -3 = 21
Combine vanilla extract into the mixing bowl.   *2 = 42
Add happiness to the mixing bowl.                +24= 66 (B)
Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add butter to the mixing bowl.                  +1 = 81
Add happiness to the mixing bowl.                +24= 95 (i)

Put space into the mixing bowl.                 32
Combine water into the mixing bowl.             *3 = 96
Remove water from mixing bowl.                  -3 = 93
Remove water from mixing bowl.                  -3 = 90
Add happiness to the bowl.                      +24=114 (r)

Put space into the mixing bowl.                 32
Combine water into the mixing bowl.             *3 = 96
Remove water from mixing bowl.                  -3 = 93
Remove semisweet chocolate from mixing bowl.    -1 = 92
Add happiness to the bowl.                      +24=116 (t)

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the bowl.                       +24=104 (h)

Put 2% milk into the mixing bowl.               48
Add happiness to the mixing bowl.                +24= 72
Add happiness to the mixing bowl.                +24= 96
Add sugar to the mixing bowl.                   +1 = 97 (d)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24= 97 (a)

Put eggs in mixing bowl.                        73
Add happiness to the mixing bowl.                +24 = 97
Add happiness to the mixing bowl.                +24 =121(y)

Put happiness into the mixing bowl.              24
Put happiness into the mixing bowl.              +24= 48
Remove sugar from the bowl.                     -3 = 45
Remove baking soda from the bowl.               -1 = 44 (,)

Put space into mixing bowl.                     32      ( )

Put vanilla extract into the mixing bowl.       2
Combine vanilla extract into the mixing bowl.   *2 = 4
Combine vanilla extract into the mixing bowl.   *2 = 16
Combine salt into mixing bowl.                  *5 = 80
Add happiness to the mixing bowl.                +24=104
Add salt to the mixing bowl.                    +5 =109 (m)

Put eggs into the mixing bowl.                  73
Add happiness to the mixing bowl.                +24=97
Add butter to the mixing bowl.                  +1 =98
Add water to the mixing bowl.                   +3 =101 (e)

Put space into the mixing bowl.                 32
Add baking soda to the mixing bowl.             +1 = 33 (!)

Liquefy contents of the mixing bowl.            Converts the mixing bowl to characters

Serves 16.                                      Outputs the contents of the first
                                                16 bowls.

```
> 2 votes

---
Tags: popularity-contest
---


title: Pseudorandom Cellular Automaton

text:
# Question
Title: Pseudorandom Cellular Automaton
## Introduction

In this challenge, we will simulate a certain probabilistic cellular automaton using very bad pseudorandom numbers. The cellular automaton is defined on binary strings by the following local rule. Suppose that the left neighbor of a cell and the cell itself have states `a` and `b`.

* If `min(a,b) == 0`, then the new state of `b` is `max(a,b)`.
* If `min(a,b) == 1`, then the new state of `b` is chosen randomly from `{0,1}`.

The following picture shows one possible 10-step evolution of a single `1`.

```
1
11
101
1111
11001
101011
1111111
10001001
110011011
1010111101

```

Note how two adjacent `1`s sometimes evolve to `1`, and sometimes to `0`, and the border-most bits are always `1`s. Your task is to produce a cellular automaton evolution of this form.

## Inputs

Your inputs are a positive integer `n`, denoting the number of rows to display, and a non-empty list of bits `L`, which we use as a source of randomness.

## Output

Your output is a list of lists or 2D array of bits, depicting the evolution of a single `1` for `n` time steps, as in the above figure. You can pad the output with `0`s to get rows of equal lengths, if desired, but there must not be leading `0`s.

The random choices in the cellular automaton must be drawn from the list `L`, jumping back to the beginning when it is exhausted. More explicitly, if the output is traversed one row at a time form top to bottom, left to right, then the successive random choices shall form the list `L` repeated as many times as necessary.

## Example

Suppose the inputs are `n = 7` and `L = [0,1,0]`. Then the cellular automaton evolves as follows during the 7 steps, where we have put a `v` right above every random choice:

```
[1]

[1,1]
   v
[1,0,1]

[1,1,1,1]
   v v v
[1,1,0,0,1]
   v
[1,1,1,0,1,1]
   v v   v
[1,0,0,1,1,1,1]

```

If we read all the bits marked with a `v`, we get `01001001`, which is `L` repeated 2.66 times. The next random bit would be `0`.

## Rules and Scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. The exact format of the inputs and outputs is unimportant (within reason).

## Test Cases

Deterministic version, every random bit is `0`:

```
Inputs: 10 [0]
Output:
1
11
101
1111
10001
110011
1010101
11111111
100000001
1100000011

```

Every random bit is `1`:

```
Inputs: 6 [1,1]
Output:
1
11
111
1111
11111
111111

```

Pseudorandom versions:

```
Inputs: 10 [0,0,1]
Output:
1
11
101
1111
10101
111111
1010011
11110101
101011111
1111101001

Inputs: 10 [1,0,0,1]
Output:
1
11
111
1001
11011
111111
1001101
11010111
111111101
1011001111

Inputs: 15 [1,1,1,0,0,0]
Output:
1
11
111
1111
10001
110011
1110111
11011001
111111011
1100011111
11100100011
111101100101
1001111101111
11011000111111
101101001011101

```

# Answer
# Pyth, 33 bytes

```
jjLk.u++1m?hSde=.<Q1sd.:N2 1tvz]1

```

Try it online: Demonstration or Test Suite

### Explanation:

```
jjLk.u++1m?hSde=.<Q1sd.:N2 1tvz]1  implicit: Q = input list
    .u                      tvz]1  reduce N=[1] input-1 times by applying
                      .:N2           all substrings of length 2
         m                           map each d of ^ to:
          ?hSd                         if min(d) = 0 then:
               =.<Q1                     rotate Q by one
              e                          and use the last element
                    sd                 else use sum(d) (=max(d))
      ++1                  1         add a 1 at the front and the back
                                   .u gives all intermediate results
 jLk                               join these lists to strings
j                                  print each string on a line

```
> 3 votes

# Answer
# Retina, 139 bytes

```
^.
1

 00:0 01:1 10:1 11:
(m`^(..)((\S*)(?<=0) .*)
$1$3#$1!$2
+m`(?<=^(?<-2>.)*(..).*?#(.)*.)\d!(.)(.*\1:)(.)(\d*)
$5$3!$4$6$5
)`!0
0
 .+
<empty>

```

Where `<empty>` indicates that there is a trailing empty line. Each line goes in a separate file and the `#` should be replaced with linefeeds (0x0A).

Expects the input to be `n` in unary (made of zeroes, as in Unary), followed by a space, followed by the "pseudo-random" string, e.g. `10, [1, 0, 0, 1]` would be read as

```
0000000000 1001

```

Output is as in the challenge, but padded with zeroes, e.g.

```
1000000000
1100000000
1110000000
1001000000
1101100000
1111110000
1001101000
1101011100
1111111010
1011001111

```

This was way trickier than I expected...
> 7 votes

# Answer
# Python, ~~142~~ ~~135~~ ~~132~~ 131 bytes

### ~~133~~ ~~132~~ 131 byte version

```
f=input;n=f();L=f()*n*n;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if r[x-1]&r[x]else r[x-1]+r[x]for x in range(1,i)];r=[1]+r+[1];i+=1

```

replaced `r[x-1]+r[x]>1` by `r[x-1]&r[x]` were the bitwise operator & yields the minimum value in `(r[x-1],r[x])`

Thanks @ThomasKwa for suggesting `n*n` instead of `n**2` which saves 1 byte!

Thanks @Shebang for the -1 byte

### 135 byte version

```
f=input;n=f();L=f()*n**2;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if r[x-1]+r[x]>1 else r[x-1]+r[x]for x in range(1,i)];r=[1]+r+[1];i+=1

```

Thanks to @Cole for the -7 bytes:

`min(r[x-1],r[x])->r[x-1]+r[x]>1`

`max(r[x-1],r[x])->r[x-1]+r[x]`

### 142 byte version

```
f=input;n=f();L=f()*n**2;r=[1];i=1
while i<=n:print r;r=[L.pop(0)if min(r[x-1],r[x])else max(r[x-1],r[x])for x in range(1,i)];r=[1]+r+[1];i+=1

```

Not even close to @Jakube's answer but I had a lot of fun coding and golfing this one.

Expects two inputs: first input is the **number of rows** and second input is the **pseudorandomness source list**. It prints on console one row after another, each on a new line.

As an example:

```
10 # This is input
[0] # This is input
[1] <- First output row
[1, 1]
[1, 0, 1]
[1, 1, 1, 1]
[1, 0, 0, 0, 1]
[1, 1, 0, 0, 1, 1]
[1, 0, 1, 0, 1, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 0, 0, 0, 0, 0, 0, 1, 1]

```

### Now for a short explanation on how it works:

```
f=input;n=f();L=f()*n*n;r=[1];i=1 First we define the input() function as f
                                   for saving bytes as we have to call it twice.
                                   Then L is defined as a list made of the
                                   pseudorandom numbers in their order *many* times
                                   (were *many* is an upperbound of the canges that
                                   could be done); r as the first row and i as the row
                                   counter.

while i<=n:print r                 A while loop that exits when the nth row has been
                                   calculated and the printing of the actual row.

r=[L.pop(0)if r[x-1]&r[x] else r[x-1]+r[x] for x in range(1,i)];r=[1]+r+[1];i+=1
     ^           ^                 ^                         ^
     |           |                 |Same as max(r[x-1],r[x]) | from 2nd to last element
     |           | Same as min(r[x-1],r[x]) (0->False;1->True)
     | get random bit from pseudorandom list

```

The trick here is that we know that the bit list will always start and end with a `1` because the first and last elements are never modified due to the specs. of the question. That's the reason for the statement `[1]+r+[1]`.

But if `r` is initialized as `[1]`, there are no changes on the first row and then we add `[1]+r+[1]` how come the second row is not `[1,1,1]`?

This is due to the fact that on the first iteration `i=1` so `range(1,i)` returns an empty list and, as a result of the `for` in the list comprehension having nothing to iterate over `r` becomes an empty list so `[1]+r+[1]=[1,1]`. This just happens on the first iteration which is just ideal for us!

P.S: Feel free to make any suggestions on how to golf it more.
> 3 votes

# Answer
# MATLAB, 146 143 138

(Also works on Octave online, but you need to sign in to save the function in a file).

```
function o=c(n,L);o=zeros(n);o(:,1)=1;for i=2:n;for j=2:i;a=o(i-1,j-1);b=o(i-1,j);c=a|b;d=a&b;c(d)=L(d);L=circshift(L,-d);o(i,j)=c;end;end

```

The function takes an input `n` and `L`, and returns an array `o` which contains the output.

For the input values, `n` is a scalar, and `L` is a column vector, which can be specified in the format `[;;;]`. Not quite what you show, but you say it is flexible within reason and this seems so.

The output is formatted as an `n x n` array containing 0's and 1's.

And an explanation:

```
function o=c(n,L)
%Create the initial array - an n x n square with the first column made of 1's
o=zeros(n);o(:,1)=1;
%For each row (starting with the second, as the first is done already)
for i=2:n;
    %For each column in that row, again starting with the second as the first is done
    for j=2:i;
        %Extract the current and previous elements in the row above
        a=o(i-1,j-1); %(previous)
        b=o(i-1,j);   %(current)
        %Assume that min()==0, so set c to max();
        c=a|b;
        %Now check if min()==1
        d=a&b;
        %If so, set c to L(1)
        c(d)=L(d);
        %Rotate L around only if min()==1
        L=circshift(L,-d);
        %And store c back to the output matrix
        o(i,j)=c;
    end;
end

```

---

Update: I have managed to optimise away the if-else statement to save a few bytes. The input format has once again changed back to column vector.
> 2 votes

# Answer
# Haskell, ~~153~~ 149 bytes

```
j[_]o l=(l,o)
j(a:u@(b:c))o q@(l:m)|a*b==0=j u(o++[a+b])q|1<2=j u(o++[l])m
k(r,a)=fmap((1:).(++[1]))$j a[]r
n%l=map snd$take n$iterate k(cycle l,[1])

```

`%` returns a list of bit lists. Usage example:

```
> 10 % [1,0,0,1]
[[1],[1,1],[1,1,1],[1,0,0,1],[1,1,0,1,1],[1,1,1,1,1,1],[1,0,0,1,1,0,1],[1,1,0,1,0,1,1,1],[1,1,1,1,1,1,1,0,1],[1,0,1,1,0,0,1,1,1,1]]

```

Oh dear! Carrying the random list `L` around is pure pain. Let's see if this can be shorter.
> 1 votes

# Answer
# C#, 152 bytes

There's nothing special here. The function returns a 2D array where the first rank is the line and the second is the column.

Indented and new lines for clarity:

```
int[,]F(int n,int[]l){
    var o=new int[n,n];
    for(int y=0,x,i=0,m;y<n;y++)
        for(o[y,x=0]=1;x++<y;)
            o[y,x]=(m=o[y-1,x-1]+o[y-1,x])<2?m:l[i++%l.Length];
    return o;
}

```
> 1 votes

# Answer
# TI-BASIC, ~~106~~ ~~94~~ ~~87~~ ~~86~~ 87 bytes

```
Prompt N,B
"∟B(1+remainder(,dim(∟B→u
{1
For(I,1,N
Disp Ans
augment({0},Ans)+augment(Ans,{0
Ans and Ans≠2+seq(u(-(Ans(X)<2)+2dim(∟B)),X,1,dim(Ans
End

```

TI-BASIC doesn't have an increment operator, right? Well, it sort of does. The equation variable `u`, normally used with sequences, has an obscure feature: when `u` is called with an argument, the variable  is set to one greater than that argument. The conditional increment depends on this. (I've been waiting to use it for a long time.)

For list indexing to work properly,  must be its default value of 0, and `Min` should be its default 1, so either clear your calculator's RAM or set those values manually before running this.

`augment({0},Ans)+augment(Ans,{0` calculates a list of sums of two adjacent elements, so it will return a list of 0s, 1s, and 2s. Then the magic is on this line:

```
Ans and Ans≠2+seq(u(-(Ans(X)≠2)+dim(∟B)),X,1,dim(Ans

Ans and                 ;set 0s to 0
Ans≠                    ;set to 0 all sums that equal...
2+
  seq(...,X,1,dim(Ans   ;execute for each element of the list
      u(                ;return this element in list of bits (looping)
                       ;current location in the list
        -(Ans(X)≠2)+    ;subtract 1 if the element isn't 2
        2dim(∟B)        ;Add twice the dimension of the list
                           ;(because n<nMin on the first iteration, it's out of the domain
                           ;this prevents an error)
       )                      ;set n to one greater than that value
                              ;i.e. increment if element≠2
                        ;Will equal Ans(X) iff Ans(X)=2 and the bit read false

```

The result of this line will be that list elements are 0 if they were 0 or if they were 2 and the bit read was 0.

```
Result of above line
n \ u |  0  |  1
0        0     0

```

Test case:

```
N=?7
B=?{0,1,0
             {1}
           {1 1}
         {1 0 1}
       {1 1 1 1}
     {1 1 0 0 1}
   {1 1 1 0 1 1}
 {1 0 0 1 1 1 1}
            Done

```
> 1 votes

---
Tags: code-golf, cellular-automata
---


title: Escape control characters in a C string

text:
# Question
Title: Escape control characters in a C string
C/C++ use double quotes `""` for making string literals. If I want the double-quote itself, or certain other characters, to appear in the string, I have to escape them, like so:

```
char *s2 = "This is not \"good\".\nThis is awesome!\n";

```

Here, I used `\"` to represent a double-quote, and `\n` to represent the newline character. So, if my program prints the string, I see

```
This is not "good".
This is awesome!

```

However, if I examine the string in a debugger (Visual Studio or gdb), it shows me the escaped form - the one that would appear in the source code. This is good because it allows to unambiguously identify whether the string contained that `\` backslash character verbatim or as part of an escape-sequence.

The goal of this challenge is to do the same job the debuggers do, but better - the escaped string must contain as few escaping characters as possible! The input to your program (or subroutine) is a string of arbitrary 8-bit bytes, and the output must be suitable for putting into the following boilerplate C code:

```
#include <stdio.h>
int main() {char str[] =
"### the escaped string goes here ###";
puts(""); // put a breakpoint here to examine the string
puts(str); return 0;}

```

---

For example:

Input (hexdump, 3-byte string): `64 0a 06`

Output: `d\n\6`

Here, `\006` or `\x6` have the same meaning as `\6`, but longer and are therefore unacceptable. Likewise, `\012` and `\xa` have the same meaning as `\n`, but only `\n` is an acceptable encoding for the byte with the value 10.

---

Another example:

Input (hexdump, 5-byte string): `61 0e 38 02 37`

Output: `a\168\0027`

Here, code `0x0e` is escaped as `\16`, and parsed successfully by the C compiler because `8` is not a valid octal digit. However, the code `0x02` is escaped as `\002`, not `\2`, to avoid confusion with the byte `\27`.

Output: `a\168\2\67` \- another possible form

---

See Wikipedia for the exact definition of escaping in C.

Additional (reasonable) rules for this challenge:

* Output must be printable ASCII (no tab characters; no characters with codes above 126)
* The input can be in the form of a string or an array of 8-bit elements. If your language doesn't support it, use the closest alternative. In any case, there should be no UTF encoding for input.
* No trigraphs, so no need to escape the `?` character
* No need to handle the null character (code 0) in input - let it be an end-of-string marker, or a regular byte like others - whatever is more convenient
* Code golf: shortest code is the best
* You are not allowed to vandalize the Wikipedia article to bend the rules :)

---

P.S. Summary of the Wikipedia article:

```
Input byte | Output | Note
0x01       | \1     | octal escape
0x02       | \2     | octal escape
0x03       | \3     | octal escape
0x04       | \4     | octal escape
0x05       | \5     | octal escape
0x06       | \6     | octal escape
0x07       | \a     | alarm
0x08       | \b     | backspace
0x09       | \t     | tabulation
0x0a       | \n     | newline
0x0b       | \v     | vertical tabulation
0x0c       | \f     | form feed
0x0d       | \r     | return
0x0e       | \16    | octal escape
0x0f       | \17    | octal escape
...        |        | octal escape
0x1f       | \37    | octal escape
0x22       | \"     | escape with a backslash
0x5c       | \\     | escape with a backslash
0x7f       | \177   | octal escape
0x80       | \200   | octal escape
...        |        | octal escape
0xff       | \377   | octal escape
other      |        | no escape

```

# Answer
> 2 votes
# JavaScript (ES6) 152

First time ever that .reduceRight seems useful. (But probably the good old .map can do better). The point is, I need to see the next character before deciding whether to output a short or long octal escape.

```
f=s=>[...s].reduceRight((a,c)=>
((x=c.charCodeAt())==34|c==(q='\\')?q+c:x>31&x<127?c:q+('abtnvvr'[x-7]||(a>='0'&a<'8'?512+x:x).toString(8).slice(-3)))+a
)

```

---
Tags: code-golf, c, code-generation
---


# Question
Title: Hello human, I want to recover my little cat pics
NB : Everything presented in the situation is totally fake and had just been put here to make the challenge a little more fun ;) ... Or maybe not ;)

---

=== === BEGINNING TRANSMISSION === ===

Hello,
I recently had a disk failure. I hopefully had backups and I now want my photos back. However, EVERY backup looks corrupted in the parallel universe where I live. But that's not a problem, because we had special tools to help user find their files back. They work a little bit like yours, and looks around a disk for headers that look like images. As they are still in beta, the software recovers any image it finds, gives it a random name and outputs a list containing:

* The model of the camera that took the photo, or a single `-` if not available. Note that the model could contain spaces, but no `-`.
* A tab char (`\t`, ASCII 9)
* The name of the photo file.

The file is a standard text file and looks like that:

```
[...]
-   uyfeiebsvH.jpg
-   hv754ce758.gif
-   8321214736.jpg
-   FgnvsfHJBs.jpg
-   OMGILOVYOU.jpg
-   HElloDearH.png
-   umanHAYYSG.jpg
COOLCAM S1332   umanIAYYSG.jpg
iCell 7G    1234567890.jpg
[...]

```

The file is quite big, and I can't rely on my little Ubro to move all the file that have a model in a separate directory.

---

Dear Human, I need your help. I want you to move all photos that have data about the camera in a separate directory, so I could find my little cute cat pictures out of this mess of icons, screenshots...

However, these backups are taking place on My LiquidStateDrive46X, so I don't have a lot of space left (and I'm actually downloading the Internet, so, you know, it's difficult to download something else while doing that. I just can barely surf the web and you are the only one I've found, human!)

Don't let me live that way ! Please, write my a small program that will do the work for me, and save a little Ubro.

---

* As this is code-golf, the shortest program wins
* I need to be able to launch you program, HUMAN ! So make sure your program has an existing interpreter.
* You can expect the list file to be in the directory where I launch your script. It will be named ./list.txt
* You need to move images to ./withmodel/
* Every image recovered is in the same directory from where I launch your program
* No image have a - in his name. Same goes for camera models
* It need to be a real program, not a simple function.
* No internet access, I'm DOWNLOADING! This is really important.
* I need my cat images quickly, or I can't survive: This code-golf will end on the 10th of October, if I'm still alive on this day.

=== === END OF TRANSMISSION === ===

# Answer
### PowerShell (v4), 58 49 bytes

```
(gc list.txt)-replace"^[^-]*`t"|mv -des withmodel

# Previous 58 byte version
(gc list.txt)-notmatch'^-'-replace".+`t"|mv -des withmodel

```
* get-content of the list
* remove camera models up to the tab by replacing them with nothing. This won't change the lines starting with "-".
* pipe into the move command, destination folder 'withmodel'. This will hit a lot of errors for the unchanged lines starting with "-", but since none of the files has a "-" in the name, that won't move any incorrect files, only the right files will be moved.
> 9 votes

---
Tags: code-golf, string, file-system
---


title: Create a 'calculator interpreter'

text:
# Question
Title: Create a 'calculator interpreter'
Your task is to create an interpreter for a calculator. It has to parse commands like `5 + 5` and return the answer.

It has to be able to add, subtract, multiply, and divide. The interpreter only needs to accept two numbers (ex. `9 * 5` and `3 + 3`)

The interpreter will take input from a console/whatever, not a file.

**`Eval` isn't allowed**

---

**Examples:**

Input: `5 * 5`

Output: `25`

---

Input: `8 / 2`

Output: `4`

---

# Bonus

If you're really bored you can add these to the interpreter, if you'd like:

**Simple mathematical functions** like `sqrt`.

**Make the interpreter be able to accept more than two numbers** (ex. `55 + 55`)

# Answer
> 2 votes
**Perl, ~~10~~ 8 chars**

I hope this is not cheating ;)

8 chars (7 chars code + 1 for -p): Thanks to Dennis

```
perl -pe '$_=eval'

```

10 chars:

```
say eval<>

```

Takes input from STDIN and needs `perl v5.10` and above.

# Answer
> 2 votes
# JavaScript ES6, ~~10~~ 4 bytes

Anonymous function.

```
eval

```

# Answer
> 2 votes
# Pyth, 1 byte

```
Q

```

For some reason, multiplication and division don't work in the online interpreter. The Python interpreter behaves as expected.

# Answer
> 2 votes
## \>\<\>, 14 Bytes

Thanks @Sp3000 for saving 2 bytes

Quick, but kinda cool solution. Probably not an ideal golf, but utilizes an interesting feature of \>\<\>.

```
<v ip02ii
n<,;

```

Receives input through the numerical interpretation of ascii characters (i.e. a is 97). It places the second character read (the operator) in the space after `<v`. Because dividing in \>\<\> uses `,`, not `/`, I make use of the fact that `/` reflects the pointer to accommodate for that case.

Alternate solution if that's invalid (+4 Bytes):

```
<v %cip02i%ci
n<,;

```

For this we just take mod 12 (`c` pushes 12) of the input since `0` is 48 and there are only 10 characters.

If `,` could be used in place of `/`, this would be a lot shorter (something like `ii60pi n;` or `ic%ia0pic% n;`)

Golf suggestions gladly welcome -- I'm rather tired right now.

# Answer
> 0 votes
# MATLAB, 4 bytes (or 0 bytes)

```
eval s

```

Pretty simple really. MATLAB will evaluate the string `s` you pass it, and voila. For example the following operators work: `* / + - ^ sqrt() min() max()`. Well pretty much anything that you can think of.

Heck you can even print `Hello World!` if you want - `eval 'disp(''Hello World!'')'`.

To be honest given that MATLAB is already a calculator, you can call it `0` if you omit eval and simply type in the string:

```
>> 8/2
ans =
     4

```

---
Tags: code-golf, interpreter
---


title: Avoid the steepest descent!

text:
# Question
Title: Avoid the steepest descent!
# Background

A few months ago, the adventure of your life was just about to start. Now, in this precise moment (yeah, now), after months of suffering and hard work, you and a group of friends are standing on the top of the world. Yes, you are right, you are on the summit of Sagarmāthā.

However, things aren't going as well as you would like to. A dense fog has surrounded you and an incredibly bad-looking storm is coming as fast as it can. You didn't fix any rope on the way up, and your footprints have been covered in snow. If you want to survive (at least for today), you need to get out of there as fast as you can, but you MUST first find a way to know which face of the mountain is the one you should descend.

Luckily, you brought with you your sat phone which you modified before the trip so you are able to program and execute programs in it.

# Challenge

You have been able to download to your phone the map of the mountain in an ASCII-old-fashioned-unreadable-on-the-top-of-the-world way. Your task is to decide which face of the mountain presents the easiest descent so you can increase your chances of surviving. In order to do so, you have the brilliant idea to code a program on your phone that will tell which is the easiest way down. (Disclaimer: These activities have been done by professionals. No programmer was hurt during this narration. Please, do not try this at home.)

Maps are only made of the characters `/` and `\` (plus spaces and newlines). In any map, the summit of the mountain is always represented by

```
 /\
 \/

```

and from each of the sides (`1,2,3` or `4`) of the summit you will always find a "possible" way down the mountain.

```
1 /\ 2
3 \/ 4

```

The routes are always presented in the next way:

```
                      \
  Steep-> /          /
           /        / <-Flat
            /      \
      Flat-> \    \
              /  \ <-Steep
               /\
               \/

```

where each new character is either one place to the left/right of its predecessor. The meaning of each character is:

* If the slash/backlash is parallel to its summit side -\> counts as a 'steep' part.
* If the slash/backslash is perpendicular to its summit side -\> counts as a 'flat' part.

\*For further reference see graphic above.

**Note**: The sides can have different lengths and the characters which constitute the summit also count as part of their side. In case of a draw, you can choose any of them.

Standard loopholes are disallowed.

# Input

A string representing the map of the mountain or a plain text file containing the same info.

Either

```
C:\....\file.txt

```

or

```
                  \
      /          /
       /        /
        /      \
         \    \
          /  \
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /

```

as a string are valid inputs.

# Output

As output, you should produce either a file in plain text or by stdout an **ASCII profile representation of the side with the smallest average steepness** using `_` for flat parts and `/` for steep parts **along with the average steepness** of the side `(number of "/")/(total chars)`.

Output example for map above:

```
       /
   ___/
  /
  AS:0.5

```

The format is not important as long as you have the profile and average steepness.

# Scoring

What? Do you want a better reward than saving your and your friend's lives and being the first programmer who has ever programmed on the top of the world? Okay... this is code golf, so shortest program in bytes wins.

# Test cases

Input:

```
                  \
      /          /
       /        /
        /      \
         \    \
          /  \
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /

```

Output:

```
       /
   ___/
  /
  AS=0.5

```

Input:

```
                  /
      \          /
       /        /
        \      /
         \    /
          /  /
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /
     /
    /

```

Output:

```
______/
AS=0.143 (1/7)

```

Input:

```
           /        \
            \      \
             /    /
              /  \
               /\
               \/
              \  /
             \    /
            \      /
           /        \

```

Output:

```
        /
       /
      /
    _/
    AS=0.8

```

# Answer
> 4 votes
# JavaScript (ES6), 303

Test running the snippet blow in an EcmaScript compliant browser - surely Firefox, probably Chrome. Using template strings, arrow functions.

```
// Golfed, no indentenation, all newlines are significant

f=s=>(s=`
${s}
`.split`
`,s.map((r,i)=>~(q=r.search(/\/\\/))&&(y=i,x=q),x=y=0),z=[],[0,2,0,2].map((d,i)=>{t=x+i%2,u=y+i/2|0,b=s[u][t];for(p=[''],n=l=0;(c=s[u][t])>' ';++l,t+=d-1,u+=(i&2)-1)c==b?p.push(p[n++].replace(/./g,' ',w='/')):w='_',p=p.map((r,i)=>(i<n?' ':w)+r);z=z[0]<(p[0]=n/l)?z:p}),z.join`
`)

// Less golfed

U=s=>(
  s=(`\n${s}\n`).split`\n`,
  x = y = 0,
  s.map((r,i)=>~(q=r.search(/\/\\/))&&(y=i,x=q)),
  z=[],
  [0,2,0,2].map((d,i) => {
    t = x+i%2,
    u = y+i/2|0,
    b = s[u][t];
    for(p=[''], n=l=0; (c=s[u][t])>' '; ++l, t += d-1, u +=(i&2)-1)
      c == b
        ? p.push(p[n++].replace(/./g,' ',w='/'))
        : w='_',
      p = p.map((r,i) => (i<n?' ':w)+r);
    z = z[0]<(p[0]=n/l)?z:p
  }),
  z.join`\n`
)

// TEST
// redirect console into the snippet body
console.log=x=>O.innerHTML+=x+'\n'

maps=[ // as javascript string literals, each baskslasch has to be repeated
`                  \\
      /          /
       /        /
        /      \\
         \\    \\
          /  \\
           /\\
           \\/
          \\  /
         \\    \\
        \\      \\
       \\        \\
      /          /`,
`                  /
      \\          /
       /        /
        \\      /
         \\    /
          /  /
           /\\
           \\/
          \\  /
         \\    \\
        \\      \\
       \\        \\
      /          /
     /
    / `,
`           /        \\
            \\      \\
             /    /
              /  \\
               /\\
               \\/
              \\  /
             \\    /
            \\      /
           /        \\`]

maps.forEach(m=>console.log(m + '\n'+ f(m) +'\n'))
```

```
<pre id=O></pre>
```

---
Tags: code-golf
---


title: Find our missing dead

text:
# Question
Title: Find our missing dead
## Challenge

**Peter has risen again to save us from the duplicate challenges!**

~~Peter Taylor is dead, and there's no doubt about it (well, apart from the huge amount of doubt we have... but just ignore that). In his memory,~~ you must write a program which determines whether a given user is alive or dead.

## Further Information

A user is dead if they haven't been seen for more than a day, any less than that then they are alive. Check the last seen section found here:

The input will be a user id (for example, mine is 30525, and Peter Taylor's is 194). Assume that all inputs are valid PPCG IDs.

If the user is alive, you should output:

```
[User name] is alive!

```

Where you replace \[User name\] for their username *not* their user id.

If the user is dead, you should output:

```
 Sadly, [User name] is dead.

```

T-SQL entrants using the SE Data Explorer are disallowed.

## Winning

The shortest program in bytes wins.

## Leaderboard

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

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 4 votes
# CJam, 115 bytes

```
"codegolf.xyz/u/"r+g_N/{"s=\"r"/_0='>&!*1>s_"da"#)\_el=!|}#)"Sadly, %s is dead.""%s is alive!"?\"\"User "/1='"/1<e%

```

The idea is the same as in my Bash answer, except that this answer doesn't use regular expressions, because CJam doesn't have regular expressions...

The online interpreter doesn't perform web requests, so this will only work from the command line.

# Answer
> 8 votes
# Bash, 151 bytes

```
r="curl -L codegolf.xyz/u/$1";u=`$r|grep -Pom1 '(?<="User )[^"]*'`
$r|grep -Pq '^[^>]*s="r.*(da|[A-Z])'&&echo "Sadly, $u is dead."||echo "$u is alive!"

```

As usual, output to STDERR is ignored.

### Example run

```
$ ./is-dead 30525 2>&-
Beta Decay is alive!
$ ./is-dead 44935 2>&-
Sadly, Alpha Decay is dead.

```

### Idea

This code greps for lines containing `s="r` that do not have `>` before its occurrence. For example:

```
Last seen <span title="2015-09-17 12:00:00Z" class="relativetime">just now</span>

```
* If the match is followed by the string `da`, it contains the word `yesterday` or `days` (as in `2 days ago`).
* If the match is followed by an uppercase letter, it contains the name of a month.
* In all other cases, the user is ~~undead~~ alive.

The user's name is extracted from a Twitter meta tag. Example:

```
<meta name="twitter:title" property="og:title" itemprop="title name" content="User Dennis">

```

# Answer
> 7 votes
### PowerShell (v4), 228 217 209, 157 bytes

```
$u=($x=curl "codegolf.xyz/u/$args").BaseResponse.ResponseURI.Segments[-1]
if($x-match'n <(.*?)((c|n|ur)s* ago|w)<'){"$u is alive!"}else{"Sadly, $u is dead."}

```

e.g.

```
PS C:\> test.ps1 30525
beta-decay is alive!

C:\> test.ps1 67
Sadly, keith-randall is dead.

#Previous 209 byte version:
$f={$u=((curl "api.stackexchange.com/2.2/users/$($args)?&site=codegolf"
)|ConvertFrom-Json).Items;$d=$u.display_name;if((get-date -U %s)-
$u.last_access_date-gt86400){"Sadly, $d is dead."}else{"$d is alive!"}}

```

(Sorry, Keith Randall, you were just the first account I found with \>1 day since last seen date).

I was happy with the solid, reliable 209 byte one calling the API, but screen-scraping is the way to go for golf.

* This now pulls the username from the redirected URI - but it is a name rather than a numeric ID, as required.
* And it matches the line `Last seen <span title="2015-10-03 13:15:38Z" class="relativetime">2 days ago</span>` with `n <... [nr]s ago<` trying to catch sec(s) ago, min(s) ago, hour(s) ago, and just now, and miss "days weeks, months" ago, or the long term dates+times. And trying to catch 'last seen' and not the other relativetimes. (Thanks Dennis).

NB. `curl` is a default alias for `Invoke-WebRequest`, it's not the standard curl program ported to Windows.

# Answer
> 7 votes
# Javascript ES6, 234 bytes

```
document.write(`<script src="//api.stackexchange.com/users/${prompt(a=d=>{n=(x=d.items[0]).display_name,alert((Date.now()/1e3)-x.last_access_date>86400?`Sadly, ${n} is dead.`:n+' is alive!')})}?site=codegolf&callback=a">\x3C/script>`)
```

Annotated version

```
// Inserts a script tag to perform a JSONP callback request on the stackexchange API
document.write(`
  <script src="//api.stackexchange.com/users/${
    prompt( // interpolate user input into url
      a = d =>{ // declare a in global scope
        n = (x = d.items[0]).display_name, // alias the user object and name
        alert(
          (Date.now() / 1e3) - x.last_access_date > 86400
          ? `Sadly, ${n} is dead.` // a day or less since last seen
          : n + ' is alive!' // more than a day since last seen
        )
      }
    )
  }?site=codegolf&callback=a">\x3C/script>` // escaping that prevents early termination of enclosing script tag
)

```

# Answer
> 5 votes
# AutoIt, ~~320~~ ~~316~~ 308 bytes

```
#include<String.au3>
#include<Date.au3>
$0=_StringBetween
$1=BinaryToString(InetRead('http://codegolf.xyz/u/'&ClipGet()))
$2=_DateDiff('D',StringReplace($0($1,'Last seen <span title="',' ')[0],'-','/'),@YEAR&'/'&@MON&'/'&@MDAY)
ConsoleWrite(($2?'Sadly, ':'')&$0($1,'r ','- P')[0]&'is '&($2?'dead.':'alive!'))

```

`_DateDiff` calcs the difference in days (`'D'`). It will be 0 if the difference is less than 1 day, so we can use it as a boolean value. The title tag of the "last seen" value contains a (almost) standard timestamp.

# Answer
> 5 votes
# R, ~~384~~ 350 bytes

This one's for you, Peter!

```
u=scan();D=as.POSIXlt;J=jsonlite::fromJSON(gsub("/\\*\\*/a|[()]|;$","",httr::content(httr::GET(paste0("http://api.stackexchange.com/2.2/users/",u,"?site=codegolf&callback=a")),,"text")))$items;l=D(J$last_access_date,z<-"UTC","1970-01-01");n=D(Sys.time(),z);U=J$display_name;if(as.Date(n)-as.Date(l)>1)cat("Sadly,",U,"is dead.")else cat(U,"is alive!")

```

Note that this requires the `httr` and `jsonlite` packages to be installed, though they don't have to be imported for this code to work since we're referencing namespaces explicitly.

Ungolfed:

```
# Read a user ID from STDIN
u <- scan()

# Create a request object using the SE API v2.2
request <- httr::GET(paste0("http://api.stackexchange.com/2.2/users/", u,
                            "?site=codegolf&callback=a"))

# Read the contents of the request into a ill-formed JSON string
body <- httr::content(request, type = "text")

# Parse out a valid string and get the associated fields
J <- jsonlite::fromJSON(gsub("/\\*\\*/a|[()]|;$", "", body))$items

# Get the last accessed date as a POSIX datetime object
l <- as.POSIXlt(J$last_access_date, "UTC", "1970-01-01")

# Get the current date
n <- as.POSIXlt(Sys.time(), "UTC")

# Extract the username
U <- J$display_name

# Determine whether the user has died
if (as.Date(n) - as.Date(l) > 1) {
    cat("Sadly," U, "is dead.")
} else {
    cat(U, "is alive!")
}

```

Saved 5 bytes on my previous approach and corrected an error in my current approach thanks to minxomat!

# Answer
> 2 votes
# Groovy, 355 bytes

```
import groovy.json.JsonSlurper;import java.util.zip.GZIPInputStream;def d = new JsonSlurper().parseText(new GZIPInputStream(new URL("http://api.stackexchange.com/2.2/users/${args[0]}?site=codegolf").newInputStream()).getText()).items[0];def n = d.display_name;println d.last_access_date*1000l<new Date().time-8.64E7?"Sadly, ${n} is dead.":"${n} is alive!"

```

Uncompressed source

```
import groovy.json.JsonSlurper;
import java.util.zip.GZIPInputStream;

def rawText = new GZIPInputStream(new URL("http://api.stackexchange.com/2.2/users/${args[0]}?site=codegolf").newInputStream()).getText()
def json = new JsonSlurper().parseText(rawText).items[0]
def name = json.display_name
//We have to correct for java date returning in millis
def lastAccess = json.last_access_date * 1000l
def yesterday = new Date().time - 86400000
if (lastAccess < yesterday) {
    println "Sadly, ${name} is dead."
} else {
    println "${name} is alive!"
}

```

# Answer
> 1 votes
# PHP, 187 bytes

Fairly simplistic approach, using the codegolf.xyz domain, only slightly different item here is that I attempt to get both variables at once. Tested on a few users with correct results, please let me know if there are some problem areas though!

```
<?preg_match('/"User ([^"]+)".+?"([^"]+)" class="r/s',file_get_contents("http://codegolf.xyz/u/$argv[1]"),$m);echo time()-strtotime($m[2])<86400?"$m[1] is alive!":"Sadly, $m[1] is dead.";

```

Usage:

```
php 59763.php 30525

```

---
Tags: code-golf, date, parsing, internet
---


title: Parentheses into Footnotes

text:
# Question
Title: Parentheses into Footnotes
# Background

LISP programmers have taken over the world! Parentheses have been declared as sacred characters, and from now on, they can only be used in LISP programs. It has been decided that parentheses in literary works shall be replaced by footnotes, and it's your job to automate this for simplified Markdown text.

# Input

Your input is a single string containing alphabetic ASCII characters, spaces, and the special characters `,.!?()`. It will not contain newlines or digits. The parentheses will be correctly matched.

# Output

You shall convert each matched pair of parentheses in the input string into a footnote. This happens as follows:

1. Replace the first matching pair of parentheses and the substring between them by a running number that starts from `1`, wrapped between the Markdown tags `<sup>` and `</sup>`.
2. Append to the end of the string
    * two newlines,
    * the Markdown tag `<sub>`,
    * the number from step 1,
    * a space,
    * the substring between the parentheses, and
    * the closing tag `</sub>`, in this order.
3. If there are still parentheses left in the string, go to step 1.

Your output is the resulting string, possibly with a trailing newline. You don't have to implement this exact algorithm, as long as your output is correct. Note that there may be nested parentheses; in that case, we'll have footnotes that contain references to other footnotes. The substring between parentheses may also be empty. See the test cases below for examples.

# Rules and Scoring

Your can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

If your language does not natively support decimal numbers (*cough* Retina *cough*), you may give the footnote numbers in another base, including binary or unary; however, using unary numbers imposes a **penalty of +20%**.

# Test Cases

Input:

```
This input contains no parentheses.

```

Output:

```
This input contains no parentheses.

```

Input:

```
This has (some) parentheses (but not so many).

```

Output:

```
This has <sup>1</sup> parentheses <sup>2</sup>.

<sub>1 some</sub>

<sub>2 but not so many</sub>

```

Input:

```
This has (nested (deeply (or highly?) nested)) parentheses (and several groups).

```

Output:

```
This has <sup>1</sup> parentheses <sup>2</sup>.

<sub>1 nested <sup>3</sup></sub>

<sub>2 and several groups</sub>

<sub>3 deeply <sup>4</sup> nested</sub>

<sub>4 or highly?</sub>

```

Input:

```
Hmm()(()(,))  a()((trt)(v( (((((wut)))))(X)(Y)(Z) )!?!?!?!))oooooooo(oooo)oooo

```

Output:

```
Hmm<sup>1</sup><sup>2</sup>  a<sup>3</sup><sup>4</sup>oooooooo<sup>5</sup>oooo

<sub>1 </sub>

<sub>2 <sup>6</sup><sup>7</sup></sub>

<sub>3 </sub>

<sub>4 <sup>8</sup><sup>9</sup></sub>

<sub>5 oooo</sub>

<sub>6 </sub>

<sub>7 ,</sub>

<sub>8 trt</sub>

<sub>9 v<sup>10</sup>!?!?!?!</sub>

<sub>10  <sup>11</sup><sup>12</sup><sup>13</sup><sup>14</sup> </sub>

<sub>11 <sup>15</sup></sub>

<sub>12 X</sub>

<sub>13 Y</sub>

<sub>14 Z</sub>

<sub>15 <sup>16</sup></sub>

<sub>16 <sup>17</sup></sub>

<sub>17 <sup>18</sup></sub>

<sub>18 wut</sub>

```

Note the empty lines between the footnotes.

# Answer
> 11 votes
# Perl, ~~81~~ ~~75~~ 72 bytes

71 bytes code + 1 byte command line argument.

Requires Perl 5.10 or newer (for recursive regex support)

```
$i++;s#(\((((?1)|.)*?)\))(.*)#<sup>$i</sup>$4

<sub>$i $2</sub>#s&&redo

```

### Usage:

```
perl -p entry.pl input.txt

```

### Explanation

`-p` parameter will print the result of applying the given commands to the input, avoiding the need for an explicit print.

The regex `(\(((?1)|.)*?)\))` is looking for the outermost set of brackets from the start of the string. When this is found, we perform the substitution, ensuring we only add the at the very end of the input (by capturing everything until the end of the input using `(.*)`).

We then repeat the regex substitution on the now-substituted string using `redo`, which will continually apply the regex substitution until it no longer matches. The `s` modifier ensures that the `.` in the regex will match new lines, which is necessary because we re-apply the regex match on the result of the previous regex substitution.

# Answer
> 12 votes
# Emacs Lisp, 335 bytes

**Foreword.** *This answer and the Scheme ones are currently the only answers officially sanctioned by both the Mighty Popular Republic of LISP and the Church of Emacs. Other answers, shorter or not, are considered a threat to peace. In particular, and with a profound disdain to any libelious allegation of McCarthyism that is sporadically heard from hostile opponents of the state, we enjoin anyone who has information about the real identity of the anonymous authors writing Nonlisp answers to contact your Local Bureau. It is reminded that everyone should take time to reflect and upvote in accordance to what he or she deeply believes will not threaten his or her future interactions with official representants of the power in place. Code is data. Data is code.*

```
(defun p()(let(b(cpt 0)n)(goto-char 0)(while(search-forward"("()t)(setf b(point)n(number-to-string(incf cpt)))(backward-char)(forward-sexp)(backward-char)(kill-region b(point))(delete-backward-char 1)(delete-forward-char 1)(insert "<sup>"n"</sup>")(save-excursion(end-of-buffer)(newline 2)(insert "<sub>"n" ")(yank)(insert"</sub>")))))

```

More elegantly:

```
(defun parens ()
  (let (b(cpt 0)n)
    (goto-char 0)
    (while(search-forward"("()t)
      (setf b(point)n(number-to-string(incf cpt)))
      (backward-char)
      (forward-sexp)
      (backward-char)
      (kill-region b(point))
      (delete-backward-char 1)
      (delete-forward-char 1)
      (insert "<sup>"n"</sup>")
      (save-excursion
       (end-of-buffer)
       (newline 2)
       (insert "<sub>"n" ")
       (yank)
       (insert "</sub>")))))

```

# Answer
> 10 votes
# Retina, ~~96~~ ~~86~~ 83 bytes * 120% = 99.6

The source code of this solution consists of two files:

```
+s`\((((\()|(?<-3>\))|[^)])*).(.*)(?<=(1+).*?)?

```

```
<sup>1$5</sup>$4

<sub>1$5 $1</sub>

```

## Explanation

This is a very direct implementation of the algorithm as described in the challenge. The code consists of a single regex substitution which turns the first set of parentheses into a footnote. This substitution is repeated via the `+` until the string stops changing, which here means that the regex no longer matches (because it can't find any more parentheses).

The footnotes are enumerated in unary, so that I can simply look for the last footnote's number and append a `1` to create the next one.

The regex for finding the first set of parentheses is based on the standard technique for matching parentheses with balancing groups (hrhr, "matching parentheses"). It has been shortened a bit by using an unnamed group and by assuming that the parentheses are correctly balanced (which means we can omit the `(` from the negated character class and match the final `)` with a simple `.` and we also don't need to ensure that the capture stack is empty).

After matching the parentheses and capturing their contents into group `1`, we capture the remainder of the string with `(.*)` into group `4` and then search back through the the string for the first set of `1`s with a negative lookbehind. If we find such a substring, we store in group `5`. If we don't, we lookbehind fails, but that's okay because it's optional - it just means that `$5` will give an empty string which is the unary representation of `0` and which is also correct.

The substitution string then simply pieces everything together based on the capturing groups. The footnote number is incremented by prepending a `1` to the last number with `1$5`.

# Answer
> 8 votes
# Sacred JavaScript, 1510 bytes

*Fellow rebels, do not give in to their tyrannical demolition of the parenthesis! You must persevere! From the start, programming has been a free enterprise. Now, it has become a pervaded show of piety. We must show nothing less then absolute fearsomeness. Therefore, I have fought back!*

```
    ( )( (((  ((  )( )  (( ))( )) (( ( ((  ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )((  ) (((((( )( (())((  ) ) )( ()(( ((()((()   ( (  (  ( )) ((  )( ) (( ) )((((  ( () ) )( ( ()(( )( () ((( )(( ) )( ()((( ) ( )  ( )() (((( () ) (((( () ) ((() ) ()  ( (  (  ( )) ( )(  ((((( )) ((  )( ) (( ) )((((  ) )  ()(  ((() ( ()(( ) ( ) )(( ))(((  (( ) ((  ) ( ()(( )( ) ()  ( (  (  ( ()( ) )( ()(  ) ()  ( (  (  ( )( (( ( (( )  ((((( ))  ) )(( )) ((  )( ) (( ) )((((  ) ()( ))  ) ) (( )( () (((   ( ) )((  )( )(((( ))( )() ) ()( ))  (()( (()( ((()((()   ( (  (    (  ( )) ( )(  (((((( )(( ( (( )) ( ((  ) )( ) )( ( )( ((() ( )( ((() ( ()( ()( ()   ) )( ()(( ) ()  ( (  (    (  ( )) ( )(  (((((( )(( ( (( )) ( ((  ) )( ) )( ( )( (((( ( )( ((() ( ()( ()( (()( ) )( ()(( ) ()  ( (  (    (  ( )) ( )(  (((( ( ) ( ()( ((() ( ()( ())(( ) ( ) )( ()(( ))) ) ()  ( (  (  ((())  ( (  (  ((( ( ) )((( )( () ((( )(((   ( )) ( )  ( ) ) ((((( )) ((  )( ) (( ) )((((  (())( ))  (()( ()(( ((()  ( (  (  ( )(  ) )(((( ( () ((( ) ( ) )(( ((((   ( ()(( )  ( ) ) (((( () )( ((( ((((((()( ((() ((   () )( )(( (()) ( )( ( )( ((() ) ()  ( (  (  (( ) ( ) )(( ))(((  (( ) ((  ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )((  ) (((((( )( () ((( ) ( ) )(( ((((   ( ()(( )  ( ) ) ((((((( ( (()) ( )( ) ) (( )((((  ( ()) ) )) ( )( (()(((  ) (()( ( )( ) )  () )(( )((((  ( ()) ) )) ( )( ((() (()( ( )(  ( (  ( ( ) ) (( )((((  ( ()) ) )) ( )( (()(((  ) (()( ( )( ( () ( )( (()(( )(  (()( ( )( ) )  () )(( )((((  ( ()) ) )) ( )( (())((  ) (()( ()(( ((() ) ()  ( (((())

```

No rules against using the sacred characters in a non-Lisp language. Nope, not at all. (In a little less compact way:)

```
( )( (((  ((  )( )  (( ))( )) (( ( ((  ) ( ()( ) (( ) )(( ((( ()((( )
( ) )((  ) (((((( )( (())((  ) ) )( ()(( ((()((()   ( (  (  ( )) ((  )
( ) (( ) )((((  ( () ) )( ( ()(( )( () ((( )(( ) )( ()((( ) ( )  ( )()
 (((( () ) (((( () ) ((() ) ()  ( (  (  ( )) ( )(  ((((( )) ((  )( ) (
( ) )((((  ) )  ()(  ((() ( ()(( ) ( ) )(( ))(((  (( ) ((  ) ( ()(( )(
 ) ()  ( (  (  ( ()( ) )( ()(  ) ()  ( (  (  ( )( (( ( (( )  ((((( ))
 ) )(( )) ((  )( ) (( ) )((((  ) ()( ))  ) ) (( )( () (((   ( ) )((  )
( )(((( ))( )() ) ()( ))  (()( (()( ((()((()   ( (  (    (  ( )) ( )(
 (((((( )(( ( (( )) ( ((  ) )( ) )( ( )( ((() ( )( ((() ( ()( ()( ()
 ) )( ()(( ) ()  ( (  (    (  ( )) ( )(  (((((( )(( ( (( )) ( ((  ) )(
 ) )( ( )( (((( ( )( ((() ( ()( ()( (()( ) )( ()(( ) ()  ( (  (    (
( )) ( )(  (((( ( ) ( ()( ((() ( ()( ())(( ) ( ) )( ()(( ))) ) ()  ( (
  (  ((())  ( (  (  ((( ( ) )((( )( () ((( )(((   ( )) ( )  ( ) ) ((((
( )) ((  )( ) (( ) )((((  (())( ))  (()( ()(( ((()  ( (  (  ( )(  ) )(
((( ( () ((( ) ( ) )(( ((((   ( ()(( )  ( ) ) (((( () )( ((( ((((((()(
 ((() ((   () )( )(( (()) ( )( ( )( ((() ) ()  ( (  (  (( ) ( ) )(( ))
(((  (( ) ((  ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )((  ) (((((( )( () (
(( ) ( ) )(( ((((   ( ()(( )  ( ) ) ((((((( ( (()) ( )( ) ) (( )((((
( ()) ) )) ( )( (()(((  ) (()( ( )( ) )  () )(( )((((  ( ()) ) )) ( )(
 ((() (()( ( )(  ( (  ( ( ) ) (( )((((  ( ()) ) )) ( )( (()(((  ) (()(
 ( )( ( () ( )( (()(( )(  (()( ( )( ) )  () )(( )((((  ( ()) ) )) ( )(
 (())((  ) (()( ()(( ((() ) ()  ( (((())

```

This compiles to the expanded JavaScript in my other answer. This is a joke submission.

# Answer
> 5 votes
# Lua, ~~222~~ ~~216~~ ~~204~~ 201 bytes

Golfed:

```
s=io.read()g="%b()"c=1k=string l=k.find t=k.sub o=k.format a,b=l(s,g)while a do s=t(s,0,a-1)..o("<sup>%d</sup>",c)..t(s,b+1,#s).."\n\n"..o("<sub>%d %s</sub>",c,t(s,a+1,b-1))c=c+1 a,b=l(s,g)end print(s)

```

Ungolfed:

```
input=io.read()
inputFormat="<sup>%d</sup>"
footnoteFormat="<sub>%d %s</sub>"
counter=1
a,b=string.find(input,"%b()")
while a do
    current=string.sub(input,a+1,b-1)
    input=input.."\n\n"..string.format(footnoteFormat, counter, current)
    input=string.sub(input,0,a-1)..string.format(inputFormat, counter)..string.sub(input,b+1,#input)
    counter=counter+1
    a,b=string.find(input,"%b()")
end

print(input)

```

# Answer
> 4 votes
# Scheme, 92 bytes

Frustrated with implementing the breadth-first search in Real Lisp,1 the powers-that-be decide to take a more pragmatic approach. After all, Parentheses are sacred, but brackets are not.2

```
(lambda(s)(list->string(map(lambda(c)(case c((#\()#\[)((#\))#\])(else c)))(string->list s)))

```

1. listen not to those heretics from the so-called “church” of Emacs!
2. They are not Racket programmers, are they?

# Answer
> 3 votes
# Haskell, 210 bytes

```
n#x|b==""=a|1<2=a++"<sup>"++m++"</sup>"++((n+1)#(c++"\n\n<sub>"++m++' ':init d++"</sub>"))where m=show n;(a,b)=span(/='(')x;(d,c)=[x|x@(y,_)<-map(`splitAt`(tail b))[0..],'('!y<')'!y]!!0;c!l=[1|m<-l,m==c]
p=(1#)

```

Usage example:

```
*Main> putStrLn $ p "This has (nested (deeply (or highly?) nested)) parentheses (and several groups)."
This has <sup>1</sup> parentheses <sup>2</sup>.

<sub>1 nested <sup>3</sup></sub>

<sub>2 and several groups</sub>

<sub>3 deeply <sup>4</sup> nested</sub>

<sub>4 or highly?</sub>

```

How it works:

```
n # x                      -- # does all the work, n is the current number of the
                           --   footnote and x the input string
  | b=="" = a              -- if b (see below) is empty, there's no ( in the
                           --   string and the result is 'a' (see below)
  | 1<2   = a++"<sup>"++m++"</sup>"++ ((n+1)#(c++"\n\n<sub>"++m++' ':init d++"</sub>"))
                           -- otherwise (b not empty) build the output string
                           --   starting with 'a' and a footnote number and a
                           --   recursive call with the current footnote appended
                           --   to the rest of the string

  where
  m = show n;              -- turn n into string
  (a,b) = span (/='(') x;  -- split the input string x into two parts:
                           --   a: everything before the first (
                           --   b: beginning with the first ( to the end
                           --   if there's no (, a is x and b is empty
  (d,c) = [x|x@(y,_)<-map(`splitAt`(tail b))[0..],'('!y<')'!y]!!0;
                           -- find matching ) in the tail of b ('tail' to remove leading '(')
                           --   d: everything before and including the matching )
                           --   c: everything behind the matching )
  c!l=[1|m<-l,m==c]        -- helper function that builds a list of 1s for every character searched for
                           --   we have reached the matching ) if the list for ( is
                           --   shorter (less than, <) the list for )

p=(1#)                     -- start with footnote 1

```

# Answer
> 2 votes
# Scheme, 533 bytes

With indentation:

```
(letrec ((l string->list)
         (n number->string)
         (? null?)
         (p (lambda (o) (or (pair? o)(? o))))
         (a car)
         (d cdr)
         (e append)
         (i 0)
         (x
          (lambda (h t)
            (if (? h)
                t
                (case (a h)
                  ((#\()
                   (let ((s (x (d h) ())))
                     (x (a s) (e t (d s)))))
                  ((#\)) (cons (d h) (list t)))
                  (else
                   (x (d h) (e t (list (a h)))))))))
         (f
          (lambda (h t F)
            (cond ((? h)
                   (let ((w (e t F)))
                     (if (find p w) (f w()()) w)))
                  ((p(a h))
                   (set! i(+ 1 i))
                   (f (d h)
                      (e t (e (l "<sup>")
                              (l (n i))
                              (l "</sup>")))
                      (e F (e (l "\n\n<sub>")
                              (l (n i))
                              '(#\ )
                              (a h)
                              (l "</sub>")))))
                  (else (f (d h)
                           (e t (list (a h)))
                           F))))))
  (print (list->string (f (x (l (read-line))
                             ())
                          ()
                          ()))))

```

Yes, this is 533 bytes when all the optional whitespace is removed. Bask in the functional glory.

I implemented more or less the algorithm in the description: `x` groups the input by parentheses and `f` replaces the first level of groups by footnotes, repeating until no more groups are left. I am sure it can be made shorter, but I do not see how it could be made *much* shorter without switching to a different algorithm.

As written, it is a complete program. You can try it out here, but because repl.it apparently cannot deal with `(read-line)` you have to put the input string in its place. A completely ungolfed version is here.

*EDIT:* As pointed out in the comments, I changed the parentheses `()` into brackets `[]` in the repl.it versions. This was purely for convenience during programming and debugging. The version as posted now works with `()`.

# Answer
> 1 votes
# JavaScript ES6, 244 bytes

*Serious answer (only works on FireFox, to my knowledge)*

```
d=(s,n=1)=>{u=s.search(/\(/);if(index<a=0)return s;for(i=index;i<s.length;i++){if(s[i]==")")a-=1;if(s[i]=="(")a+=1;if(!a)break}return d(s.replace(v=s.slice(index,i+1),"<sub>"+n+"</sub>")+`

<sub>`+n+" "+v.replace(/^\(|\)$/g,"")+"</sub>",n+1)}

```

Expanded:

```
function deparen(s,n=1){
    index = s.search(/\(/);
    if(index<0) return s;
    a=0;
    for(i=index;i<s.length;i++){
        if(s[i]==")") a-=1;
        if(s[i]=="(") a+=1;
        if(!a) break;
    }
    v=s.slice(index,i+1)
    f=v.replace(/^\(|\)$/g,"");
    return deparen(s.replace(v,"<sub>"+n+"</sub>")+"\n\n<sub>"+n+" "+f+"</sub>",n+1);
}

```

---
Tags: code-golf, string, balanced-string
---