Search code examples
carraysnested-loops

is a given array a sub sequence of another array


building a code that will check if a group of numbers in s_array[] is a sub-sequence of array[], that means that { 1, 5, 4 } is not a sub-sequence of array, whereas { 1, 4, 5} is one (order matters)

my code will first check if the first element of s_array[] exists in array[], once a common element is found it will proceed to check if the rest of s_array[]'s elements also exist in array[] and in the same order (other elements can be between them)

#include <stdio.h>
void main(){
    int s_array[] = { 5, 7, 13 };
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
    int i, Bcount, m, counter = 1, j = 4;
    //i, Bcount and m are loop counters
    //counter will count number of repeated elements
    //j is the number of elements in s_array + 1

    for( i = 0; i <= 15; i++ ){
        if( s_array[0] == array[i] ){ // does the first element exist?
            for( Bcount = 1; Bcount < j; Bcount++ ){ //checking the rest 
                for( m = i; m < 15; m++){
                    if( s_array[Bcount] == array[m] ){
                        counter++;
                        i = m;
                        break;
                    }
                }

            }
        }
        if( j == counter ){
               printf( "B is a sub-sequence of A.\n" );
               break;
        }
        else{
               printf( "B is not a sub-sequence of A.\n" );
               break;
        }
    }
}

and honestly I can't see if it is the algorithm or that I did something wrong with the coding


Solution

  • First of all the first loop is wrong as i goes up to 15 and at this index you access array out of bounds (undefined behavior).

    Then the loop is quite simple. You only need

    • one loop i index for array and si for s_array
    • only increment si if you find the number array[i] at s_array[si]
    • stop the loop if i covered array, or if si got the number of sub array elements (3)
    • if si is at least 3, the sub sequence was found

    That is

    int s_array[] = { 5, 7, 13 };
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
    
     int si,i;
     for (si=0,i=0 ; i<15 && si<3 ; i++) {
        if (s_array[si] == array[i]) si++;
     }
    
     printf ("Sub was %s\n", si<3 ? "not found":"found");