Skip to content

Commit

Permalink
re-added solution
Browse files Browse the repository at this point in the history
  • Loading branch information
peterkhayes committed Nov 4, 2014
1 parent 3d57be9 commit 9b7bb02
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
12 changes: 11 additions & 1 deletion DynamicProgramming/extras.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
// Recursive solution - not nearly as good as DP.

var cache = [];
for (var i = 0; i < size; i++) {
cache.push([]);
}

var recurse = function(row, col) {
if (cache[row][col] !== undefined) {
return cache[row][col];
}
if (row === size - 1) {
return {
cost: input[row][col],
Expand Down Expand Up @@ -30,10 +38,12 @@ var recurse = function(row, col) {
choice = center;
}

return {
var retVal = {
cost: choice.cost + input[row][col],
path: [col].concat(choice.path)
};
cache[row][col] = retval;
return retval;
};

var bestPath = null;
Expand Down
13 changes: 13 additions & 0 deletions DynamicProgramming/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ var size = 12;

var findMinimumPath = function(input) {

// Dynamic programming woo!
for (var row = size - 2; row >= 0; row--) {
for (var col = 0; col < size; col++) {

var left = input[row+1][col-1] || Infinity;
var center = input[row+1][col];
var right = input[row+1][col+1] || Infinity;

// Update the square above these choices.
input[row][col] += Math.min.apply(null, [left, center, right]);
}
}

// This is the "greedy" solution - it's not very good, because
// it never "looks ahead" to the rows yet to come.
// But it might be of some help to you as you write your own!
Expand Down

0 comments on commit 9b7bb02

Please sign in to comment.