1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
// -- crosswordhelper.cpp - Find words that match a pattern.
// Reads dictionary from local file "words.dict", then
// reads patterns from user and lists all words that match
// the pattern. Patterns are simply either a lowercase
// letter which must match or a dot which will match
// anything. Eg, "..able" with match "doable", "liable", ...
// Making this more efficient is an interesting problem.
// Fred Swartz - 2002-09-24
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
bool match(string pat, string w); //--- prototype
//============================================================= main
int main() {
string word; // holds each input word as we read it
vector<string> dictionary;
string pattern; // pattern as entered by user
//--- read dictionary
ifstream dictInput;
dictInput.open("word.list");
if (!dictInput) {
cerr << "Unable to open word.list file" << endl;
exit(1);
}
int n = 0;
while (dictInput >> word) {
dictionary.push_back(word);
if (n++%10000 == 0) {
cout << '.';
}
}
cout << endl << "Dictionary size = " << n << endl;
cout << "Enter your patterns, one per line." << endl;
//--- read patterns and try to match them in dictionary.
while (cin >> pattern) {
int numberOfMatches = 0;
for (int i=1; i<n; i++) {
if (match(pattern, dictionary[i])) {
cout << "Found " << dictionary[i] << endl;
numberOfMatches++;
}
}
cout << "Number of matches: " << numberOfMatches << endl;
cout << "Enter another pattern" << endl;
}
return 0;
}//end main
//========================================================= match
bool match(string pat, string w) {
int len = pat.size();
if (w.size() != len) return false;
for (int i=0; i<len; i++) { //--- look for mismatches
if (pat[i] != '.') {
if (pat[i] != w[i]) {
return false;
}
}
}
return true; // no mismatches in this word.
}//end match |