Compare hashMap values
compare, hashmap, java
Solution
Check each letter in your ransom note and see if there are enough in the newspaper:
boolean enoughLetters(Map<Character, Integer> magMap, Map<Character,Integer> ransomMap) {
for( Entry<Character, Integer> e : ransomMap.entrySet() ) {
Character letter = e.getKey();
Integer available = magMap.get(letter);
if (available == null || e.getValue() > available) return false;
}
return true;
}
Problem
Im practicing some interview questions but have no idea how to compare hashMap values. The premise is that you have a magazine with strings. You have to cut out the appropriate number of characters out of the magazine to form a ransom note. I've managed to add both the characters and the number of occurrences of the characters to a hashMap but how do I compare the two hashMaps to determine I have enough letters.Any guidance would be much appreciated. Magazine = {g=2, =14, d=2, e=2, a=4, n=1, o=5, l=4, m=1, .=1, k=1, I=2, h=2, i=6, w=1, T=1, u=1, t=2, s=3, r=1, y=2} Ransom = {w=1, =3, o=1, l=4, k=1, I=1, y=1, i=2} ``` String mag = "this is what I said Im going to do. i really like you a lot"; String ransom = "i will kill you"; Map<Character,Integer> map = new HashMap<Character,Integer>(); Map<Character,Integer> ransomMap = new HashMap<Character,Integer>(); for(int i = 0; i < mag.length() -1; i++) { char c = mag.charAt(i); if(!map.containsKey(c)) map.put(c, 1); else{ int value = map.get(c); map.put(c,++value); } } System.out.println(map); for(int i = 0; i < ransom.length()-1; i++ ) { char c = ransom.charAt(i); if(!ransomMap.containsKey(c)) ransomMap.put(c,1); else { int value = (ransomMap.get(c)); ransomMap.put(c,++value); } } System.out.println(ransomMap); } ```