Common sub-string in alphabetic order











up vote
0
down vote

favorite












I'm trying to write a code that gets two strings of maximum length 1000 uppercase characters and then prints their longest common sub-string BUT if there were more than one sub-strings of the maximum length the output must be the sub-string that comes first in the alphabetic order .
example:
input:DEFTABC,DEFHABC
output:ABC
Here's my code that I wrote but the problem of this code is that for above inputs it gives "DEF" instead of "ABC",please help me correct my code.



#include<stdio.h>
#include<string.h>
int chart[1002][1002];
void commonsubstring(char str1,char str2,int m,int n){
int len=0;
int row,col,i,j;
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
if(i==0 || j==0){
chart[i][j]=0;
}
else if(str1[i-1]==str2[j-1]){
chart[i][j]=chart[i-1][j-1]+1;
if(len<chart[i][j]){
len=chart[i][j];
row=i;
col=j;
}
}
else{
chart[i][j]=0;
}
}
}
if(len==0){
return;
}
char result[1001];
while(chart[row][col]!=0){
result[--len]=str1[row-1];
row--;
col--;
}
puts(result);
}
int main(){
char str1[1001],str2[1001];
gets(str1);
gets(str2);
int m,n;
m=strlen(str1);
n=strlen(str2);
commonsubstring(str1,str2,m,n);
return 0;
}









share|improve this question






















  • Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
    – Jonathan Leffler
    Nov 22 at 14:28






  • 1




    Incidentally, see Why gets() is too dangerous to be used — ever!
    – Jonathan Leffler
    Nov 22 at 14:29










  • Yes this code works!
    – b.j
    Nov 22 at 14:33






  • 1




    If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
    – Jonathan Leffler
    Nov 22 at 14:39










  • SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
    – jdv
    Nov 22 at 16:50















up vote
0
down vote

favorite












I'm trying to write a code that gets two strings of maximum length 1000 uppercase characters and then prints their longest common sub-string BUT if there were more than one sub-strings of the maximum length the output must be the sub-string that comes first in the alphabetic order .
example:
input:DEFTABC,DEFHABC
output:ABC
Here's my code that I wrote but the problem of this code is that for above inputs it gives "DEF" instead of "ABC",please help me correct my code.



#include<stdio.h>
#include<string.h>
int chart[1002][1002];
void commonsubstring(char str1,char str2,int m,int n){
int len=0;
int row,col,i,j;
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
if(i==0 || j==0){
chart[i][j]=0;
}
else if(str1[i-1]==str2[j-1]){
chart[i][j]=chart[i-1][j-1]+1;
if(len<chart[i][j]){
len=chart[i][j];
row=i;
col=j;
}
}
else{
chart[i][j]=0;
}
}
}
if(len==0){
return;
}
char result[1001];
while(chart[row][col]!=0){
result[--len]=str1[row-1];
row--;
col--;
}
puts(result);
}
int main(){
char str1[1001],str2[1001];
gets(str1);
gets(str2);
int m,n;
m=strlen(str1);
n=strlen(str2);
commonsubstring(str1,str2,m,n);
return 0;
}









share|improve this question






















  • Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
    – Jonathan Leffler
    Nov 22 at 14:28






  • 1




    Incidentally, see Why gets() is too dangerous to be used — ever!
    – Jonathan Leffler
    Nov 22 at 14:29










  • Yes this code works!
    – b.j
    Nov 22 at 14:33






  • 1




    If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
    – Jonathan Leffler
    Nov 22 at 14:39










  • SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
    – jdv
    Nov 22 at 16:50













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to write a code that gets two strings of maximum length 1000 uppercase characters and then prints their longest common sub-string BUT if there were more than one sub-strings of the maximum length the output must be the sub-string that comes first in the alphabetic order .
example:
input:DEFTABC,DEFHABC
output:ABC
Here's my code that I wrote but the problem of this code is that for above inputs it gives "DEF" instead of "ABC",please help me correct my code.



