Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
Dinesh R

# Levenshtein logic

Levenshtein percentage calculation logic ,
I want to compare
Account Number: 123456
Account Number: 123456
based on the match I want to percentage result

Safiya
try with this

String string1 = '123456';
String string2 = '12345';
Double bigger = Math.max(string1.length(), string2.length());
Double distance = levenshteinDistance(string1,string2);
Double percentage = (bigger - distance) * 100 /bigger;

public integer levenshteinDistance ( String s, String t) {

if (s.length() == 0) return t.length();
if (t.length() == 0) return s.length();

return Math.min(Math.min(
levenshteinDistance(s.substring(1), t) + 1,
levenshteinDistance(t.substring(1), s) + 1),
levenshteinDistance(s.substring(1), t.substring(1)) + (s.charAt(0) != t.charAt(0) ? 1 : 0)
);
}
Dinesh R
Hi blackperl

While running this code I am getting error on CPU time limit exception

thanks
Safiya
Hi Dinesh,

Yea recurtion will not play well in salesforce, so here is a code without recurtion.
```public double levenshteinDistance(String s, String t) {
Integer len0 = s.length() + 1;
integer len1 = t.length() + 1;
list<integer> cost = new list<integer>();
List<Integer> newcost = new list<Integer>();
for(Integer i = 0; i < len0; i++)
for(integer j = 1; j< len1; j++) {
for(Integer i = 1; i< len0; i++) {
integer match = (s.charAt(i-1) == t.charat(j-1)) ? 0 : 1;
Integer cost_replace = cost[i-1] + match;
Integer cost_insert = cost[i] + 1;
Integer cost_delete = newcost[i - 1] + 1;
if(newcost.size() > i )
newcost[i] = Math.min(Math.min(cost_replace,cost_delete),cost_replace);
else
}
list<integer> swap = new list<Integer>();
cost = new List<Integer>();
newcost = new list<integer>();