I should have set a timer on this one but I think it took 10 mins. This is what I ended up with in javascript - notice that it can print the whole triangle as a by-product of the implementation, but also because I have a (bad) habit of doing more than just what was required. Most of the implementation (testing) issues I suffered were due to lack of js knowledge (where is clone?) but the original skeleton of code that I wrote just thinking about the problem didn't need to change. I wouldn't have got it exactly right without a debugger though.
function printPascal(x, triangle) {
var row = [];
while (x) {
var next = clone(row);
next.push(1);
for (var i = 0; i < row.length - 1; i++)
next[i + 1] = row[i] + row[i + 1];
row = next;
x--;
if (triangle)
print(whitespace(x) + row);
}
if (!triangle)
print(row);
}
function clone(list) {
var clone = [];
for (i in list)
clone.push(list[i]);
return clone;
}
function whitespace(x) {
var white = " ";
while (x) {
white += " ";
x--;
}
return white;
}
printPascal(10);
Ignoring the whitespace and clone functions, is there a much simpler way of doing this?