#include<stdio.h>
#include<string.h>
int chart[1002][1002];
void commonsubstring(char str1,char str2,int m,int n){
int len=0;
int row,col,i,j;
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
if(i==0 || j==0){
chart[i][j]=0;
}
else if(str1[i-1]==str2[j-1]){
chart[i][j]=chart[i-1][j-1]+1;
if(len<chart[i][j]){
len=chart[i][j];
row=i;
col=j;
}
}
else{
chart[i][j]=0;
}
}
}
if(len==0){
return;
}
char result[1001];
while(chart[row][col]!=0){
result[--len]=str1[row-1];
row--;
col--;
}
puts(result);
}
int main(){
char str1[1001],str2[1001];
gets(str1);
gets(str2);
int m,n;
m=strlen(str1);
n=strlen(str2);
commonsubstring(str1,str2,m,n);
return 0;
}









share|improve this question













I'm trying to write a code that gets two strings of maximum length 1000 uppercase characters and then prints their longest common sub-string BUT if there were more than one sub-strings of the maximum length the output must be the sub-string that comes first in the alphabetic order .
example:
input:DEFTABC,DEFHABC
output:ABC
Here's my code that I wrote but the problem of this code is that for above inputs it gives "DEF" instead of "ABC",please help me correct my code.



#include<stdio.h>
#include<string.h>
int chart[1002][1002];
void commonsubstring(char str1,char str2,int m,int n){
int len=0;
int row,col,i,j;
for(i=0;i<=m;i++){
for(j=0;j<=n;j++){
if(i==0 || j==0){
chart[i][j]=0;
}
else if(str1[i-1]==str2[j-1]){
chart[i][j]=chart[i-1][j-1]+1;
if(len<chart[i][j]){
len=chart[i][j];
row=i;
col=j;
}
}
else{
chart[i][j]=0;
}
}
}
if(len==0){
return;
}
char result[1001];
while(chart[row][col]!=0){
result[--len]=str1[row-1];
row--;
col--;
}
puts(result);
}
int main(){
char str1[1001],str2[1001];
gets(str1);
gets(str2);
int m,n;
m=strlen(str1);
n=strlen(str2);
commonsubstring(str1,str2,m,n);
return 0;
}






c






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 13:59









b.j

66




66












  • Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
    – Jonathan Leffler
    Nov 22 at 14:28






  • 1




    Incidentally, see Why gets() is too dangerous to be used — ever!
    – Jonathan Leffler
    Nov 22 at 14:29










  • Yes this code works!
    – b.j
    Nov 22 at 14:33






  • 1




    If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
    – Jonathan Leffler
    Nov 22 at 14:39










  • SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
    – jdv
    Nov 22 at 16:50


















  • Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
    – Jonathan Leffler
    Nov 22 at 14:28






  • 1




    Incidentally, see Why gets() is too dangerous to be used — ever!
    – Jonathan Leffler
    Nov 22 at 14:29










  • Yes this code works!
    – b.j
    Nov 22 at 14:33






  • 1




    If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
    – Jonathan Leffler
    Nov 22 at 14:39










  • SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
    – jdv
    Nov 22 at 16:50
















Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
– Jonathan Leffler
Nov 22 at 14:28




Allocating close to 1 MiB of working memory in chart seems like it should be overkill; are you sure that's sensible? Could you call the function reliably on multiple different substrings?
– Jonathan Leffler
Nov 22 at 14:28




1




1




Incidentally, see Why gets() is too dangerous to be used — ever!
– Jonathan Leffler
Nov 22 at 14:29




Incidentally, see Why gets() is too dangerous to be used — ever!
– Jonathan Leffler
Nov 22 at 14:29












Yes this code works!
– b.j
Nov 22 at 14:33




Yes this code works!
– b.j
Nov 22 at 14:33




1




1




If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
– Jonathan Leffler
Nov 22 at 14:39




If the code works, why is there a question? It doesn't work correctly — it doesn't produce the correct result. You don't scan through possible results looking for the first in alphabetic order. I don't understand how your 2D array works; I'm not sure I want to since I think it is fundamentally wrong to allocate O(N²) space for this problem. However, maybe the trouble is that you don't know how to do dynamic memory allocation with malloc() (and how to release it with free()), in which case, there is an excuse for what is otherwise serious overkill.
– Jonathan Leffler
Nov 22 at 14:39












SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
– jdv
Nov 22 at 16:50




SO is not a good debugger. ericlippert.com/2014/03/05/how-to-debug-small-programs
– jdv
Nov 22 at 16:50












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










