Skip to content

Instantly share code, notes, and snippets.

@tychota
Last active January 7, 2016 12:07
Show Gist options
  • Save tychota/8aff23d8f685eb845baf to your computer and use it in GitHub Desktop.
Save tychota/8aff23d8f685eb845baf to your computer and use it in GitHub Desktop.
Th. Exo 3
'use strict';
let solutions = {};
let bestPathValue = 0;
let crop = (mat, col_start, row_start, col_end, row_end) => {
col_end = col_end || mat.length;
row_end = row_end || mat[0].length;
return mat.slice(col_start, col_end).map(
row => row.slice(row_start, row_end)
)
}
class Path {
constructor(path, acc, left, right){
this.path = path || 'START';
this.acc = acc || null;
this.left = left || null;
this.right = right || null;
}
isLeaf() {
if (!this.left & !this.right) return true;
return false;
}
constructFromMatrix(matrix) {
this.acc += matrix[0][0];
let dim_col = matrix.length;
let dim_row = matrix[0].length;
if (dim_col > 1) {
this.left = new Path(this.path + ' RIGHT', this.acc)
this.left.constructFromMatrix(crop(matrix, 1, 0));
}
if (dim_row > 1) {
this.right = new Path(this.path + ' DOWN', this.acc)
this.right.constructFromMatrix(crop(matrix, 0, 1));
}
if (this.isLeaf()){
this.path += ' STOP';
if (!solutions[this.acc])
solutions[this.acc] = [this.path];
else
solutions[this.acc].push(this.path);
bestPathValue = bestPathValue > this.acc ? bestPathValue : this.acc;
}
}
}
let items = [[1, 2, 3],[0, 4, 5], [0,6, 2], [1, 2, 3]];
let mouse = new Path('START', 0);
mouse.constructFromMatrix(items);
console.log(solutions[bestPathValue]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment