/* * triangle.cpp * * Created on: Oct 18, 2010 * Author: mike * for use in Yale course CPSC 427a, Fall 2010 */ #include "triangle.hpp" // Build the triangle dictionary containing only words // that are part of some non-trivial triangle void Triangle::build(Dictionary& dict) { // Keep all words of minimal length const WordList& wl1 = dict.getWordList(Word::triangle_min); WordList::iterator p; for (p = wl1.begin(); p != wl1.end(); p++) { add(*p); } // Iterate through words in order of increasing length, // keeping each word only if it has a parent in the list // of shorter words. // Set the parent pointer to the first such word for (int k = Word::triangle_min+1; k <= Word::triangle_max; k++) { const WordList& wl1 = dict.getWordList(k); const WordList& wl2 = getWordList(k - 1); for (p = wl1.begin(); p != wl1.end(); p++) { WordEntry* parent = wl2.findParent(*p); if (parent != NULL) { // found parent, so *p in triangle add(*p)->setParent(parent); } } } } // Print triangle beginning with WordEntry start ostream& Triangle::printOneTriangle(ostream& out, const WordEntry& start) const { for (const WordEntry* p = &start; p != NULL; p = p->getParent()) { out << *p << endl; } return out<< endl; } // Print one triangle from each Word::triangle_max-length word that has // at least one triangle ostream& Triangle::print(ostream& out) const { const WordList& wln = getWordList(Word::triangle_max); WordList::iterator q; for (q = wln.begin(); q != wln.end(); q++) { printOneTriangle(out, *q); } return out; }