-
Notifications
You must be signed in to change notification settings - Fork 0
/
Text Comparison.js
96 lines (87 loc) · 2.96 KB
/
Text Comparison.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class TextComparisonExtension {
getInfo() {
return {
id: 'textcomparison',
name: 'Text Comparison',
blocks: [
{
opcode: 'calculateLevenshteinDistance',
blockType: 'reporter',
text: 'calculate Levenshtein distance of [text1] and [text2]',
arguments: {
text1: {
type: 'string',
defaultValue: 'Hello'
},
text2: {
type: 'string',
defaultValue: 'Helo'
}
}
},
{
opcode: 'calculateSimilarityScore',
blockType: 'reporter',
text: 'calculate similarity score of [text1] and [text2]',
arguments: {
text1: {
type: 'string',
defaultValue: 'Hello'
},
text2: {
type: 'string',
defaultValue: 'Helo'
}
}
}
]
};
}
calculateLevenshteinDistance(args) {
const text1 = args.text1;
const text2 = args.text2;
return this.levenshteinDistance(text1, text2);
}
calculateSimilarityScore(args) {
const text1 = args.text1;
const text2 = args.text2;
return this.similarityScore(text1, text2);
}
levenshteinDistance(text1, text2) {
const m = text1.length;
const n = text2.length;
// Create a 2D array to store the Levenshtein distances
const dp = new Array(m + 1);
for (let i = 0; i <= m; i++) {
dp[i] = new Array(n + 1);
}
// Initialize the first row and column of the array
for (let i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (let j = 0; j <= n; j++) {
dp[0][j] = j;
}
// Compute the Levenshtein distances
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (text1[i - 1] === text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(
dp[i - 1][j] + 1, // Deletion
dp[i][j - 1] + 1, // Insertion
dp[i - 1][j - 1] + 1 // Substitution
);
}
}
}
return dp[m][n];
}
similarityScore(text1, text2) {
const distance = this.levenshteinDistance(text1, text2);
const maxLength = Math.max(text1.length, text2.length);
return 1 - distance / maxLength;
}
}
Scratch.extensions.register(new TextComparisonExtension());