Question: anagramCount: [challenging] This method takes a single parameter and it must return the number distinct case-insensitive anagrams of the given word that have been added
anagramCount: [challenging] This method takes a single parameter and it must return the number distinct case-insensitive anagrams of the given word that have been added to the processor. An anagram consists of exactly the same number of letters as the given word with each character occurring the same number of times. However, identical words are not considered to be anagrams. For instance: "and" is an anagram of "dan" but "nan" is neither an anagram of "naan" nor of nan. Note that because the match must be case-insensitive, Dan is also an anagram of and. However, because the match is case-insensitive, all of Dan, dan and DAN only count as a single match for any of and, AND and And. Also, each anagram is only counted once, regardless of how many times it has been added to the processor via addWord.
My Java code:
public int anagramCount(String word) { int count = 0; int[] wordFreq = new int[26]; word = word.toLowerCase(); for(char ch : word.toCharArray()){ wordFreq[ch-'a']++; } HashSet checked = new HashSet<>(); for(String str : processor.keySet()){ int[] strFreq = new int[26]; String s = str.toLowerCase(); if(checked.contains(s)){ continue; } checked.add(s); for(char ch : s.toCharArray()){ strFreq[ch-'a']++; } boolean isAnagram = true; for(int i=0; i<26; i++){ if(wordFreq[i] != strFreq[i]){ isAnagram = false; break; } } if(isAnagram){ count++; } } return count; }
Main code
public class TextProcessor { private HashMap
I need help with my anagram code it is failing all the test :
public void anagramNone() { testInstance.addWord("and"); assertEquals(0, testInstance.anagramCount("and")); }
@Test public void anagramNoneCaseSensitive() { testInstance.addWord("and"); testInstance.addWord("AND"); assertEquals(0, testInstance.anagramCount("and")); assertEquals(0, testInstance.anagramCount("AND")); }
@Test public void anagramOne1() { testInstance.addWord("and"); testInstance.addWord("dan"); assertEquals(1, testInstance.anagramCount("dan")); assertEquals(1, testInstance.anagramCount("and")); }
@Test public void anagramOne2() { testInstance.addWord("and"); testInstance.addWord("AND"); testInstance.addWord("dan"); testInstance.addWord("Dan"); testInstance.addWord("DAN"); assertEquals(1, testInstance.anagramCount("dan")); assertEquals(1, testInstance.anagramCount("and")); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
