import structure5.*; import java.io.FileInputStream; import java.util.Scanner; class LetterFreq { /* This hash function just produces the sum of each * letter (converted to an int) mod 26 */ public static int hash(String word) { int sum = 0; for (int i = 0; i < word.length(); i++) { sum += (int)word.charAt(i); } return sum % 26; } /* The purpose of this program is to explore whether * any of the following three hash functions are "good" * when hashing common (US) English words: * 1. The first letter of the word. * 2. The last letter of the word. * 3. The sum of all of the letters of the word, mod 26. */ public static void main(String[] args) { Map first_counts = new Hashtable<>(); Map last_counts = new Hashtable<>(); Map h_counts = new Hashtable<>(); try { Scanner input = new Scanner(new FileInputStream("google-10000-english-usa.txt")); while(input.hasNext()) { // get next word String word = input.next().toLowerCase(); // get last letter of word char last = word.charAt(word.length() - 1); // get first letter of word char first = word.charAt(0); // skip non-English, non-alpha chars if (first >= 97 || first <= 122) { // count first if (!first_counts.containsKey(first)) { first_counts.put(first, 0); } first_counts.put(first, first_counts.get(first) + 1); } // skip non-English, non-alpha chars if (last >= 97 || last <= 122) { // count last if (!last_counts.containsKey(last)) { last_counts.put(last, 0); } last_counts.put(last, last_counts.get(last) + 1); } // count hash int hval = hash(word); if (!h_counts.containsKey(hval)) { h_counts.put(hval, 0); } h_counts.put(hval, h_counts.get(hval) + 1); } } catch (Exception e) { // quit System.out.println("Can't find input!"); System.exit(1); } // first letters for (int i = 97; i < 123; i++) { char c = (char)i; System.out.println(c + "," + first_counts.get(c)); } System.out.println(); // last letters for (int i = 97; i < 123; i++) { char c = (char)i; System.out.println(c + "," + last_counts.get(c)); } System.out.println(); // hash values for (Integer key: h_counts.keySet()) { System.out.println(key + "," + h_counts.get(key)); } } }