Search code examples
arrayscpalindromefunction-definition

How to identify an embedded palindrome within an array of digits


Say we have

int arr1[]={1,2,3,4,5};
int temp1[], temp2[];

and that we need to copy the first 3 members from arr1 to temp1, and the second 3 from arr1 to temp2, so that

temp1={1,2,3};
temp2={2,3,4};

and so on and so forth, how would you go on about doing it? I am trying to write a program to check if a user inputted number contains a palindrome in a length k (where k is also chosen by the user) and my idea was to store the number in an array, take the first 3 members, put them in an array, reverse them and put that in another array and then compare, but I am stuck on how to solve the problem I mentioned above, I tried something like:

void copyandReverse(int arr[], int copy[], int reverse[], int start, int length)
{
    for(int i=0; i<length; i++)
    {
        copy[start+i]=arr[start+i];
        reverse[start+i]=arr[start+length-i-1];

    }
}

but it seems to only copy the first 3 elements, and reverse them.

PS: I don't think we're allowed to use string or dynamic memory allocation, it's given that the inputted number contains less then 10 digits, so I made the temporary arrays with a constant size 10.


Solution

  • There is no any need to create auxiliary arrays to check whether a given array is a palindrome.

    This can be done much simpler.

    Write a function like this

    int is_palindrome( const unsigned int a[], size_t n )
    {
        size_t i = 0;
    
        while (i < n / 2 && a[i] == a[n - i - 1]) ++i;
    
        return i == n / 2;
    }
    

    then in main if you have an array like

    unsigned int a[10];
    

    and you need to check whether a sub-array with three elements is a palindrome then you can do this in a for loop

    size_t k = 3;
    
    for ( size_t i = 0; i <= 10 - k; i++ )
    {
        if ( is_palindrome( a + i, k ) ) 
        {
            printf( "The sub-array at position %zu:", i );
            for ( size_t j = i; j < k + i; j++ ) printf( " %u", a[j] );
            puts( " is a palindrome" );
        }
    }