Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- public class Program
- {
- public static void Main()
- {
- foreach (var test in GetTestCases()) {
- var result = IsAnagramPair(test.First, test.Second);
- Console.WriteLine((result == test.Expected) ? "Success" : "FAIL");
- }
- }
- // Assumptions:
- // Word or phrase only uses English alphabet.
- // Test cases don't pass in null for first and second.
- public static bool IsAnagramPair(string first, string second)
- {
- var firstPhrase = RemoveNonAlphabeticCharacter(first);
- var secondPhrase = RemoveNonAlphabeticCharacter(second);
- if(string.IsNullOrEmpty(firstPhrase) || string.IsNullOrEmpty(secondPhrase) || firstPhrase.Length != secondPhrase.Length){
- return false;
- }
- var firstPhraseSorted = SortLetter(firstPhrase.ToLower());
- var secondPhraseSorted = SortLetter(secondPhrase.ToLower());
- return firstPhraseSorted == secondPhraseSorted;
- }
- public static string RemoveNonAlphabeticCharacter(string phrase) {
- return Regex.Replace(phrase, @"[^a-z]", "", RegexOptions.IgnoreCase);
- }
- public static string SortLetter(string phrase){
- var letters = phrase.ToCharArray();
- Array.Sort(letters);
- return new String(letters);
- }
- public static IEnumerable<TestCase> GetTestCases()
- {
- yield return new TestCase { First = "add", Second = "dad", Expected = true };
- yield return new TestCase { First = "aad", Second = "dad", Expected = false };
- yield return new TestCase { First = "Astronomer", Second = "Moon starer", Expected = true };
- yield return new TestCase { First = "thorough", Second = "through", Expected = false };
- yield return new TestCase { First = "Jim Morrison", Second = "Mr. Mojo Risin'", Expected = true };
- yield return new TestCase { First = "", Second = "", Expected = false };
- yield return new TestCase { First = " ", Second = " ", Expected = false };
- yield return new TestCase { First = " 1", Second = "1 ", Expected = false };
- yield return new TestCase { First = "\n he\tl o l", Second = " hello\\n", Expected = false };
- yield return new TestCase { First = "\n he\tl o l", Second = " hello\n", Expected = true };
- }
- }
- public class TestCase
- {
- public string First { get; set; }
- public string Second { get; set; }
- public bool Expected { get; set; }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement