Skip to content

Instantly share code, notes, and snippets.

@alistairstead3408
Created November 26, 2014 11:56
Show Gist options
  • Save alistairstead3408/2017fac04f33cc0d663e to your computer and use it in GitHub Desktop.
Save alistairstead3408/2017fac04f33cc0d663e to your computer and use it in GitHub Desktop.
#Takes two character vectors
lev_dist_better <- function(s, t){
if(identical(s, t)) return(0)
if(length(s) == 0) return(length(t))
if(length(t) == 0) return(length(s))
#initialise v0 with a sequence from 0 to length of t + 1
previous <- seq(1, length(t) + 1, 1)
current <- c(rep(0, length(t) + 1))
for(i in 1:length(s)){
current[1] <- i +1
for(j in 1:length(t)){
cost <- ifelse(s[i] == t[j], 0, 1)
current[j + 1] = min(current[j] + 1, previous[j+1] + 1, previous[j] + cost)
}
for(j in 1:length(previous))
previous[j] = current[j]
}
return(current[length(t)+1]-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment