≡ Menu

Java Practice Assignment #4 – The Anagram

Alright ladies and gentlemen, this week’s assignment is in. But before we get into it:

Click Here to download my particular solution for Assignment 3.

There will be many ways to solve this assignment, and I’m not saying that my solution is the best solution, but if you were having trouble getting your assignment to work, then mine might help you out. If you feel like you’ve got a better solution feel free to shoot it over to me via email at info@howtoprogramwithjava.com. I’ll post it here as another solution so that everyone may benefit 🙂

Assignment #4 – The Anagram

Before you read through and download this assignment, I’d like to ask you for a favour. Back in October of 2012 I decided to quit my 9-5 day job and take a run at doing what it is I love to do full-time: creating fun and educational tutorials like this one. So since this has now become my livelihood, it would really mean the world to me if you took a few seconds to share this content with the world. The more people I have sharing this stuff, the more chance I’ll have at being able to continue doing what it is I love, and that’s helping YOU guys out. So if you have a moment, please click one of the sharing options to the left of this, and if you do I humbly thank you.

Click Here to view the assignment files for Java practice assignment #4 on GitHub.

Here’s the GitHub URI: https://github.com/tp02ga/JavaPracticeAssignment4.git

This is one of my favourite types of assignments, it’s an algorithm assignment. This type of assignment is design to test your skills at creating an algorithm that will solve the presented problem. Remember that there are MANY ways to solve this problem, your goal should be to create code that is as efficient as possible. Your task for Java practice assignment #4 is to code an anagram solver. First of all, we’ll define the term “anagram” for this assignment:

An anagram is considered to be a pair of words that are made up of the exact same letters. Think of it like taking one word, then just scrambling the letters around until you can spell another word. For the purposes of this assignment we’ll only be dealing with single word anagrams, as there are certainly anagrams that can be formed by multiple words (but let’s not worry about those ones). Here are some examples of valid anagrams:

care -> race
tool -> loot
cloud -> could

An example of words that a NOT anagrams:

tool -> toll (doesn’t have the exact same number of letters)
cloud -> clouds (one word is longer than the other)

So, your task will be to create a method that will return true or false (anagram or NOT an anagram) based on the two Strings that will be passed in. Be sure to follow the instructions included in the assignment files!

