(I have simplified my code after reading advice)
I am writing a program to take 2 strings and return the smallest editing distance as int.
eg. str1 = ab, str2 = ab ; //distance will be 0.
(when both char of str1 and str2 are the same, distance will be 0)
eg. str1 = abc, str2 = c ; distance will be 2.
In my code,I have used below strings.
str1 = editing
str2 = distance
correct answer should be 5 (e, s, i&a, g&c, e), but my program returns 6. I have tried other strings eg, (short & ports) which gives the answer what it is supposed to be.
I have tried to debug, but I do not understand why sometimes those 3 options (ans1, ans2, ans3) in the function "check" give correct outcome, sometimes they dont.
ans1 is the result when index of str1 +1
ans2 is the result when index of str2 +1
ans3 is the result when index of both str1 and str2 +1
I have read my code many times and I cant find what went wrong. please help me to understand my problems.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check(const char* str1, const char* str2, int i, int j, int dp[10][10])
{
int steps = 0;
while (str1[i] != '\0' || str2[j] != '\0')
{ //while one side has not reach '\0'
while (str1[i] != '\0' && str2[j] != '\0')
{ //while both sides has not reach '\0'
if (dp[i][j] != -1){ return dp[i][j];} //if there is stored answer, return that
if (str1[i] == str2[j])
{ // if both char are the same, both move forward
i++;
j++;
}
else //if both char are not the same
{
int ans1 = check(str1, str2, i+1, j, dp); //ans1 = when str1 move forward
int ans2 = check(str1, str2, i, j+1, dp); //ans2 = when str2 move forward
int ans3 = check(str1, str2, i+1, j+1, dp);//ans3 = when both move forward
//compare the result below to find the smallest steps(distance)
if (ans1 <= ans2)
{ //ans1 is smaller than ans2
if (ans1 <= ans3)
{ //ans1 is smallest
dp[i][j] = ans1 + 1; //store the answer to dp array
i++; //move forward
steps++; //steps +1
}
else //ans3 is smallest
{
dp[i][j] = ans3 + 1;
i++;
j++;
steps++;
}
}
else //ans2 is smaller than ans1
{
if (ans2 <= ans3)
{ //ans2 is smallest
dp[i][j] = ans2 + 1;
j++;
steps++;
}
else //ans3 is smallest
{
dp[i][j] = ans3 + 1;
i++;
j++;
steps++;
}
}
}//else ends here
}//while loop ends (both sides are not \0)
//when str1 or str2 reaches the end '\0'
if (str1[i] != '\0')
{
i++;
steps++;
}
else if (str2[j] != '\0')
{
j++;
steps++;
}
}//while loop ends(one side is not \0)
//printf("i=%d\nj=%d\nsteps=%d\n", i, j, steps);
return steps;
}//function ends here
int main() {
char str1[10] = "editing";
char str2[10] = "distance";
int min_step[10][10]; //with index [i][j]
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
min_step[i][j] = -1;
//scanf("%s %s", str1, str2);
printf("%d\n", check(str1, str2, 0, 0, min_step));
return 0;
}