Java Program to Detect Anagrams Using Sorted Letter Inventory Class – Implementing LetterInventory.java for Canonical Form Processing

Learn how to implement a Java program that finds anagrams by creating a LetterInventory class to generate canonical sorted letter forms. Step-by-step guide to building an anagram detector using object-oriented programming in Java.



For this project, you are going to write a program to find the anagrams in a given dictionary for a given word. If two words have the same letters but in different order, they are called anagrams. For example, “listen” and “silent” are a pair of anagrams.

**JAVA**

First let’s focus on “LetterInventory.java”.

Its purpose is to compute the canonical “sorted letter form” for a given word.

1. Implement the constructor, which takes the String input word. You can assume that the input word contains only valid letters (e.g. no punctuation or blanks), but it may contain letters in different cases.

2. Implement the method: public String getCanonical() It should return the canonical “sorted letter form” for the input word (given in the constructor). It should use only lower cases. For example, if the given word is “AliBaba”, then this method should return “aaabbil”.

 

Answer

 

import java.io.*;

import java.util.*;

 

public class AnagramFinder {

 

  Map<String, String> dictionary = new   HashMap<String, String>();

 

 

   public static void main(String[] args) throws FileNotFoundException {

       String[] originals = new String[] {

           "realfun",

           "mias",

           "EVIL",

           "unable",

           "Silent",

           "AliBaba"

       };

 

       for(String original: originals) {

           LetterInventory inv = new LetterInventory(original);

           System.out.println("Original: " + original + ", Canonical: " + inv.getCanonical());

       }

 

       System.out.println("\n");

 

       // TODO: change path to match where your input file is located

      File f = new File("sample_dict.txt");

 

       AnagramFinder finder = new AnagramFinder(f);

 

 

 

       for(String original: originals) {

           finder.printAnagrams(original);

       }

 

 

   }

 

   public AnagramFinder(File f)throws FileNotFoundException      {

       // TODO: implement

 try{

 

BufferedReader br = new BufferedReader(new FileReader(f));

 

 

String input = "";

 

LetterInventory sort = null ;

 

 

// add dictionay file to map

while ((input = br.readLine()) != null) {

 

//sort the string by getCanonical

sort  = new LetterInventory(input);

String sortedInput = sort.getCanonical();

 

 

if (dictionary.get(sortedInput) == null) {

dictionary.put(sortedInput, input);

}

 

else {

String previousValue = dictionary.get(sortedInput);

dictionary.put(sortedInput, previousValue + "; " + input);

}

}

}catch  (IOException e){

System.out.println(e);

}

 

 

   }

 

public void printAnagrams(String word) {

       // TODO: implement

 

String output = "";

int length = word.length();

 

LetterInventory sort  =null;

 

int lengthloop = (int) (Math.pow(2, length)-1);

 

  Map<String, String> othermap = new  HashMap<String, String>();

 

for (int j=0; j<lengthloop; j++) {

 

String convertbin = Integer.toBinaryString(j+1);

String tempstring = "";

 

int convertbinLength = convertbin.length();

 

for (int k=convertbinLength-1; k>=0; k--) {

 

if (convertbin.charAt(k)=='1') {

int getChar = length - (convertbinLength - k);

tempstring = word.charAt(getChar) + tempstring;

}

}

 

sort  = new LetterInventory(tempstring);

String sortedBuffer = sort.getCanonical();

 

 

if (othermap.get(sortedBuffer) != null) { }

 

 

else {

 

othermap.put(sortedBuffer, "");

String dictVal = "";

 

if ((dictVal = dictionary.get(sortedBuffer)) != null) {

 

String[] dictValSplit = dictVal.split("; ");

 

for (int m=0; m<dictValSplit.length; m++) {

 

if(dictValSplit[m].length()   == length) {

 

 output += dictValSplit[m] ;

  if( m != dictValSplit.length - 1)

                           output += ", ";

 

              }

 

 

}

 

}

}

 

}

 

if(!output.equals(""))

System.out.println ("Your input is: "+word+". Found anagrams:  "+output+".");

else

System.out.println ("Your input is: "+word+". Sorry, didn't find any angrams.");

 

    }

 

public void printAnagrams2(String word) {

 

// Extra Credit: optional to implement

 

String output = "";

int length = word.length();

 

 

int lengthloop = (int) (Math.pow(2, length)-1);

 

 Map<String, String> othermap = new HashMap<String, String>();

 

for (int j=0; j<lengthloop; j++) {

 

String convertbin = Integer.toBinaryString(j+1);

String tempstring = "";

 

int convertbinLength = convertbin.length();

 

for (int k=convertbinLength-1; k>=0; k--) {

 

if (convertbin.charAt(k)=='1') {

            int getChar = length - (convertbinLength - k);

            tempstring = word.charAt(getChar) + tempstring;

}

}

 

 

char[] letters = tempstring.toCharArray();

Arrays.sort(letters);

String sortedBuffer = String.valueOf(letters);

 

 

if (othermap.get(sortedBuffer) != null) { }

 

 

else {

 

othermap.put(sortedBuffer, "");

String dictVal = "";

 

if ((dictVal = dictionary.get(sortedBuffer)) != null) {

 

            String[] dictValSplit = dictVal.split("; ");

 

            for (int m=0; m<dictValSplit.length; m++) {

 

                        if(dictValSplit[m].length()   == length && !dictValSplit[m].equals(word) ) {

 

                         output += dictValSplit[m] ;

                          if( m != dictValSplit.length - 1)

                                                              output += ", ";

 

                                      }

 

 

            }

 

}

}

 

   }

 

if(!output.equals(""))

System.out.println ("Your input is: "+word+". Found anagrams:  "+output+".");

else

System.out.println ("Your input is: "+word+". Sorry, didn't find any angrams.");

 

   }

}

 

 

 

 

 

 

 

 

