function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dinesh RDinesh 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 

any one know about that
SafiyaSafiya
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 RDinesh R
Hi blackperl

Thanks your help.
While running this code I am getting error on CPU time limit exception 

thanks
SafiyaSafiya
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++)
        cost.add(i);
    for(integer j = 1; j< len1; j++) {
        newcost.add(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
            	newcost.add(Math.min(Math.min(cost_replace,cost_delete),cost_replace));
        }
        list<integer> swap = new list<Integer>();
        swap.addAll(cost);
        cost = new List<Integer>();
        cost.addAll(newcost);
        newcost = new list<integer>();
        newcost.addall(swap);
    }
    integer bigger = Math.max(s.length(),t.length());
    system.debug(cost[len0 - 1]);
    Double perentage = (double.valueOf(bigger)-double.valueOf(cost[len0 - 1])) * 100 /double.valueOf(bigger);
    return perentage;
}

System.debug(levenshteinDistance('12345','12345678'));

 
SafiyaSafiya
let me know whether the above code helped you or not