Coding_for_Crosswords_in_Py.../a.c

124 lines
2.4 KiB
C

#include <iostream> // library for printing
#include <string> // support for strings
#include <vector> // support for vectors
#include <assert.h>
#include <fstream> // support for reading files
using namespace std;
// For compiling C++ code
// g++ a.c -o a
class Library {
public:
void ComputeStats() {
assert(counts.empty());
counts.resize(18);
for (string s : words) {
int len = s.length();
if (len < 18) {
counts[len]++;
}
}
}
void PrintStats() const {
cout << "Here are the counts of each word length:\n";
for (int i=1; i<counts.size(); i++) {
cout << "[" << i << "] " << counts[i] << "\n";
}
}
string GetWord(int i) const {
assert(i >= 0 && i < words.size());
return words[i];
}
void ReadFromFile(string filename) {
ifstream f;
f.open(filename);
while (!f.eof())
{
string line;
getline(f, line);
// cout << line << "\n";
if (!line.empty())
{
int len = line.length();
if (line[len-1] == '\r') {
line = line.substr(0, len-1);
}
words.push_back(line);
}
}
cout << "Read " << words.size() << " words from file '"
<< filename << "'\n";
}
private:
vector<string> words;
vector<int> counts;
};
struct Grid
{
Grid(string n)
{
name = n;
}
int rows() const { return lines.size(); }
int cols() const
{
if (lines.empty())
{
return 0;
}
else
{
return lines[0].size();
}
}
void LoadFromFile(string filename)
{
ifstream f;
f.open("test");
while (!f.eof())
{
string line;
getline(f, line);
// cout << line << "\n";
if (!line.empty() && line[0] != '#')
{
lines.push_back(line);
}
}
}
void Check() const
{
for (string s : lines)
{
assert(s.size() == cols());
}
}
void Print() const
{
cout << "Grid: " << name
<< " (rows=" << rows()
<< ", cols=" << cols() << ")\n";
for (string s : lines)
{
cout << " " << s << "\n";
}
}
string name; // string are initialized empty
vector<string> lines;
};
int main()
{
Library lib;
lib.ReadFromFile("top_12000.txt");
lib.ComputeStats();
lib.PrintStats();
//Grid grid("MY GRID");
//grid.LoadFromFile("test");
//grid.Check();
//grid.Print();
}