ruby edit_distance.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby edit_distance.rb相关的知识,希望对你有一定的参考价值。

# An edit distance (e.d.) is defined as how many times you need to replace, add, or remove characters to match two strings.
# E.G. "train" and "brain" have e.d.=1
# "train" and "rain" have e.d.=1
# "train" and "trains" have e.d.=1
# Write a method that returns TRUE if edit distance is exactly 1, FALSE if not.
# Author: Murat Ayfer

def edit_distance_is_one(word1, word2)

    i1 = 0
    i2 = 0

    distance = 0

    while i1 < word1.length && i2 < word2.length
        if word1[i1] != word2[i2]
            distance += 1
            if word1.length > word2.length
                i1 += 1
            elsif word2.length > word1.length
                i2 += 1
            else
                i1 += 1
                i2 += 1
            end
        else
            i1 += 1
            i2 += 1
        end
    end

    distance == 1
end


def edit_distance_is_one(word1, word2)
    long = word1.length >= word2.length ? word1 : word2
    short = word2.length <= word1.length ? word2 : word1

    i = 0
    distance = 0

    while i < short.length
        if long[i] != short[i]
            distance += 1
            if long.length > short.length
                long.slice!(i)
            end
        end
        i += 1
    end

    distance == 1
end


puts edit_distance_is_one("train", "brain") == true
puts edit_distance_is_one("train", "rain") == true
puts edit_distance_is_one("rain", "brain") == true
puts edit_distance_is_one("murat", "brain") == false
puts edit_distance_is_one("murat", "murattt") == false
puts edit_distance_is_one("murat", "murrrat") == false

以上是关于ruby edit_distance.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee