New Year’s Probability Fun!

December 31st, 2008

There’s a post today over at coding horror that proposed a very simple probability problem. After more than 400 comments (and counting) I’m very surprised that so many people have the wrong answer. The question is this:

Let’s say, hypothetically speaking, you met someone who told you they had two children, and one of them is a girl. What are the odds that person has a boy and a girl?

Actually, I’m not sure if by “odds” Jeff meant this, or probability — as is the case in most everyday use. But assuming that he meant probability, then the solution is as follows.

Let A be the event of having a girl.
Let B be the event of having a boy.

Assume that P(A) = P(B) = 0.5

We know that the person has a girl, thus we are trying to find P(B|A) (probability of B given that A has occurred).

Now we note that A and B are independent events, thus P(B|A) = P(B) = 0.5 (conditional probability).

And there you go, the probability of the person having a boy given that person has a girl is 0.5 (or 50%).

Happy New Year’s folks!

Do you mean partial application?

December 8th, 2008

As I’ve been digging through more functional programming techniques, I often see people mention Curry functions. As it turns out, when a lot of people say “curry” they really mean Partial Application. For example, this page here about curry implementation in Python, or implementations in JavaScript. I did find one implementation in JavaScript that worked, but it’s rather long.

I came up with my own implementation in less than 10 lines of JavaScript code. Before I show it though, let’s define what we should expect. The follow are the JavaScript code we’re going to run, and the expected output are in the comments.

function add(a, b) {
    return a + b;
}

function add5(a, b, c, d, e) {
    return a + b + c + d + e;
}

function saySomething(x, y, z) {
    alert(x + y + z);
}

add.curry()(4)(6);
//--> 10

add5.curry()(1)(2)(3)(4)(5);
//--> 15

add5.curry()(1)(2);
//--> function with one parameter

add5.curry()(1)(2)(3)(4)(5)(6);
//--> TypeError: add5.curry()(1)(2)(3)(4)(5) is not a function

saySomething.curry()('Hello ')('World! ')('foo bar');
//--> Alert mssage "Hello World! foo bar" pops up

Remember that currying a function, say f:(X x Y) –> Z means that curry(f):X –> (Y –> Z). And for a function g with n arguments, curry(g) transforms the function g into a chain of n functions that each take exactly one argument.

So here is my implementation of the curry function.

Function.prototype.curry = function() {
    var savedArgs = [],  n = this.length, func = this;

    return (function(x) {
        savedArgs.push(x);
        if (savedArgs.length < n) return arguments.callee;
        else  return func.apply(null, savedArgs);
    });
};

Note that is utilizes anonymous functions in JavaScript, which recursively calls itself using the arguments.callee reference.

Publisher/Subscriber Fun with jQuery

December 5th, 2008

I’ve decided to try out the Publish/Subscribe pattern for some of the new things we’re creating at work. So far I think it’s working out really well. The neatest thing is that a Pub/Sub system can be created in JavaScript in very little amount of code. And with the help of jQuery, you can shorten the amount of code even more.

Here is the entire system in jQuery.

jQuery.subscribe = function(signal, scope, fnName) {
    var curryArgs = Array.prototype.slice.call(arguments, 3);
    $(window).bind(signal, function () {
        var normalizedArgs = Array.prototype.slice.call(arguments, 1);
        scope[fnName].apply(signal, curryArgs.concat(normalizedArgs));
    });
    return jQuery;
};

jQuery.publish = function(signal) {
    $(window).trigger(signal, Array.prototype.slice.call(arguments, 1));
    return jQuery;
};

Notice that the subscriber function allows for partial applicationof the handler function. This can be useful in some cases.

Project Euler: Problem 2

November 18th, 2008

An elegant solution to the Fibonacci problem.

from math import sqrt, pow

def fib(n):
    phi = (1 + sqrt(5))/2
    return int((pow(phi, n) - pow(1 - phi, n))/sqrt(5))

if __name__==’__main__’:
    i = 3
    sum = 0
    stop = 4000000

    while True:
        curr = fib(i)

        if curr > stop: break

        sum = sum + fib(i)
        i = i + 3
    print sum

Unlike the other solutions I found online, mine is not done through brute-force. To generate the Fibonacci number at index i, you don’t need to loop through the sequence until i. There is a closed form solution to this. For even-numbers in the sequence, it’s rather simple. An even number occurs with index 3, 6, 9, 12, 15, … Notice a pattern? I hope you do. :)

Project Euler: Problem 28

November 10th, 2008

Thought I’d post up my solution to Problem 28 on Project Euler.

After the answer was submitted I read through some of the other code the people have posted. It seems that there are a lot more programmers than mathematicians because almost all of the solutions were brute-force algorithms… and quite a few were written in assembly. *shrug*

Anyway, here is the problem.

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

