Categories
Career Programming

Programmer interview challenge 1, revisited once more: “Anagram” in Ruby and C#

Oh hey — why not one more? In the past three articles, I’ve been writing about a challenge that’s often given to programmers at a tech interview: Write a program that determines if two words are anagrams.

In the first article, I wrote a basic Python solution. In the second article, I refined the Python solution and then based a JavaScript solution on it. In the third article, I showed a couple of Swift implementations — one simple, one hardcore. In this article, I’ll present Ruby and C# solutions.

The Ruby version

I used to work with Ruby and Rails a fair bit, so I really should post a Ruby version:

def sortLetters(word)
   word.downcase.chars.sort.join.strip 
end

def anagram?(word1, word2)
   sortLetters(word1) == sortLetters(word2) 
end

# Let’s try it out
puts anagram?('iceman', 'cinema')     # true
puts anagram?('Florida', 'fail rod')  # true
puts anagram?('ABC', 'xyz')           # false

Some things to note:

  • Ruby doesn’t support nested methods. You can put a method inside another method in Ruby, but that doesn’t make it a nested method. That’s why I’ve defined sortLetters() and anagram?() as two separate methods.
  • I wrote these methods to reflect the preferred “delightfully terse” style that is preferred way in the Ruby world. InsortLetters(), and I skip the return statement (optional in Ruby; in its absence, a method returns the result of its last line), use method chaining, and skip any unnecessary parentheses, hence word.downcase.chars.sort.join.strip, which very clearly states that it does the following:
    • Convert the given string to all lowercase characters.
    • Split the resulting string into an array of characters.
    • Sort the array.
    • Turn the array back into a string.
    • Strip any leading and trailing strings from string. If the original string had any spaces in it, they would be leading spaces in the current string.
  • Following Ruby convention, I added a ? to the “anagram” name to make the name of the method anagram?(), which is the Ruby convention for methods that return boolean values. As with the versions of anagram()that I wrote in JavaScript, Python, and Swift, two words are anagrams of each other if their sorted forms are the same.

If you’re interested in trying the histogram approach, you may want to try out Ruby’s Enumerable#tally method:

'foo'.chars.tally   # results in {"f"=>1, "o"=>2}

The C# version

Here’s the C# version. It uses LINQ, because LINQ often makes life easier:

using System.Linq;

string sortLetters(string word) 
{
  return String.Concat(word.ToLower().OrderBy(c => c)).Trim();
}

static bool anagram(string word1, string word2) 
{
  return sortLetters(word1) == sortLetters(word2);
}

Previously, in the “Programmer interview challenge” series