Write a function that takes an integer (i) and prints out the first 'i' rows of Pascal's Triangle (eg. i =5).
line = 5;
var pascalDepth = parseInt(line, 10); //The input integer is provided on a single line as a text value, so this handles it.
var testTriangle = pascalTriangle(pascalDepth);
var output = [];
maxlength = testTriangle.length;
var html = "<table>"
for(var i = 0; i < maxlength; i++){
html += "<tr>";
html += "<td>";
html += testTriangle[i];
html += "</td>";
html += "</tr>";
}
html+= "</table>";
document.write(html);
function pascalTriangle(totalLines, triangle) {
if (typeof triangle === 'undefined') {
triangle = [];
}
if (triangle.length === totalLines) {
return triangle;
}
if (triangle.length > 0) {
var triangleLine = [];
for (var i = 0; i < triangle.length; i++) {
if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') {
triangleLine.push(1);
} else {
triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i]));
}
}
triangleLine.push(1);
triangle.push(triangleLine);
} else {
triangle.push([1]);
}
return pascalTriangle(totalLines, triangle);
}
-----------------------------------------------------------------------------------------
var pascalDepth = parseInt(line, 10); //The input integer is provided on a single line as a text value, so this handles it.
var testTriangle = pascalTriangle(pascalDepth);
var output = [];
maxlength = testTriangle.length;
var html = "<table>"
for(var i = 0; i < maxlength; i++){
html += "<tr>";
html += "<td>";
html += testTriangle[i];
html += "</td>";
html += "</tr>";
}
html+= "</table>";
document.write(html);
function pascalTriangle(totalLines, triangle) {
if (typeof triangle === 'undefined') {
triangle = [];
}
if (triangle.length === totalLines) {
return triangle;
}
if (triangle.length > 0) {
var triangleLine = [];
for (var i = 0; i < triangle.length; i++) {
if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') {
triangleLine.push(1);
} else {
triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i]));
}
}
triangleLine.push(1);
triangle.push(triangleLine);
} else {
triangle.push([1]);
}
return pascalTriangle(totalLines, triangle);
}
-----------------------------------------------------------------------------------------
Write a function that prints out a breakdown of an integer into a sum of numbers that have just one non-zero digit.
eg., given 43018 it should print 40000 + 3000 + 10 + 8.
var arr = [];
var i =1;
var a = 40118;
var input = 40118;
while(a > 0)
{
if(a%(Math.pow(10,i)) > 0)
arr.push(a%(Math.pow(10,i)));
a = a-a%(Math.pow(10,i++));
}
arr.sort(function(a,b){ return b-a;});
document.write(input +" = " +arr.join(" + "));
var i =1;
var a = 40118;
var input = 40118;
while(a > 0)
{
if(a%(Math.pow(10,i)) > 0)
arr.push(a%(Math.pow(10,i)));
a = a-a%(Math.pow(10,i++));
}
arr.sort(function(a,b){ return b-a;});
document.write(input +" = " +arr.join(" + "));