## Jaro–Winkler Similarity – How to correctly count the number of transpositions

Jaro–Winkler Similarity is a widely used similarity measure for checking the similarity between two strings. Being a similarity measure (not a distance measure), a higher value means more similar strings.

You can read on basics and how it works on Wikipedia. It’s available in many places and I’m not going into that. However, none of these sites talks about how to correctly count the number of transpositions in complex situations.

Transposition is defined as “matches which are not in the same position”. For a simple example like ‘c**ar**t’ vs ‘c**ra**tec’ it is obvious with 4 matches and 2 transpositions (r and a in not in the same position). But for ‘x**abcd**xxxxxx’ vs ‘y**a**y**b**y**c**y**d**yyyyyy’ in the first look, all letters seems to be out of position but there are **no transpositions** (4 matches). For very similar ‘x**abcd**xxxxxx’ vs ‘y**d**y**a**y**b**y**c**yyyyyy’, there are **4 transpositions **(4 matches). With these examples, it might not be trivial to count the number of transpositions.

The main reason behind this complexity is we are looking at the whole word whereas we should be looking only at the matched part.

Ex: ‘x**abcd**xxxxxx’, ‘y**a**y**b**y**c**y**d**yyyyyy’ (get the matching letters and write it down)

- ‘x
**abcd**xxxxxx’:**abcd**‘ - y
**a**y**b**y**c**y**d**yyyyyy’:**abcd**

Now it’s clear that there are no transpositions

- ‘x
**abcd**xxxxxx’:**abcd** - ‘ y
**d**y**a**y**b**y**c**yyyyyy’:**dabc**

After extracting the matching letters, you can see each letter can be given an index. In the first word a-0, b-1, c-2, d-4. In the second word d-0, a-1, b-2, c-3. What you must check is how many of the matches are not having the same index. In this case, none of the matching letters has the same index. So, there are **4 **transpositions. Once you understand this, it’s very trivial.

You can find code for Jaro-Winkler here: https://rosettacode.org/wiki/Jaro_distance. You can use it to check if your calculations are correct.