forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiceCoefficient.js
More file actions
Latest commit
50 lines (39 loc) · 1.61 KB
/
Copy pathDiceCoefficient.js
File metadata and controls
50 lines (39 loc) · 1.61 KB
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
/* The Sørensen–Dice coefficient is a statistic used to gauge the similarity of two samples.
* Applied to strings, it can give you a value between 0 and 1 (included) which tells you how similar they are.
* Dice coefficient is calculated by comparing the bigrams of both strings,
* a bigram is a substring of the string of length 2.
* read more: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
*/
// Time complexity: O(m + n), m and n being the sizes of string A and string B
// Find the bistrings of a string and return a hashmap (key => bistring, value => count)
functionmapBigrams(string){
constbigrams=newMap()
for(leti=0;i<string.length-1;i++){
constbigram=string.substring(i,i+2)
constcount=bigrams.get(bigram)
bigrams.set(bigram,(count||0)+1)
}
returnbigrams
}
// Calculate the number of common bigrams between a map of bigrams and a string
functioncountCommonBigrams(bigrams,string){
letcount=0
for(leti=0;i<string.length-1;i++){
constbigram=string.substring(i,i+2)
if(bigrams.has(bigram))count++
}
returncount
}
// Calculate Dice coeff of 2 strings
functiondiceCoefficient(stringA,stringB){
if(stringA===stringB)return1
elseif(stringA.length<2||stringB.length<2)return0
constbigramsA=mapBigrams(stringA)
constlengthA=stringA.length-1
constlengthB=stringB.length-1
letdice=(2*countCommonBigrams(bigramsA,stringB))/(lengthA+lengthB)
// cut 0.xxxxxx to 0.xx for simplicity
dice=Math.floor(dice*100)/100
returndice
}
export{diceCoefficient}