-1

The Problem:-
enter image description here

So, i have taken the second string along the row and the first string along the columns-I am getting the wrong answer because of this. But i dont understand how and why??
also, for some value(i.e "table" and "bal") i am getting segmentation fault.


#include <vector>
#include <string>
#include <iostream>
using namespace std;

void print(vector<vector<int>> &table)
{
    for(int i = 0; i < table.size(); ++i)
    {
        for(int j = 0; j < table[0].size(); ++j)
            cout << table[i][j] << " ";
        cout << endl;
    }
}
int levenshteinDistance(string a, string b) 
{
    int r = b.size() + 1;
    int c = a.size() + 1;
    vector<vector<int>> table(r, vector<int>(c, 0));
    for(int i = 0; i < r; ++i)
        table[i][0] = i;
    for(int j = 0; j < c; ++j)
        table[0][j] = j;
    
    for(int i = 1; i < r; ++i)
    {
        for(int j = 1; j < c; ++j)
        {
            
            if(a[j - 1] != b[i - 1])
            {
                table[i][j] = 1 + min(table[i - 1][j - 1], 
                                                min(table[j - 1][i], table[i - 1][j]));
            }
            else
                table[i][j] = table[i - 1][j - 1];
            
        }
        
    }

    print(table);
  return table[r-1][c-1];
}
user21692
  • 21
  • 6

1 Answers1

0

No it does not matter in which way you define the matrix, as long as you access it appropriately in the nested loops afterwards.

In your case you access them here:

table[i][j] = 1 + min(table[i - 1][j - 1], min(table[j - 1][i], table[i - 1][j]));

in your case i is the index for the first dimension of the matrix, while j is the index for the second dimension. So the access table[j - 1][i] should be table[i][j - 1]. This caused a segmentation fault, since you accessed elements outside of the vectors.

maxbachmann
  • 2,862
  • 1
  • 11
  • 35