// ------------------------------------------------------ // Using Directives // ------------------------------------------------------ using System.Collections.Generic; using System.IO; using System; // ------------------------------------------------------ // Palindrome // ------------------------------------------------------ public class Palindrome { // ------------------------------------------------------ // GetWords - Returns false if 'fileName' could not be // read and populates 'errMsg', returns true // otherwise and populates 'words' // ------------------------------------------------------ public static bool GetWords( string fileName, out string[] words, out string errMsg ) { words = null; errMsg = null; try { words = File.ReadAllLines(fileName); } catch(Exception e) { errMsg = e.Message; return(false); } return(true); } // ------------------------------------------------------ // ArePalindrome - Returns true if word1 + word2 makes // a palindrome, false otherwise // ------------------------------------------------------ public static bool ArePalindrome(string word1, string word2) { if(string.IsNullOrEmpty(word1) || string.IsNullOrEmpty(word2)) return(false); string s1 = word1; string s2 = word2; int n1 = word1.Length; int n2 = word2.Length; int index1 = 0; int index2 = n2 - 1; for(int i = 0, n = (n1 + n2) / 2; i < n; i ++) { if(s1[index1] != s2[index2]) return(false); if(++index1 == n1) { s1 = word2; index1 = 0; } if(--index2 < 0) { s2 = word1; index2 = n1 - 1; } } return(true); } // ------------------------------------------------------ // ShowWords - Output the contents of 'words' // to the console // ------------------------------------------------------ public static void ShowWords(string[] words) { foreach(string word in words) Console.WriteLine("'{0}'", word); } // ------------------------------------------------------ // Main // ------------------------------------------------------ public static void Main() { string errMsg; string[] words; if(!GetWords("words.txt", out words, out errMsg)) { Console.WriteLine(errMsg); } else { //ShowWords(words); for(int i = 0; i < words.Length; i ++) { for(int j = 0; j < words.Length; j ++) { if(i != j) { if(ArePalindrome(words[i], words[j])) Console.WriteLine("'{0}' + '{1}'", words[i], words[j]); } } } } Console.Read(); } }