You have error in the increment; it should be ++index
instead of index++
:
return Rowpalindrome(arr, ++index);
you should increment and pass modified value of index
(++index
), not increment and pass initial value (index++
). Even better implementation is to put it simple:
return Rowpalindrome(arr, index + 1);
Edit: You have some logical errors as well (thanks to Fildor who's pointed it out): the condition should be
if (arr.Length <= 1 || index > arr.Length % 2 + 1)
return true;
The final recoursive code can be
static bool Rowpalindrome(char[] arr, int index) {
if (arr.Length <= 1 || index > arr.Length % 2 + 1)
return true;
// Let's get rid of "i" (which is index) and exploit short circuit of &&:
// .Net tests arr[index] != arr[(arr.Length - index - 1)]
// and only if it's true call for Rowpalindrome(arr, index + 1)
return arr[index] != arr[(arr.Length - index - 1)] && Rowpalindrome(arr, index + 1);
}
Test cases: (Let's use Linq to query for each test)
using System.Linq;
...
var tests = new char[][] {
new char[] { },
new char[] { 'a' },
new char[] { 'a', 'a' },
new char[] { 'a', 'b' },
new char[] { 'a', 'b', 'a' },
new char[] { 'a', 'b', 'c' },
new char[] { 'a', 'b', 'b', 'a' },
new char[] { 'a', 'b', 'c', 'a' },
new char[] { 'a', 'b', 'b', 'c' },
};
var result = tests
.Select(test => $"{"[" +string.Join(", ", test) + "]", -15} : {(Rowpalindrome(test, 0) ? "Palindrome" : "Not")}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
[] : Palindrome
[a] : Palindrome
[a, a] : Palindrome
[a, b] : Not
[a, b, a] : Palindrome
[a, b, c] : Not
[a, b, b, a] : Palindrome
[a, b, c, a] : Not
[a, b, b, c] : Not
Edit 2: In case of multidimensional array (see comments below) you can extract column of interest into an array and run the routine, e.g. for 2D
array:
char[,] c = new char[,] {
{ 'a', 'b', 'c'},
{ 'x', 'y', 'z'},
{ 'x', 'p', 'q'},
{ 'a', 'm', 'n'},
};
int colIndex = 0; // should be {'a', 'x', 'x', 'a'} column
// c.GetLength(0) - number of lines (length of the 1st dimension) - 4
char[] a = new char[c.GetLength(0)];
for (int i = 0; i < a.Length; ++i)
a[i] = c[i, colIndex];
bool result = Rowpalindrome(a, 0);