import java.util.Arrays;

 

public class LetterInventory {

 

                String words;

 

    public LetterInventory(String input) {

        // TODO: implement

 

        words = input;

    }

 

    public String getCanonical() {

        // TODO: implement

 

        words = words.toLowerCase();

                                char [] word = words.toCharArray();

                                Arrays.sort(word);

                                String result  = new String (word);

 

       return result;

    }

}

 

 

 

 

sample_dict.txt

 

2

1080

isawabus

&c

10-point

10th

11-point

12-point

16-point

18-point

1st

2,4,5-t

2,4-d

20-point

2D

2nd

30-30

3D

3-D

3M

3rd

48-point

4-D

4GL

4H

4th

5-point

5-T

5th

6-point

6th

7-point

7th

8-point

8th

9-point

9th

a

a'

a-

A&M

A&P

A.

A.A.A.

A.B.

A.B.A.

A.C.

A.D.

A.D.C.

A.F.

A.F.A.M.

A.G.

A.H.

A.I.

A.I.A.

A.I.D.

A.L.

A.L.P.

A.M.

A.M.A.

A.M.D.G.

A.N.

a.p.

a.r.

A.R.C.S.

A.U.

A.U.C.

A.V.

a.w.

A.W.O.L.

A/C

A/F

A/O

A/P

A/V

A1

A-1

A4

A5

AA

AAA

AAAA

AAAAAA

AAAL

AAAS

Aaberg

Aachen

AAE

AAEE

AAF

AAG

aah

aahed

aahing

aahs

AAII

aal

Aalborg

Aalesund

aalii

aaliis

aals

Aalst

Aalto

AAM

AAMSI

Aandahl

A-and-R

Aani

AAO

AAP

AAPSS

Aaqbiye

Aar

Aara

Aarau

AARC

aardvark

aardvarks

aardwolf

aardwolves

Aaren

Aargau

aargh

Aarhus

Aarika

Aaron

Aaronic

Aaronical

Aaronite

Aaronitic

Aaron's-beard

Aaronsburg

Aaronson

AARP

aarrgh