It can be verified that the sum of both diagonals is 101.

What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?

The first you to notice is that you don’t have to actually construct the spiral in order to solve this problem. It can be shown quite simply that in an nxn spiral, the values of the four corners are as follows:

top-right: n^2
top-left: n^2 - n + 1
bottom-left: n^2 - 2n + 2
bottom-right: n^2 - 3n + 3

Adding all that up yields 4n^2 -6n + 6.

At this point you can easily loop through from 3 to 1001 (in increments of 2) and add up the results. Just make sure you add a 1 to the results for the base case. :)

Of course, if you’re like me you wouldn’t be satisfied with that result. All we’re dealing with are some simple summations, so the result for an nxn spiral should be easily expressed by a formula. In fact, here’s the formula.

Sum(i = 1:500)[4(2*i + 1)^2 - 6(2i + 1) +6]

The beginning reads “sum from i=1 to 500″… I’m not too sure how to type out sigma notations properly.

Converting the summation into closed form gives the formula we’re looking for. I’m leaving out the steps, but it’s fairly simple anyway.

(16n^3)/3 + (10n^2)/2 + 26n/3

And here is the complete solution in Python.

from math import pow
def prob28(n): return (16*pow(n, 3) + 26*n)/3 + 10*pow(n, 2)
print prob28(500) + 1

Project Euler

November 10th, 2008

I came across this interesting project online. It’s called Project Euler, and the point is to use both mathematical skills and programming skills to solve the posted problems. You can use whatever language to solve, and you input the answer to validate it. So far I’ve worked on the very first one, and it’s pretty fun, both from a programming perspective, and from a math geek POV.

Here’s my solution to Problem 1:

Problem: Add all the natural numbers below one thousand that are multiples of 3 or 5.

Solution (Python):
reduce(lambda x,y: x+y, ifilter(lambda x: x%3==0 or x%5==0, range(1,1000)))

:)

World’s Best Dance Crew?

September 19th, 2008

I’m sure everyone’s heard of the show America’s Best Dance Crew. Last year’s winner, the Jabbawokeez, are now famous across all of North America. They are super talented, no question about that, but sadly the average American doesn’t even know the state of world B-boying. I think most people in North America think B-boy crews in the US = best in the world. That’s totally wrong though… in fact crews in the US is not even close to being in the top. Talk to anyone know who’s what they’re talking about and they’ll say that currently South Koreans are the best b-boys in the world. Followed closely by France and Japan. In fact, in recent years, South Korean crews have been winning a lot of the annual Battle of the Year competitions, whereas US has not even reached the finals.

Here’s the crew that won last year’s BOTY, Extreme Crew. Enjoy!

Automated Trading Program Caused UAL Stocks to Drop $1.14B

September 10th, 2008

United Airlines’ stocks dropped by $1.14B today as automated trading programs quickly sold stocks after crawling a Google news story. The news story was from 2002, when UAL filed for bankruptcy. Google found the article, but since no timestamp was on it, it reported the story as recent. This triggered programs that automatically scan for news articles and take appropriate trading actions to immediately sell all UAL stocks, causing it to drop from $12 a share to $3 a share. It has since recovered back to $10 a share.

I found this story hilarious. A badly crawled article triggers robots to cause a company’s stocks to drop $1.14B. How messed up is that?

Read more about it here.

Google News Archives Goes Back to early 1900s

September 8th, 2008

Google just finished digitizing newspapers that date back to early 1900s, for their news archives search.

For example, here’s an article from the Pittsburgh Post-Gazette for the moon landing. Pretty cool eh?

So Globe & Mail’s archives search goes back to 2000, while Google’s goes back to early 1900s. And I think NY Times recently went back as far as 1800s? — or maybe early 1900s too. Globe and Fail!

What Happened to Single-File?

August 18th, 2008

Remember back in grade school your teachers will always have you line-up in single-files along with the other kids. This happened before recess, before lunch, before the school day ends.

Now, we’re all grown up. We’re adults. We don’t line-up single-file anymore. Nope! We found a better way…

The TTC subway pulls up, with a sea of people crowding in front of the tracks. The door opens, and it’s everyone for themselves. Pushing, shoving, anything goes!

This morning on my commute to work, the subway was delayed at Yonge station (yet again). And there were maybe 3-4 times the normal number of people at the station. Let me just say it wasn’t pretty. When the train finally came and the door opened, people were trying to get on when the other passengers were still trying to get off! All I heard was one lady shouting in a very frustrated voice, “Let the other people off first! Geez!” Finally, one decent person among the zombies.

Why does Toronto, and probably all of North American, suck so much? Why can’t we be like the Japanese and line-up for the trains. The most efficient way to board a train is to line-up. It should be first-in-first-out queue so it’s fair. I hate when you get there first but some punk pushes his/her way in front of you.