Skip to content

Commit

Permalink
Added examples with diffing two words for chapter 09_dynamic_programming
Browse files Browse the repository at this point in the history
  • Loading branch information
yepstepz authored and egonSchiele committed Jun 24, 2017
1 parent 0a2ed9e commit 67dc8de
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 09_dynamic_programming/javascript/examples/base.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function initialize_matrix(rows, cols){
let matrix = [];
for (let i = 0; i < rows.length; i++){
matrix.push(Array(cols.length).fill(0));
}
return matrix;
}
25 changes: 25 additions & 0 deletions 09_dynamic_programming/javascript/examples/diff_two_words.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import initialize_matrix as base from "./base.js";

export default function diff( firstWord, secondWord ){
let arr1 = firstWord.split('');
let arr2 = secondWord.split('');
let matrix = initialize_matrix(arr1, arr2);
for (let i = 0; i < arr1.length; i++){
for (let j = 0; j < arr2.length; j++){
if( arr1[i] == arr2[j] ){
if( i > 0 && j > 0){
matrix[i][j] = matrix[i - 1][j - 1] + 1;
}else{
matrix[i][j] = 1;
}
} else {
if( i > 0 && j > 0){
matrix[i][j] = Math.max(matrix[i - 1][j], matrix[i][j - 1]);
}else{
matrix[i][j] = 0;
}
}
}
}
return matrix[arr1.length-1][arr2.length-1];
}

0 comments on commit 67dc8de

Please sign in to comment.