@Override public List<List<Node<String>>> search() { boolean canStart = checkWords(wordsPair); canStart &= checkDictionary(dictionary); if (!canStart) { return null; } Tree.Node<String> root = new Tree.Node<>(); root.setData(wordsPair[0]); Tree<String> tree = new Tree<>(); tree.setRootElement(root); String word = root.getItem(); dictionary.remove(word); Node<String> currentNode = root; List<Node<String>> nodes = new ArrayList<>(); while (!word.equals(wordsPair[1]) && currentNode != null) { // потенциальные слова List<String> words = generateCandidates(word); // отсекаем слова, которых нет в словаре for (Iterator<String> iterator = words.iterator(); iterator.hasNext(); ) { String s = iterator.next(); if (!dictionary.contains(s)) { iterator.remove(); } } // удаляем полученные слова из словаря (для исключения цикличности поиска) for (String c : words) { if (!c.equals(wordsPair[1])) { dictionary.remove(c); } } // формируем очередной уровень дерева for (String c : words) { Node<String> n = new Node<>(c); currentNode.addChild(n); if (c.equals(wordsPair[1])) { nodes.add(n); } } currentNode = tree.getNextElement(currentNode, !nodes.isEmpty()); if (currentNode != null) { word = currentNode.getItem(); } else if (nodes.isEmpty()) { return null; } } return tree.getPaths(nodes); }
public static void main(String[] args) throws IOException { PrintWriter out = null; if (args.length < 1) { System.err.println("Usage: java Filter input [output]"); System.exit(2); // POSIX } else if (args.length < 2) // Optional arg: use stdout if no output file given. out = new PrintWriter(System.out); else // Wrap a BufferedWriter around the FileWriter as it may be costly. out = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); StreamTokenizer tokenizer = null; String res = resourceLoc(args[0]); try { tokenizer = new StreamTokenizer(new FileReader(res)); tokenizer.lowerCaseMode(true); } catch (FileNotFoundException e) { System.err.printf("Input file %s was not found.\n", res); System.exit(-1); } Dictionary dictionary = new Dictionary(); while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if (tokenizer.ttype == StreamTokenizer.TT_WORD && dictionary.contains(tokenizer.sval)) out.println(tokenizer.sval); } out.close(); }