Added examples with diffing two words for chapter 09_dynamic_programming
This commit is contained in:
committed by
Aditya Bhargava
parent
0a2ed9e4bb
commit
67dc8de543
7
09_dynamic_programming/javascript/examples/base.js
Normal file
7
09_dynamic_programming/javascript/examples/base.js
Normal file
@@ -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
09_dynamic_programming/javascript/examples/diff_two_words.js
Normal file
25
09_dynamic_programming/javascript/examples/diff_two_words.js
Normal file
@@ -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];
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user