google treasure hunt problem 1

21.05.2008

couple of days ago google launched a contest(?) named treasure hunt. i don't know if there's a price or something(not a big deal though). as a member of project euler and topcoder i quickly jumped to the challenge, and decided to publish the source code in here. i'll use python mostly, but who knows i may try other languages such as java, ocaml as well. here's first problem of the contest.
A robot is located at the top-left corner of a n * k grid.
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
note: n, k changes randomly. you'll get different numbers.

i'm not gonna explain the solution(i'm terrible at explaining things). this is nothing but binomial coefficient. here's our little python code that does the job.
def factorial(n):
  if n < 1:
    return 1
  return n*factorial(n-1)

def treasure(rows, cols):
  r = rows-1
  c = cols-1
  return (factorial(r+c) / (factorial(r) * (factorial(c))))
i wonder why i didn't use lambda, it would end in two lines. that flu is killin' me...
blog comments powered by Disqus