{ 14 comments… add one }

  • Bernd January 23, 2013, 4:25 am

    Since the assigbnement is a while ago, I think I can show my solution…
    My personal challenge was to get the solution into one line. Well, I _almost_ succeeded.

    My algorithm is: sort the uppercase or lowercase strings and compare them. If they match, they are anagrams.
    Unfortunatelly there is no funtion/metod in Java which returns a sorted String or Array (all sorting methods sort in-place and return nothing, i.e. they are void).
    So I had to provide my own function for this task.
    Today I stumbled upon a very critical topic concerning toLowerCase, toUpperCase: Locale. There are some very special characters in german (sharp s=ß, which becomes SS in uppercase) and turkish undotted lowercase i and dotted uppercase I). Please follow the links in the source to learn more.

    String.compareToIgnoreCase(str2) would handle these cases just fine, but for this anagram assigment I had to upperCase() the String first and then sort it.

    I have added two test cases which deal with these special cases:

      @Test
      public void should_treat_turkish ()
      {
        boolean anAnagram = sut.isAnAnagram("Biılly", "BİILLY");
        assertThat(anAnagram, is(true));
      }
      @Test
      public void should_treat_non_turkish ()
      {
        boolean anAnagram = sut.isAnAnagram("Billy", "BILLY");
        assertThat(anAnagram, is(true));
      }
    

    The code isAnagram is hard to read according to my one-line goal. This is not an example of clear, readable code, but it works.

          public class AnagramSolverImpl implements AnagramSolver {
    	@Override
    	public boolean isAnAnagram(String word1, String word2) {
    		return !(word1 == null || word2 == null || !sortUcString(word1).equals(sortUcString(word2)));
    	}
    
    	private String sortUcString(String inStr) {
    		// assertion: inStr is not null
    		// Beware of Turkish locale (dotted, undotted i)
    		//  http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug
    		//  http://java.dzone.com/articles/policemans-horror-default
    		// And german (all locales) ß toUpperCase: SS but not vice-versa!
    		Locale loc = Locale.ENGLISH;
    		// Contains undotted small i or dotted capital I?
    		// => Must be turkish.
    		if (inStr.contains("ı") || inStr.contains("İ")) {
    			loc = Locale.forLanguageTag("tr");
    		}
    		char[] wordArr = inStr.toUpperCase(loc).toCharArray();
    		Arrays.sort(wordArr);
    		return new String(wordArr);
    	}
       }
    
  • Ashish July 28, 2014, 7:10 am

    An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

    For example: orchestra can be rearranged into carthorse or cat can be rearranged into act.

    We can find out the anagram strings using below algorithm:

    public static boolean isAnagram(String str1, String str2) {
    if (str1 == null || str2 == null) {
    return false;
    } else if (str1.length() != str2.length()) {
    return false;
    }

    Map map = new HashMap();

    for (int i = 0; i < str1.length(); i++) {
    char characters = str1.charAt(i);
    int charInStr1 = map.containsKey(characters) ? map.get(characters) : 0;
    map.put(characters, ++charInStr1);
    char charFromStr2 = str2.charAt(i);
    int charsInRight = map.containsKey(charFromStr2) ? map.get(charFromStr2) : 0;
    map.put(charFromStr2, –charsInRight);
    }

    for (int occurrences : map.values()) {
    if (occurrences != 0) {
    return false;
    }
    }
    return true;
    }

    I found below useful links for more information

    Write program to find if Strings are anagram

  • Pramod February 20, 2015, 2:14 am

    Very nice assignment….

  • David September 29, 2015, 3:27 pm

    mmm i use this, is this valid?
    public class AnagramSolverImpl implements AnagramSolver {

    @Override
    public boolean isAnAnagram(String word1, String word2)
    {
    // TODO Auto-generated method stub
    if (word1 == null || word2 == null)
    return false;
    if (word1.length() == word2.length() && word2.compareTo(word1) >= 0)
    {

    return true;
    }
    else {
    return false; }
    }

    }

    • David September 29, 2015, 3:58 pm

      oops sorry, i got a better option

      public class AnagramSolverImpl implements AnagramSolver {

      @Override
      public boolean isAnAnagram(String word1, String word2)
      {
      if (word1 == null || word2 == null)
      return false;
      if (word1.length() != word2.length())
      return false;
      char[] test1 = (word1.toLowerCase()).toCharArray();
      char[] test2 = (word2.toLowerCase()).toCharArray();
      Arrays.sort(test1);
      Arrays.sort(test2);
      if(Arrays.equals(test1,test2))
      return true;

      else
      return false;

      }

  • roman December 16, 2016, 7:42 am

    can u do this question to me:
    1) The Car class has two attributes, which correspond to the description and the customer’s name. The description and the customer’s name are each represented as a string of text. The description is initialised in the constructor, by being assigned the value of the constructor’s only parameter. The customer’s name is assigned an empty string (“”).

    Each attribute has a corresponding accessor method and there is another method to set the customer’s name to a new name. A display method will output (suitably annotated) the description and, if the customer’s name is not an empty string, the customer’s name too.

  • roman December 29, 2016, 2:03 am

    remove my question
    do not give me solution to me

  • roman December 29, 2016, 2:05 am

    do not give me solution and remove the question
    whish i have asked

  • roman December 29, 2016, 2:25 am

    remove my question which i have post
    dont give me solution

  • roman December 29, 2016, 2:25 am

    dont give me solution
    remove my question which i have post

  • roman December 29, 2016, 8:34 pm

    remove my question and do not give me solution plz

  • roman December 31, 2016, 10:03 pm

    remove my question which i have asked
    donot give me solution

  • roman March 16, 2017, 5:23 pm

    remove mi question which i asked donut give me solution

  • game players wish March 22, 2017, 6:55 pm

    Thanks for a marvelous posting! I definitely enjoyed reading
    it, you could be a great author.I will make certain to bookmark your blog and may come back very soon. I want
    to encourage yourself to continue your great job, have a
    nice morning!

Leave a Comment