Welcome to week two of the weekly programming contests! As always, you can find the rules and information on the contests Posted Here
This weeks challenge: is to write a method that checks whether or not two words are anagrams. It should take in exactly two String parameters, and return true if they are anagrams, and false if they are not. Remember to also make the method public and static. For this challenge, Imports Are Allowed!
If you do not know what an anagram is, Google defines it as “a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman”
For the purposes of this challenge an anagram will be only a single word (no spaces) and one that must be formed by the use of ALL the letters of another word
public static boolean anagram(String s1, String s2) {
char[] l = s1.toCharArray();
if (l.length != s2.length())
return false;
for (char c : s2.toCharArray())
if (!c(l, c))
return false;
return true;
}
public static boolean c(char[] l, char c) {
for (char n : l)
if (n == c)
return true;
return false;
}
To be fair, if you’re going to use a vararg, you should at least properly check that there are a minimum of two strings instead of just assuming there are. I consider potential, non-handled exceptions as code failure.
If we don’t care about possible exceptions and incorrect returns, we may as well just assume that this method will return false most of the time, and finish it by just automatically returning it as such.
public static boolean anagram(String... s){return false;}
“should”, “consider”, “may”… You just turned this little game into a farce. Nothing of this is agreed upon and you just make things up to feel morally predominant.
Not a winner, but here’s an alternative, recursive solution:
public static boolean areAnagrams(String a, String b) {
return a.length() == b.length() && (a.length() > 0 ? areAnagrams(a.substring(1), b.replaceFirst(a.substring(0, 1), "")) : true);
}
Shortened; 146 characters:
public static boolean a(String a,String b){int c=a.length();return c==b.length()&(c>0?a(a.substring(1),b.replaceFirst(a.substring(0,1),"")):1>0);}
It should be noted that this works only if the parameters do not contain a character that has a special meaning as a regex pattern. All letters is fine.