I have the following program which returns true (1) or false (0) depending on whether the array passed as a parameter is a palindrome or a concatenation of two arrays, both of which are palindromes as well:
#include <iostream>
using namespace std;
bool palindrome(int arr[], int n)
{
int flag = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
counter++;
if (counter == (n/2))
flag = 1;
}
}
}
if (flag != 1)
return false;
else
return true;
}
int main()
{
int arr[] = { 1, 2, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << palindrome(arr, n) <<endl;
return 0;
}
If I use a single palindrome like 1, 2, 3, 2, 1 or 1, 2, 3, 3, 2, 1 I'm getting true and it's working the way it should. If my array however is a concatenated it's not always working properly. For example, if I use 1, 2, 3, 2, 1, 5, 6, 6, 5, I will get true (1) as a result. But with 1, 2, 3, 2, 1, 5, 6, 7, 6, 5 I get false (0) although both parts of the array are palindromes. Or with 1, 2, 3, 3, 1, 5, 6, 6, 5 I get true (1) although the first part doesn't contain a palindrome.
How to make my program display correct result every time and detect if both parts of the array are palindromes? Any help is appreciated.