Write a program (written in C language NOT C++) that will read two sequences of
ID: 3764331 • Letter: W
Question
Write a program (written in C language NOT C++) that will read two sequences of characters (two c-strings) from a file (named input.txt) and print the matched leading characters of these two sequences on the screen. Space(s) or new line (s) separates these two sequences (You can assume that there are no spaces or new lines before the first sequence and after the second sequence). One sequence of characters may contain letters, numbers, and punctuations. Each sequence has no more than 20 characters. For example, if the first sequence is “Apple”, and the second sequence is “Application”, the program should print “Appl” on the screen. You should write a function to compare these two sequences. The return value of the function should be the location of the last same character in the sequence, e.g., 3 in the above example. *Your program should be able to handle the case when one sequence has more than 20 characters. You may just skip the extra characters in each sequence.
Explanation / Answer
#include <stdio.h>
int main()
{
int i = 0;
int BUFSIZE = 1000;
char* words[20];
FILE *fp = fopen("input.txt", "r");
if (fp == 0){
fprintf(stderr, "Error while opening");
return 0;
}
words[i] = (char*)malloc(BUFSIZE);
words2[i] = (char*)malloc(BUFSIZE);
while (fgets(words[i], BUFSIZE, fp)) {
i++;
words[i] = (char*)malloc(BUFSIZE);
if(words[i] == ' ')
return;
}
// reset i back to zero
i = 0;
while (fgets(words2[i], BUFSIZE, fp)) {
i++;
words2[i] = (char*)malloc(BUFSIZE);
}
printf("Output: ");
srand(time(NULL));
int j = rand()%i;
int k = (j+1)%i;
fflush(stdout);
printf("%d - %s %d -%s", j, words[j], k, words[k]);
int x;
for(x = 0; x<i; x++){
free(words[x]);
free(words2[x]);
}
scanf("%d", x);
fclose(fp);
LongestCommenSubstring(words, words2);
return 0;
}
void LongestCommenSubstring(std::string str1, std::string str2)
{
const int m = str1.length();
const int n = str2.length();
int lcs[m][n];
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n;++j)
{
lcs[i][j] = 0;
}
}
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n;++j)
{
if(str1[i] == str2[j])
{
if((i-1 >= 0 ) && ( j-1 >= 0))
{
if(str1[i-1] == str2[j-1])
{
lcs[i][j] = lcs[i-1][j-1]+1;
}
}
}
else
{
if((i-1 >= 0 ) &&( j-1 >= 0))
{
lcs[i][j] = std::max(lcs[i][j-1], lcs[i-1][j]);
}
}
}
}
std::cout << "longest commen substring" << lcs[m-1][n-1];}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.