Use standard string functions to make the code less convoluted. If for some reason strcmp, strstr etc. are not available, then you can make your own functions.



You don't need an array of 1000 strings of size 1000. Just get the shorter string and find all its sub-strings. If the sub-string is found in the larger string, then make that your result. If result already exists, make sure that new match is longer than the existing result, and is lower in the alphabetic order. Example:



#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void common(char* m, char* n)
{
char *a = m;
char *b = n;
if(strlen(a) > strlen(b))
{
//make sure the shorter string is used first
a = n;
b = m;
}

int len = strlen(a);

char *substr = malloc(len + 1);
char *result = malloc(len + 1);
result[0] = 0;

for(int beg = 0; beg < len - 1; beg++)
{
for(int end = beg + 1; end < len; end++)
{
//find all substrings in "a":
strncpy(substr, a + beg, end - beg + 1);
substr[end - beg + 1] = 0;

//see if substring is in "b":
if(strstr(b, substr))
{
//we want the longest common substring
if(strlen(substr) < strlen(result))
continue;

//sort by alphabetic order
if(strlen(substr) == strlen(result))
if(strcmp(substr, result) > 0)
continue;

strcpy(result, substr);
}
}
}

printf("result = %sn", result);

free(substr);
free(result);
}

int main(void)
{
char str1[1001], str2[1001];
fgets(str1, sizeof(str1), stdin);
fgets(str2, sizeof(str2), stdin);
common(str1, str2);
return 0;
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432618%2fcommon-sub-string-in-alphabetic-order%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    Use standard string functions to make the code less convoluted. If for some reason strcmp, strstr etc. are not available, then you can make your own functions.



    You don't need an array of 1000 strings of size 1000. Just get the shorter string and find all its sub-strings. If the sub-string is found in the larger string, then make that your result. If result already exists, make sure that new match is longer than the existing result, and is lower in the alphabetic order. Example:



    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>

    void common(char* m, char* n)
    {
    char *a = m;
    char *b = n;
    if(strlen(a) > strlen(b))
    {
    //make sure the shorter string is used first
    a = n;
    b = m;
    }

    int len = strlen(a);

    char *substr = malloc(len + 1);
    char *result = malloc(len + 1);
    result[0] = 0;

    for(int beg = 0; beg < len - 1; beg++)
    {
    for(int end = beg + 1; end < len; end++)
    {
    //find all substrings in "a":
    strncpy(substr, a + beg, end - beg + 1);
    substr[end - beg + 1] = 0;

    //see if substring is in "b":
    if(strstr(b, substr))
    {
    //we want the longest common substring
    if(strlen(substr) < strlen(result))
    continue;

    //sort by alphabetic order
    if(strlen(substr) == strlen(result))
    if(strcmp(substr, result) > 0)
    continue;

    strcpy(result, substr);
    }
    }
    }

    printf("result = %sn", result);

    free(substr);
    free(result);
    }

    int main(void)
    {
    char str1[1001], str2[1001];
    fgets(str1, sizeof(str1), stdin);
    fgets(str2, sizeof(str2), stdin);
    common(str1, str2);
    return 0;
    }





    share|improve this answer

























      up vote
      0
      down vote



      accepted










      Use standard string functions to make the code less convoluted. If for some reason strcmp, strstr etc. are not available, then you can make your own functions.



      You don't need an array of 1000 strings of size 1000. Just get the shorter string and find all its sub-strings. If the sub-string is found in the larger string, then make that your result. If result already exists, make sure that new match is longer than the existing result, and is lower in the alphabetic order. Example:



      #include<stdio.h>
      #include<stdlib.h>
      #include<string.h>

      void common(char* m, char* n)
      {
      char *a = m;
      char *b = n;
      if(strlen(a) > strlen(b))
      {
      //make sure the shorter string is used first
      a = n;
      b = m;
      }

      int len = strlen(a);

      char *substr = malloc(len + 1);
      char *result = malloc(len + 1);
      result[0] = 0;

      for(int beg = 0; beg < len - 1; beg++)
      {
      for(int end = beg + 1; end < len; end++)
      {
      //find all substrings in "a":
      strncpy(substr, a + beg, end - beg + 1);
      substr[end - beg + 1] = 0;

      //see if substring is in "b":
      if(strstr(b, substr))
      {
      //we want the longest common substring
      if(strlen(substr) < strlen(result))
      continue;

      //sort by alphabetic order
      if(strlen(substr) == strlen(result))
      if(strcmp(substr, result) > 0)
      continue;

      strcpy(result, substr);
      }
      }
      }

      printf("result = %sn", result);

      free(substr);
      free(result);
      }

      int main(void)
      {
      char str1[1001], str2[1001];
      fgets(str1, sizeof(str1), stdin);
      fgets(str2, sizeof(str2), stdin);
      common(str1, str2);
      return 0;
      }





      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        Use standard string functions to make the code less convoluted. If for some reason strcmp, strstr etc. are not available, then you can make your own functions.



        You don't need an array of 1000 strings of size 1000. Just get the shorter string and find all its sub-strings. If the sub-string is found in the larger string, then make that your result. If result already exists, make sure that new match is longer than the existing result, and is lower in the alphabetic order. Example:



        #include<stdio.h>
        #include<stdlib.h>
        #include<string.h>

        void common(char* m, char* n)
        {
        char *a = m;
        char *b = n;
        if(strlen(a) > strlen(b))
        {
        //make sure the shorter string is used first
        a = n;
        b = m;
        }

        int len = strlen(a);

        char *substr = malloc(len + 1);
        char *result = malloc(len + 1);
        result[0] = 0;

        for(int beg = 0; beg < len - 1; beg++)
        {
        for(int end = beg + 1; end < len; end++)
        {
        //find all substrings in "a":
        strncpy(substr, a + beg, end - beg + 1);
        substr[end - beg + 1] = 0;

        //see if substring is in "b":
        if(strstr(b, substr))
        {
        //we want the longest common substring
        if(strlen(substr) < strlen(result))
        continue;

        //sort by alphabetic order
        if(strlen(substr) == strlen(result))
        if(strcmp(substr, result) > 0)
        continue;

        strcpy(result, substr);
        }
        }
        }

        printf("result = %sn", result);

        free(substr);
        free(result);
        }

        int main(void)
        {
        char str1[1001], str2[1001];
        fgets(str1, sizeof(str1), stdin);
        fgets(str2, sizeof(str2), stdin);
        common(str1, str2);
        return 0;
        }





        share|improve this answer












        Use standard string functions to make the code less convoluted. If for some reason strcmp, strstr etc. are not available, then you can make your own functions.



        You don't need an array of 1000 strings of size 1000. Just get the shorter string and find all its sub-strings. If the sub-string is found in the larger string, then make that your result. If result already exists, make sure that new match is longer than the existing result, and is lower in the alphabetic order. Example:



        #include<stdio.h>
        #include<stdlib.h>
        #include<string.h>

        void common(char* m, char* n)
        {
        char *a = m;
        char *b = n;
        if(strlen(a) > strlen(b))
        {
        //make sure the shorter string is used first
        a = n;
        b = m;
        }

        int len = strlen(a);

        char *substr = malloc(len + 1);
        char *result = malloc(len + 1);
        result[0] = 0;

        for(int beg = 0; beg < len - 1; beg++)
        {
        for(int end = beg + 1; end < len; end++)
        {
        //find all substrings in "a":
        strncpy(substr, a + beg, end - beg + 1);
        substr[end - beg + 1] = 0;

        //see if substring is in "b":
        if(strstr(b, substr))
        {
        //we want the longest common substring
        if(strlen(substr) < strlen(result))
        continue;

        //sort by alphabetic order
        if(strlen(substr) == strlen(result))
        if(strcmp(substr, result) > 0)
        continue;

        strcpy(result, substr);
        }
        }
        }

        printf("result = %sn", result);

        free(substr);
        free(result);
        }

        int main(void)
        {
        char str1[1001], str2[1001];
        fgets(str1, sizeof(str1), stdin);
        fgets(str2, sizeof(str2), stdin);
        common(str1, str2);
        return 0;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 23:26









        Barmak Shemirani

        20.5k42044




        20.5k42044






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432618%2fcommon-sub-string-in-alphabetic-order%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Trompette piccolo

            Slow SSRS Report in dynamic grouping and multiple parameters

            Simon Yates (cyclisme)