Created
July 9, 2018 13:41
-
-
Save VAlux/968af45ec5a3665ea9f184de630f82e1 to your computer and use it in GitHub Desktop.
Anagram search in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Assert; | |
import org.junit.Test; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
public class AnagramTest { | |
private final HashMap<String, Integer> dictionary = | |
new HashMap<String, Integer>() {{ | |
put("a", 5); | |
put("b", 71); | |
put("c", 37); | |
put("d", 29); | |
put("e", 2); | |
put("f", 53); | |
put("g", 59); | |
put("h", 19); | |
put("i", 11); | |
put("j", 83); | |
put("k", 79); | |
put("l", 31); | |
put("m", 43); | |
put("n", 13); | |
put("o", 7); | |
put("p", 67); | |
put("q", 97); | |
put("r", 23); | |
put("s", 17); | |
put("t", 3); | |
put("u", 41); | |
put("v", 73); | |
put("w", 47); | |
put("x", 89); | |
put("y", 61); | |
put("z", 10); | |
}}; | |
@Test | |
public void testAnagrams() { | |
Assert.assertTrue(areAnagrams("ABBA", "ABAB")); | |
Assert.assertTrue(areAnagrams("abBa", "ABaB")); | |
} | |
@Test | |
public void testNotAnagrams() { | |
Assert.assertFalse(areAnagrams("ABBA", "AFAF")); | |
Assert.assertFalse(areAnagrams("ABBA", "ABABG")); | |
Assert.assertFalse(areAnagrams("ABBA", "FFFFFFFFF")); | |
} | |
private boolean areAnagrams(final String first, final String second) { | |
if (first.length() != second.length()) { | |
return false; | |
} | |
return factorizeWord(first) == factorizeWord(second); | |
} | |
private long factorizeWord(final String word) { | |
return Arrays.stream(word.split("")) | |
.map(String::toLowerCase) | |
.filter(dictionary::containsKey) | |
.map(dictionary::get) | |
.reduce(1, (a, b) -> a * b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment