Problem 7-2

CSharp · Console

/Program.cs

// Implement a function that checks whether given array is a palindrome
// (i.e. array reversal gives the same array).
using System;

public class Program
{
	// a is non-empty and the program stops because subarray decreases
    public static bool IsPalindrome(int [] a)
    {
		return IsPalindrome(a, 0, a.Length);
    }
	
	// Returns true if a[start .. start+length-1] is a palindrome
	public static bool IsPalindrome(int [] a, int start, int length)
    {
		// length >= 0 and decreases by 2 on each nested call
		return length < 2 || (a[start]==a[start+length-1] && IsPalindrome(a, start+1, length-2));
    }
	public static void Main(string[] args)
    {
        TestArray( new int [0]);
		TestArray( new int [] { 5});
		TestArray( new int [] { 3, 3});
		TestArray( new int [] { 3, 0, 3});
        TestArray( new int [] { 1, 4, 5, 7, 8, 8, 7, 5, 4, 1});
        TestArray( new int [] { 0, 3, 5, 6, 6, 7, 3, 0, 8, 8});
    }
		
    public static void TestArray(int[] a)
    {
		Console.Write(string.Join(" ", a));
		Console.WriteLine(IsPalindrome(a) ? " is a palindrome" : " is not a palindrome");
    }

}
;