DEV Community

Cover image for Day 6: Anagram Detector
Matt Ryan
Matt Ryan

Posted on

Day 6: Anagram Detector

Detect if given word or phrase form an anagram.

import java.util.Arrays;

public class DaySix
{
    public static void main(String[] args)
    {
        String input = "Dormitory ? Dirty room\n" +
                "Conversation ? Voices rant on\n" +
                "The eyes ? They see\n" +
                "Inch ? Chins\n" +
                "Fourth of July ? Joyful Fourth\n" +
                "Elbow ? Below\n" +
                "The Morse Code ? Here come the dots\n" +
                "Astronomer ? Moon starer\n" +
                "Vacation Time ? I'm Not as Active\n" +
                "Listen ? Silent\n" +
                "Eleven plus two ? Twelve plus one";

        String[] line = input.split("\n");
        String[][] wordSet = new String[line.length][2];

        for(int i = 0; i < line.length; i++)
            for (int j = 0; j < 2; j++)
                wordSet[i][j] = line[i].split("\\?")[j].trim();


        for(String[] cur: wordSet)
            System.out.println( "\"" + cur[0] + "\"" + (isAnagram(cur[0], cur[1]) ? " is an anagram of " : " is NOT an anagram of ") +  "\"" + cur[1] + "\"");


    }

    private static boolean isAnagram(String str1, String str2)
    {
        char[] charArr1;
        char[] charArr2;

        charArr1 = str1.toLowerCase()
                .replaceAll("'", "")
                .replaceAll("\\s", "")
                .toCharArray();
        charArr2 = str2.toLowerCase()
                .replaceAll("'", "")
                .replaceAll("\\s", "")
                .toCharArray();

        Arrays.sort(charArr1);
        Arrays.sort(charArr2);

        return Arrays.equals(charArr1, charArr2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay