Skip to content

Instantly share code, notes, and snippets.

@tyage
Created January 5, 2015 05:49
Show Gist options
  • Select an option

  • Save tyage/98d39cfa97999815a571 to your computer and use it in GitHub Desktop.

Select an option

Save tyage/98d39cfa97999815a571 to your computer and use it in GitHub Desktop.
let distance = (str1, str2) => {
let distanceTable = []
for (let i = 0; i <= str1.length; ++i) {
distanceTable[i] = []
for (let j = 0; j <= str2.length; ++j) {
distanceTable[i][j] = -1
}
}
for (let i = 0; i <= str1.length; ++i) {
distanceTable[i][0] = i
}
for (let i = 0; i <= str2.length; ++i) {
distanceTable[0][i] = i
}
for (let i = 1; i <= str1.length; ++i) {
for (let j = 1; j <= str2.length; ++j) {
let cost = (str1[i - 1] === str2[j - 1] ? 0 : 1)
distanceTable[i][j] = Math.min(
distanceTable[i - 1][j] + 1,
distanceTable[i][j - 1] + 1,
distanceTable[i - 1][j - 1] + cost
)
}
}
return distanceTable[str1.length][str2.length]
}
console.log(distance("abcde", "cd"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment