|
| 1 | +require "test/unit" |
| 2 | + |
| 3 | +def editDistDP(str1, str2, m, n) |
| 4 | + rows, cols = m+1,n+1 |
| 5 | + |
| 6 | + # Create a 2D array to store results of subproblems |
| 7 | + dp = Array.new(rows) { Array.new(cols) } |
| 8 | + |
| 9 | + #using bottom up approach |
| 10 | + for i in (0..m + 1-1) do |
| 11 | + for j in (0..n + 1-1) do |
| 12 | + |
| 13 | + #If the first string is empty, insert all the characters of the second string |
| 14 | + if i == 0 |
| 15 | + dp[i][j] = j |
| 16 | + |
| 17 | + #If the second string is empty, insert all the characters of the first string |
| 18 | + elsif j == 0 |
| 19 | + dp[i][j] = i |
| 20 | + |
| 21 | + #If the last character in both the strings are same, we can ignore the character and move to the next character in both the strings |
| 22 | + elsif str1[i-1] == str2[j-1] |
| 23 | + dp[i][j] = dp[i-1][j-1] |
| 24 | + |
| 25 | + #If the last character of both the strings are different, find out the minimum value of the three operations(insert, delete, replace) |
| 26 | + else |
| 27 | + dp[i][j] = 1 +[dp[i][j-1],dp[i-1][j],dp[i-1][j-1]].min() |
| 28 | + |
| 29 | + end |
| 30 | + |
| 31 | + end |
| 32 | + |
| 33 | + end |
| 34 | + |
| 35 | + return dp[m][n] |
| 36 | +end |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +class Editdistancetest < Test::Unit::TestCase |
| 42 | + |
| 43 | + #Test1 |
| 44 | + #Replace 'n' with 'r' |
| 45 | + #insert 'a' |
| 46 | + #insert 't' |
| 47 | + #No of total operations : 3 |
| 48 | + def test_distance1 |
| 49 | + assert_equal 3, editDistDP( "sunday","saturday",6,8), "Should return 3" |
| 50 | + end |
| 51 | + |
| 52 | + #Test2 |
| 53 | + #Replace 'a' with 'u' |
| 54 | + #No of total operations : 1 |
| 55 | + def test_distance2 |
| 56 | + assert_equal 1, editDistDP("cat","cut",3,3), "editDistDpShould return 1" |
| 57 | + end |
| 58 | + |
| 59 | + #Test3 |
| 60 | + #Insert 'a','p', 'p','l','e','p','i','e' into string 1 |
| 61 | + #No of total operations : 8 |
| 62 | + def test_distance3 |
| 63 | + assert_equal 8, editDistDP("","applepie",0,8), "editDistDpShould return 1" |
| 64 | + end |
| 65 | + |
| 66 | + #Test4 |
| 67 | + #Both the strings are equal, thus no operation needed |
| 68 | + #No of total operations : 0 |
| 69 | + def test_distance4 |
| 70 | + assert_equal 0, editDistDP("Hello","Hello",5,5), "editDistDpShould return 1" |
| 71 | + end |
| 72 | + |
| 73 | + end |
| 74 | + |
0 commit comments