Words from neighbour ones: Difference between revisions

Content added Content deleted
(C code efficiency improved)
(C++ code efficiency improvement)
Line 187: Line 187:


=={{header|C++}}==
=={{header|C++}}==
{{libheader|Boost}}
<lang cpp>#include <algorithm>
<lang cpp>#include <algorithm>
#include <cstdlib>
#include <cstdlib>
Line 194: Line 195:
#include <string>
#include <string>
#include <vector>
#include <vector>
#include <boost/circular_buffer.hpp>


// The input file must consist of one word per line in alphabetical order.
int main(int argc, char** argv) {
int main(int argc, char** argv) {
const int min_length = 9;
const int min_length = 9;
Line 204: Line 207:
}
}
std::string line;
std::string line;
std::vector<std::string> words;
boost::circular_buffer<std::string> words(min_length);
while (getline(in, line)) {
if (line.size() >= min_length)
words.push_back(line);
}
std::sort(words.begin(), words.end());
std::string previous_word;
std::string previous_word;
int count = 0;
int count = 0;
while (getline(in, line)) {
for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {
if (line.size() < min_length)
continue;
words.push_back(line);
if (words.size() < min_length)
continue;
std::string word;
std::string word;
word.reserve(min_length);
word.reserve(min_length);
for (size_t j = 0; j < min_length; ++j)
for (size_t i = 0; i < min_length; ++i)
word += words[i + j][j];
word += words[i][i];
if (previous_word == word)
if (previous_word == word)
continue;
continue;
auto w = std::lower_bound(words.begin(), words.end(), word);
auto it = std::find(words.begin(), words.end(), word);
if (w != words.end() && *w == word)
if (it != words.end())
std::cout << std::setw(2) << ++count << ". " << word << '\n';
std::cout << std::setw(2) << ++count << ". " << word << '\n';
previous_word = word;
previous_word = word;