aarrghh

Aaru

AAS

A'asia

aasvogel

aasvogels

AAU

AAUP

AAUW

AAVSO

AAX

A-axes

A-axis

AB

ab-

ABA

Ababa

Ababdeh

Ababua

abac

abaca

abacay

abacas

abacate

abacaxi

abaci

abacinate

abacination

abacisci

abaciscus

abacist

aback

abacli

Abaco

abacot

abacterial

abactinal

abactinally

abaction

abactor

abaculi

abaculus

abacus

abacuses

Abad

abada

Abadan

Abaddon

abadejo

abadengo

abadia

Abadite

abaff

abaft

Abagael

Abagail

Abagtha

abay

abayah

Abailard

abaisance

abaised

abaiser

abaisse

abaissed

abaka

Abakan

abakas

Abakumov

abalation

abalienate

abalienated

abalienating

abalienation

abalone

abalones

Abama

abamp

abampere

abamperes

abamps

Abana

aband

abandon

abandonable

abandoned

abandonedly

abandonee

abandoner

abandoners

abandoning

abandonment

abandonments

abandons

abandum

abanet

abanga

Abanic

abannition

Abantes

abapical

abaptiston

abaptistum

Abarambo

Abarbarea

Abaris

abarthrosis

abarticular

abarticulation

Abas

abase

abased

abasedly

abasedness

abasement

abasements

abaser

abasers

abases

Abasgi

abash

abashed

abashedly

abashedness

abashes

abashing

abashless

abashlessly

abashment

abashments

abasia

abasias

abasic

abasing

abasio

abask

abassi

Abassieh

Abassin

abastard

abastardize

abastral

abatable

abatage

Abate

abated

abatement

abatements

abater

abaters

abates

abatic

abating

abatis

abatised

abatises

abatjour

abatjours

abaton

abator

abators

ABATS

abattage

abattis

abattised

abattises

abattoir

abattoirs

abattu

abattue

Abatua

abature

abaue

abave

abaxial

abaxile

abaze

abb

Abba

abbacy

abbacies

abbacomes

Abbadide

Abbai

abbaye

abbandono

abbas

abbasi

Abbasid

abbassi

Abbassid

Abbasside

Abbate

abbatial

abbatical

abbatie

Abbe

Abbey

abbeys

abbey's

abbeystead

abbeystede

abbes

abbess

abbesses

abbest

Abbevilean

Abbeville

Abbevillian

Abbi

Abby

Abbie

Abbye

Abbyville

abboccato

abbogada

Abbot

abbotcy

abbotcies

abbotnullius

abbotric

abbots

abbot's

Abbotsen

Abbotsford

abbotship

abbotships

Abbotson

Abbotsun

Abbott

Abbottson

Abbottstown

Abboud

abbozzo

ABBR

abbrev

abbreviatable

abbreviate

abbreviated

abbreviately

abbreviates

abbreviating

abbreviation

abbreviations

abbreviator

abbreviatory

abbreviators

abbreviature

abbroachment

ABC

abcess

abcissa

abcoulomb

ABCs

abd

abdal

abdali

abdaria

abdat

Abdel

Abd-el-Kadir

Abd-el-Krim

Abdella

Abderhalden

Abderian

Abderite

Abderus

abdest

Abdias

abdicable

abdicant

abdicate

abdicated

abdicates

abdicating

abdication

abdications

abdicative

abdicator

Abdiel

abditive

abditory

abdom

abdomen

abdomens

abdomen's

abdomina

abdominal

Abdominales

abdominalia

abdominalian

abdominally

abdominals

abdominoanterior

abdominocardiac

abdominocentesis

abdominocystic

abdominogenital

abdominohysterectomy

abdominohysterotomy

abdominoposterior

abdominoscope

abdominoscopy

abdominothoracic

abdominous

abdomino-uterotomy

abdominovaginal

abdominovesical

Abdon

Abdu

abduce

abduced

abducens

abducent

abducentes

abduces

abducing

abduct

