Как вы получаете слова из текстового файла, которые имеют длину 9? - PullRequest
2 голосов
/ 07 октября 2019

Мне было интересно, как вы можете просмотреть текстовый файл и получить все слова в этом текстовом файле длиной 9, а затем выбрать любое из этих слов и рандомизировать эти буквы.

book = readWordsFile("misc/word.txt");
std::vector<std::string> text;
for(int i = 0; i<book.size();i++){
if(book[i] == 9) {

return book[i];
}
}

1 Ответ

2 голосов
/ 07 октября 2019

Предполагая, что у вас есть файл words.txt, который представляет собой большой длинный файл слов, разделенных запятыми, например, из популярного курса MOOC здесь : Вы можете сделать что-то вроде этого:

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // random_shuffle
#include <cstdlib> // rand()
using namespace std;

int main() {
    // init rand function
    srand(time(NULL));

    string dictionaryPath = "words.txt"; 
    ifstream ifs(dictionaryPath);
    vector<string> allNineLetterWords;
    char c;
    string word;
    // read words.txt and save 9 letter words into list
    while (ifs.get(c))
    {
        // seperate words by ,
        if (c == ',') {
            // store 9 letter words
            if (word.size() == 9) {
                allNineLetterWords.push_back(word);
            }
            word = "";
        } else {
            word += c;
        }
    }
    ifs.close();

    // randomize
    int randomIndex = rand() % allNineLetterWords.size();
    string originalWord = allNineLetterWords.at(randomIndex);
    string scrambledWord;
    vector<int> indices = {0, 1, 2, 3, 4, 5, 6, 7, 8};
    std::random_shuffle(indices.begin(), indices.end());
    for ( int i = 0 ; i < 9; i++) {
        int randomIndex = indices.at(i);
        scrambledWord += originalWord.at(randomIndex);
    }
    // print original and scrambled word
    cout << originalWord << ", " << scrambledWord << endl;

    return 0;
}

выход:

приводы, crsaotaut

расстегивание молнии, piungzinp

мобилизация, имилсезоб

РЕДАКТИРОВАТЬ:

Если ваша цель состоит в том, чтобы иметь слово-головоломку, похожую на те, что на шоу, такие как Обратный отсчет , Буквы и цифры , Des chiffres et des lettres , гораздо интереснее, если вы выберете только 9-буквенные слова, которые сочетаются, сочетание 4-буквенного и 5-буквенного слова.

Примерно так:

vector<string> findWords(string dictionaryPath, int length) {
    ifstream ifs(dictionaryPath);
    vector<string> allLengthNWords;
    char c;
    string word;
    // read words.txt and save 9 letter words into list
    while (ifs.get(c))
    {
        // seperate words by ,
        if (c == ',') {
            // store 9 letter words
            if (word.size() == length) {
                allLengthNWords.push_back(word);
            }
            word = "";
        } else {
            word += c;
        }
    }
    ifs.close();
    return allLengthNWords;
}

bool twoWordsExistInWord(string firstWord, string secondWord, string largeWord) {
    // check iff all letters of first and second word are in larger word

    // create a dictionary of all letters in largeWord
    std::map<char, int> lettersMap;
    for (int i = 0; i < largeWord.size(); i++)
    {
        if (!lettersMap.count(largeWord.at(i))) {
            lettersMap.insert({largeWord.at(i), 1});
        } else {
            lettersMap[largeWord.at(i)]++;
        }
    }
    for (int i = 0; i < firstWord.size(); i++) {
        if (!lettersMap.count(firstWord[i]))
            return false;
        lettersMap[firstWord.at(i)]--;
    }
    for (int i = 0; i < secondWord.size(); i++) {
        if (!lettersMap.count(secondWord[i]))
            return false;
        lettersMap[secondWord.at(i)]--;
    }

    for (int i = 0; i < lettersMap.size(); i++) {
        if (lettersMap[i])
            return false;
    }
    return true;
}
int main() {

    // init rand function
    srand(time(NULL));

    string dictionaryPath = "words.txt"; 
    vector<string> allNineLetterWords = findWords(dictionaryPath, 9);
    vector<string> allFourLetterWords = findWords(dictionaryPath, 4);
    vector<string> allFiveLetterWords = findWords(dictionaryPath, 5);
    for (int k = 0; k < allNineLetterWords.size(); k++) {
        for (int i = 0; i < allFourLetterWords.size(); i++) {
            for (int j = 0; j < allFiveLetterWords.size(); j++) {
                if (twoWordsExistInWord(allFourLetterWords[i], allFiveLetterWords[j], allNineLetterWords[k])) {
                    std::cout << allNineLetterWords[k] << ", " << allFourLetterWords[i] << allFiveLetterWords[j] << std::endl;
                }
            }
        }
    }


    return 0;
}

Будет производить:

очаровано, acnetrend

женское, среди известных

аэрации, asiatoner

изгнание, coresixes

...

Lol, веселиться!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...