numberOfPaths
by Christopher Stephens
HTML
<div class="print"></div>
CSS
table td {
padding:5px;
text-align:center;
}
JavaScript
var size = 5;
var TwoDArray = function (x, y) {
this.model = [];
var that = this.model;
for (var firstDepth = 0; firstDepth < x; firstDepth++) {
that.push([]);
for (var secondDepth = 0; secondDepth < y; secondDepth++) {
that[firstDepth].push(firstDepth + "x" + secondDepth);
}
}
};
TwoDArray.prototype.print = function () {
var that = this.model;
var toPrint = "<table>";
for (var firstDepth = 0; firstDepth < that.length; firstDepth++) {
toPrint += "<tr>"
for (var secondDepth = 0; secondDepth < that[firstDepth].length; secondDepth++) {
toPrint += " <td> " + that[firstDepth][secondDepth] + "</td>";
}
toPrint += ' </tr>'
}
$('.print').html(toPrint);
};
var grid;
getNumberOfPaths = function (gridSize, otherSize) {
var otherSize = otherSize || gridSize;
grid = new TwoDArray(gridSize, otherSize)
for (var y = 0; y < gridSize; y++) {
var above = y - 1 >= 0 ? grid.model[y - 1][y] : 0;
var left = y - 1 >= 0 ? grid.model[y][y - 1] : 0;
grid.model[y][y] = left + above;
//walk down
var walk = function (down) {
for (var x = y + 1; x < gridSize; x++) {
var above = grid.model[x - 1][y] || 0;
var left = grid.model[x][y - 1] || 0;
if (down) {
grid.model[x][y] = (above + left) || 1;
} else {
grid.model[y][x] = (above + left) || 1;
}
}
}
walk(true);
walk(false);
}
return grid.model[gridSize - 1][gridSize - 1];
};
console.log(getNumberOfPaths(5, 7));
grid.print();