abducted

abducting

abduction

abductions

abduction's

abductor

abductores

abductors

abductor's

abducts

Abdul

Abdul-Aziz

Abdul-baha

Abdulla

Abe

a-be

abeam

abear

abearance

Abebi

abecedaire

abecedary

abecedaria

abecedarian

abecedarians

abecedaries

abecedarium

abecedarius

abed

abede

abedge

Abednego

abegge

Abey

abeyance

abeyances

abeyancy

abeyancies

abeyant

abeigh

ABEL

Abelard

abele

abeles

Abelia

Abelian

Abelicea

Abelite

Abell

Abelmoschus

abelmosk

abelmosks

abelmusk

Abelonian

Abelson

abeltree

Abencerrages

abend

abends

Abenezra

abenteric

Abeokuta

abepithymia

ABEPP

Abercromby

Abercrombie

Aberdare

aberdavine

Aberdeen

Aberdeenshire

aberdevine

Aberdonian

aberduvine

Aberfan

Aberglaube

Aberia

Aberystwyth

Abernant

Abernathy

abernethy

Abernon

aberr

aberrance

aberrancy

aberrancies

aberrant

aberrantly

aberrants

aberrate

aberrated

aberrating

aberration

aberrational

aberrations

aberrative

aberrator

aberrometer

aberroscope

Abert

aberuncate

aberuncator

abesse

abessive

abet

abetment

abetments

abets

abettal

abettals

abetted

abetter

abetters

abetting

abettor

abettors

Abeu

abevacuation

abfarad

abfarads

ABFM

Abgatha

ABHC

abhenry

abhenries

abhenrys

abhinaya

abhiseka

abhominable

abhor

abhorred

abhorrence

abhorrences

abhorrency

abhorrent

abhorrently

abhorrer

abhorrers

abhorrible

abhorring

abhors

Abhorson

ABI

aby

Abia

Abiathar

Abib

abichite

abidal

abidance

abidances

abidden

abide

abided

abider

abiders

abides

abidi

abiding

abidingly

abidingness

Abidjan

Abydos

Abie

abye

abied

abyed

abiegh

abience

abient

Abies

abyes

abietate

abietene

abietic

abietin

Abietineae

abietineous

abietinic

abietite

Abiezer

Abigael

Abigail

abigails

abigailship

Abigale

abigeat

abigei

abigeus

Abihu

abying

Abijah

Abyla

abilao

Abilene

abiliment

Abilyne

abilitable

ability

abilities

ability's

abilla

abilo

abime

Abimelech

Abineri

Abingdon

Abinger

Abington

Abinoam

Abinoem

abintestate

abiogeneses

abiogenesis

abiogenesist

abiogenetic

abiogenetical

abiogenetically

abiogeny

abiogenist

abiogenous

abiology

abiological

abiologically

abioses

abiosis

abiotic

abiotical

abiotically

abiotrophy

abiotrophic

Abipon

Abiquiu

abir

abirritant

abirritate

abirritated

abirritating

abirritation

abirritative

abys

Abisag

Abisha

Abishag

Abisia

abysm

abysmal

abysmally

abysms

Abyss

abyssa

abyssal

abysses

Abyssinia

Abyssinian

abyssinians

abyssobenthonic

abyssolith

abyssopelagic

abyss's

abyssus

abiston

abit

Abitibi

Abiu

abiuret

Abixah

abject

abjectedness

abjection

abjections

abjective

abjectly

abjectness

abjectnesses

abjoint

abjudge

abjudged

abjudging

abjudicate

abjudicated

abjudicating

abjudication

abjudicator

abjugate

abjunct

abjunction

abjunctive

abjuration

abjurations

abjuratory

abjure

abjured

abjurement

abjurer

abjurers

abjures

abjuring

abkar

abkari

abkary

Abkhas

Abkhasia

Abkhasian

Abkhaz

Abkhazia

Abkhazian

abl

abl.

ablach

ablactate

ablactated

ablactating

ablactation

