import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;

/**
 * Implements the AdjacencyGraph interface by reporting any words that differ
 * by one letter as adjacent.
 *   @author Dave Reed
 *   @version 11/11/11
 */
public class DictionaryGraph implements AdjacencyGraph<String> {
    private ArrayList<String> dictionary;
    
    public DictionaryGraph(String fileName) {
       this.dictionary = new ArrayList<String>();
       try {
            Scanner infile = new Scanner(new File(fileName));
            while (infile.hasNext()) {
                this.dictionary.add(infile.next());
            }
        }
        catch (java.io.FileNotFoundException e) {
            System.out.println("DICTIONARY FILE NOT FOUND");
        } 
    }
    
    public boolean contains(String word) {
        return this.dictionary.contains(word);
    }
    
    public Set<String> adjacencies(String word) {
        Set<String> adjSet = new HashSet<String>();
        for (String nextWord : this.dictionary) {
            if (differByOne(nextWord, word)) {
                adjSet.add(nextWord);
            }
        }
        return adjSet;
    }
    
    /////////////////////////////////////////////////////////////////
    
    private boolean differByOne(String word1, String word2)
    {
	    if (word1.length() != word2.length()) {
            return false;
        }

        int diffCount = 0;
	    for (int i = 0; i < word1.length(); i++) {
		    if (word1.charAt(i) != word2.charAt(i)) {
			    diffCount++;
		    }
	    }
	    return (diffCount == 1);
    }
    
    public static void main(String[] args) {
        DictionaryGraph wg = new DictionaryGraph("dictionary.txt");
        System.out.println(wg.contains("shale"));
        System.out.println(wg.adjacencies("shale"));
    }
}
