Coding Challenge – Detect an Anagram

Halloween Jack O' Lantern maybe a scare for our coding challenge?

OK, it is time for my unofficial weekly coding challenge.  This time I am going to do a fairly simple challenge involving anagrams.  If you read the definition on Wikipedia it states that an anagram is, “a word or phrase formed by rearranging the letters in a word or a phrase, typically using all the letters exactly once.”

Now, on to the challenge. The challenge I am going to take on today is to determine if two words are anagrams.  Both words will be taken from the standard input terminated by the system’s end of line character.  If the words are anagrams I will output “true” to the standard output and “false” if they are not.

Before I move on there are a few of things to remember.  First, spaces are not important in determining if a word is an anagram.  Second, an anagram will have the

Dogs are not afraid of coding challenge

same number of letters.  Lastly, converting the characters to lowercase will help.  I will be testing the anagrams using Halloween themed items such as: scare and cares; pirates and parties; potion and option; and monster and mentors.

Since we now have that knowledge, here is the basic logic.  If we order two lists and every position is the same character it’s an anagram and if even one character is not in order then it is not an anagram.  This should be pretty easy so let’s get started.

[show_more more=”View solution” less=”Close solution”]

 

[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Pessetto
{
public class Anagram
{
public static void Main(string[] args)
{
var firstWord = Console.ReadLine().ToLower().Replace(" ","");
var secondWord = Console.ReadLine().ToLower().Replace(" ","");
char[] firstWordArray = firstWord.ToCharArray();
char[] secondWordArray = secondWord.ToCharArray();
Array.Sort(firstWordArray);
Array.Sort(secondWordArray);
var anagram = true;
if(firstWordArray.Length == secondWord.Length)
{
for(int i = 0; i < firstWord.Length; ++i)
{
if(firstWordArray[i] != secondWordArray[i])
{
anagram = false;
break;
}
}
}
else
{
anagram = false;
}
if(anagram)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
[/csharp]

[/show_more]

This entry was posted on Tuesday, October 31st, 2017 at 6:00 pm

Leave a Reply

Your email address will not be published. Required fields are marked *