ablaqueate

ablare

A-blast

ablastemic

ablastin

ablastous

ablate

ablated

ablates

ablating

ablation

ablations

ablatitious

ablatival

ablative

ablatively

ablatives

ablator

ablaut

ablauts

ablaze

able

able-bodied

able-bodiedness

ableeze

ablegate

ablegates

ablegation

able-minded

able-mindedness

ablend

ableness

ablepharia

ablepharon

ablepharous

Ablepharus

ablepsy

ablepsia

ableptical

ableptically

abler

ables

ablesse

ablest

ablet

ablewhackets

ably

ablings

ablins

ablock

abloom

ablow

ABLS

ablude

abluent

abluents

ablush

ablute

abluted

ablution

ablutionary

ablutions

abluvion

ABM

abmho

abmhos

abmodality

abmodalities

abn

Abnaki

Abnakis

abnegate

abnegated

abnegates

abnegating

abnegation

abnegations

abnegative

abnegator

abnegators

Abner

abnerval

abnet

abneural

abnormal

abnormalcy

abnormalcies

abnormalise

abnormalised

abnormalising

abnormalism

abnormalist

abnormality

abnormalities

abnormalize

abnormalized

abnormalizing

abnormally

abnormalness

abnormals

abnormity

abnormities

abnormous

abnumerable

Abo

aboard

aboardage

Abobra

abococket

abodah

abode

aboded

abodement

abodes

abode's

abody

aboding

abogado

abogados

abohm

abohms

aboideau

aboideaus

aboideaux

aboil

aboiteau

aboiteaus

aboiteaux

abolete

abolish

abolishable

abolished

abolisher

abolishers

abolishes

abolishing

abolishment

abolishments

abolishment's

abolition

abolitionary

abolitionise

abolitionised

abolitionising

abolitionism

abolitionist

abolitionists

abolitionize

abolitionized

abolitionizing

abolitions

abolla

abollae

aboma

abomas

abomasa

abomasal

abomasi

abomasum

abomasus

abomasusi

A-bomb

abominability

abominable

abominableness

abominably

abominate

abominated

abominates

abominating

abomination

abominations

abominator

abominators

abomine

abondance

Abongo

abonne

abonnement

aboon

aborad

aboral

aborally

abord

Aboriginal

aboriginality

aboriginally

aboriginals

aboriginary

Aborigine

aborigines

aborigine's

Abor-miri

Aborn

aborning

a-borning

aborsement

aborsive

abort

aborted

aborter

aborters

aborticide

abortient

abortifacient

abortin

aborting

abortion

abortional

abortionist

abortionists

abortions

abortion's

abortive

abortively

abortiveness

abortogenic

aborts

abortus

abortuses

abos

abote

Abott

abouchement

aboudikro

abought

Aboukir

aboulia

aboulias

aboulic

abound

abounded

abounder

abounding

aboundingly

abounds

Abourezk

about

about-face

about-faced

about-facing

abouts

about-ship

about-shipped

about-shipping

about-sledge

about-turn

above

aboveboard

above-board

above-cited

abovedeck

above-found

above-given

aboveground

abovementioned

above-mentioned

above-named

aboveproof

above-quoted

above-reported

aboves

abovesaid

above-said

abovestairs

above-water

above-written

abow

abox

Abp

ABPC

Abqaiq

abr

abr.

Abra

abracadabra

abrachia

abrachias

abradable

abradant

abradants

abrade

abraded

abrader

abraders

abrades

abrading

Abraham

Abrahamic

Abrahamidae

Abrahamite

Abrahamitic

Abraham-man

Abrahams

Abrahamsen

Abrahan

abray

abraid

Abram

Abramis

Abramo

Abrams

Abramson

Abran

abranchial

abranchialism

abranchian

Abranchiata

abranchiate

abranchious

abrasax


 📩 Need a similar solution? Email me: adel455@hotmail.com









Previous Post Next Post

Comments

Nepali Graphics - Learn design, Animation, and Progrmming