Well, here's my contribution. It's in python(as is usual for me). My solution essentially builds the triangle up from the ground up(instead of the more common recursive approach). The heart of the algorithm is the next_row function which, given a row computes the next one. I include both a documented and verbose answer as well as a 3-liner called compact_next_row() :D
def pascal_idx(n):
"""
In the pascal triangle the value at the (n,m) is the sum of
(n-1,m) and (n-1,m-1) (where n is the row and m is the column)
This function generates a sequence given the current row in the
triangle of the indices in the previous row which should be added
Examples:
>>> list(pascal_idx(1))
[(0,), (0,)]
This means that row 1(the 2nd row) should obtain it's first and
second elements by copying the first element of row 0.
>>> list(pascal_idx(2)) [(0,), (0, 1), (1,)]
Row 2(the 3rd row) should obtain its first element by copying
element 0 from row 1, its second element by summing elements 0 and
1 in row 1 and its last element by copying element 1 from row 1
One last example:
>>> list(pascal_idx(3))
[(0,), (0, 1), (1, 2), (2,)]
"""
yield (0,)
for i in range(1,n):
yield i-1,i
yield (n-1,)
def sum_of_indices(l, indices):
"""
Calculates the sum of the elements in l pointed to by the indices
"""
s = 0
for i in indices:
s += l[i]
return s
def next_row(row):
"""
Calculates the next row given a row of the pascal triangle. It
invokes pascal_idx to know how to build the row and then performs
the necessary sums
"""
result = []
for indices in pascal_idx(len(row)):
result.append(sum_of_indices(row, indices))
return result
def compact_next_row(row):
soi = lambda l,indices: sum(map(lambda a:l[a], indices))
indices = [(0,)] + [(i-1,i) for i in range(1, len(row))] + [(len(row)-1,)]
return [soi(row, i) for i in indices]
if __name__ == "__main__":
"""
A small example
"""
print "The usual way:"
row = [1]
for i in range(10):
print ",".join(map(str, row))
row = next_row(row)
print "\nNow to try out the compact way:"
row = [1]
for i in range(10):
print ",".join(map(str, row))
row = compact_next_row(row)
Result:
$ python pascal.py
The usual way:
1
1,1
1,2,1
1,3,3,1
1,4,6,4,1
1,5,10,10,5,1
1,6,15,20,15,6,1
1,7,21,35,35,21,7,1
1,8,28,56,70,56,28,8,1
1,9,36,84,126,126,84,36,9,1
Now to try out the compact way:
1
1,1
1,2,1
1,3,3,1
1,4,6,4,1
1,5,10,10,5,1
1,6,15,20,15,6,1
1,7,21,35,35,21,7,1
1,8,28,56,70,56,28,8,1
1,9,36,84,126,126,84,36,9,1