Monday, March 20, 2023

Coding Challenge #27

// Daily Coding Challenge #31
// calculate the edit distance between two strings
// the edit distance is calculated by how many characters additions, deletions, and substitutions take place in order to get to the new word.
// Example: 'kitten' -> 'sitting' = 3 (k->s, e->i, add g)
// Example: 'round' -> 'pound' = 1 (r->p)
function calcEditDistance(str1, str2){
    // we're using str1 as the starting point, and calculating changes to get to string 2
    var edist = Math.abs(str1.length - str2.length);
    for(var xint = 0, len = Math.min(str1.length,str2.length); xint < len;xint++){
        if(str1.charAt(xint) != str2.charAt(xint)) edist++;
    }
    return edist;
}


function test(str1, str2, expected_output){
    var s = "Testing '" + str1 + "' against '" + str2 + "'. Was it the expected " + expected_output + "? ";
    if(calcEditDistance(str1, str2) == expected_output){
        s += "YES, PASS";
    }else{
        s += "NO, FAIL";
    }
    console.log(s);
}

// test (str1, str2, expected output)
test('hi there', 'hi theory', 3); // should PASS
test('pear', 'bear', 1); // should PASS
test('pear', 'boar', 1); // should FAIL
test('doodle', 'doodle', 0); // should PASS

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...