Monday, September 24, 2012

Algorithm to check if a String is an Anagram or not

Anagram is a word of a phrase made by reordering the letters of another word.
For more information on anagrams please refer wikipedia link. Also a list of few funny anagrams is given below :

Mother-in-law = Woman Hitler
John Mayer = Enjoy harm
president barack hussein obama: a maniac presides. the banks rob u
William Shakespeare: I'll make a wise phrase
Jay Leno: Enjoy L.A.
Gene Simmons: Immense Song
Motley Crue: Me Cruel Toy
Bob Marley: Marble Boy
The Morse Code = Here Come Dots
Belgium = Big mule
The eyes = They see
Barbie doll = Liberal bod
George Bush = He bugs Gore
Waitress = A stew, Sir?
Guinness draught = naughtiness drug
Breasts = Bra sets
The Titanic disaster = Death, it starts in ice
Apple Products = Support Placed
Western Union = No Wire Unsent
Bruce Springsteen = Creep brings tunes
Tom Cruise = So I'm Cuter
vegetarian = ate in grave
graduation = out in a drag
Dick Cheney = Needy Chick
Debit card = Bad credit
A Decimal Point = I'm a Dot in Place
Jennifer Aniston = fine in torn jeans
Achievements = Nice, save them
Clothespins = So Let's Pinch
Christine = Nice Shirt
Spice Girls = Pig Slices
The Cincinnati Reds = Indecent Christian
Dormitory = Dirty Room
Confessional = On scale of sin
David Letterman = Nerd Amid Late TV
Princess Diana = end is a car spin
President W = Newest Drip
Statue of Liberty = Built to Stay Free
Laxative = exit lava
Evangelist = Evil's Agent
George W Bush = he grew bogus
Beavis and Butthead = Thus, be a bad deviant
Astronomer = moon starer
Apple, Inc = Epic Plan
San Francisco Giants- Fascinating, No scars
Pre Calculus = Call up curse
Stupid Girl = Drips Guilt
madonna louise ciccone = one cool dance musician
The United States of America = Attaineth its cause, freedom
Desperation = A Rope Ends It
Dancing with the stars = Winners had tight acts
Sherlock Holmes = He'll mesh crooks
Frito Lay = Oily Fart
Baseball = Babes All
Conversation = Voices Rant On 
Astronomer: Moon Starer
The Eyes: They See
Geologist = Go Get Oils
Christmas = Trims cash
Why do you care? = Hey you coward!
President Bush = Burnished Pest
Action man = cannot aim
The Simpson's = men's hot piss
Year two thousand = a year to shut down
Debit card = Bad Credit
shower time = where moist
Santa Monica = satanic moan
goodbye = Obey god
ipod lover = poor devil
Narcissism = Man's crisis
Actor Sylvester Stallone = Very cool talentless star
Funeral = Real Fun
comfort is = microsoft
Hot water = Worth tea
Television programming = Permeating living rooms
Margaret Thatcher = That great charmer
Darling I love you = Avoiding our yell
The Country Side = No City Dust Here
Flamethrower =  oh, felt warmer
Clint Eastwood = Old West Action
Ronald Wilson Reagan = Insane Anglo Warlord
Saddam Hussain = Humans sad side
Sheryl crow = her slow cry
Howard Stern = Retard Shown
Ladybug = bald guy
Astronomers = No more stars
Snooze Alarms = Alas! No More Z's
A Gentleman = Elegant Man
I hate school = oh so ethical
No admittance = contaminated
Microwave = Warm Voice
Austin Powers = power us satin
T.S. Eliot = toilets
A telescope = To see place
Elvis = lives
Justin Timberlake = im a jerk but listen
Mel Gibson = Big Melons
The Apple Macintosh = Machines apt to help
Eleven plus two = Twelve plus one
Christmas = Trims cash
The Meaning of Life = The fine game of nil
Schoolmaster = The classroom
A shoplifter = has to pilfer
listen = silent
Chemistry = shit, me cry
Gene Simmons = Immense Song
A Domesticated Animal = Docile, as a Man Tamed it
Garbage Man = Bag Manager
Following is an algorithm to detect whether two words are anagrams or not.

1. By means of Sorting which can take O(nlg(n)) + O( n).
2. By means simple logic not using sorting

public class Anagrams {

/**
* @param args
*/
public static void main(String[] args) {
/**
* 3 true
*/
System.out.println(isAnagram_By_Sort("abcdefghijlk", "abcdefghijlk"));
System.out.println(isAnagram_By_Sort("abcdefghijlkabcdef",
"ghiabcdefjlkabcdef"));
System.out
.println(isAnagram_Not_By_Sort("abcdefghijlk", "abcdefghijlk"));
/**
* false
*/
System.out.println(isAnagram_Not_By_Sort("abcdefghijlk",
"abcdefghijlkkkk"));
/**
* false for the next two
*/
System.out.println(isAnagram_Not_By_Sort("abcdefghijlk", "abcdefghij"));
System.out.println(isAnagram_Not_By_Sort("abcdefghijlk",
"abcdefghijlkklkl"));
/**
* true
*/
System.out
.println(isAnagram_Not_By_Sort("abcdefghijlk", "abcghijlkdef"));

}

private static boolean isAnagram_By_Sort(String str1, String str2) {
/**
* I have a int[] sorting algorithm in Heap sort that runs with n lg n
* so I am creating new methods for sorting char[]
*/
if (str1.length() != str2.length())
return false;
char[] st = str1.toCharArray();
char[] st2 = str2.toCharArray();
gyle.binarysearch.HeapSort.heapSort(st);
System.out.println(st);
gyle.binarysearch.HeapSort.heapSort(st2);
System.out.println(st2);
for (int i = 0; i < st2.length; i++) {
if (st[i] != st2[i])
return false;
}
return true;
}

private static boolean isAnagram_Not_By_Sort(String str1, String str2) {
if (str1.length() != str2.length())
return false;
int[] counts = new int[256];// as therer are only 256 characters that a
// string can acoomodate
for (int i = 0; i < str1.length(); i++) {
counts[str1.charAt(i)]++;
}
for (int i = 0; i < str2.length(); i++) {
if (counts[str2.charAt(i)]-- < 0)
return false;
}

for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
return false;
}

return true;
}

}



No comments:

Post a Comment