forked from egonSchiele/grokking_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added examples with diffing two words for chapter 09_dynamic_programming
- Loading branch information
1 parent
0a2ed9e
commit 67dc8de
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
25
09_dynamic_programming/javascript/examples/diff_two_words.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |