单词解密程序 - C++

Word Unscrambling Program - C++

本文关键字:C++ 程序 解密 单词      更新时间:2023-10-16

嗨,我正在开发一个程序来解密一组字母并输出可以从该组字母组成的所有单词,例如: 如果我输入字母"vlei",程序将输出"live"、"evil"和"vile"。

到目前为止,我已经在互联网上查看了一下这个quiiiite,在这一点上找不到与我的技能水平(2级菜鸟)相关的任何具体问题。

到目前为止,我已经从给定的字母中进行了所有可能的组合。排除任何少于 7 个字母的内容,这是一个问题。

这是我到目前为止的代码:

string letter;
char newWord[7];
    int main()
{
cout << "Type letters here: ";
cin >> letter;

for(int i = 0 ; i < 7 ; i++)
{   
    for(int j = 0 ; j < 7 ; j++)
    {
        for(int k = 0 ; k < 7 ; k++)
        {
            for(int l = 0 ; l < 7 ; l++)
            {
                for(int m = 0 ; m < 7 ; m++)
                {
                    for(int n = 0 ; n < 7 ; n++)
                    {
                        for(int o = 0 ; o < 7 ; o++)
                        {
                            sprintf(newWord, "%c%c%c%c%c%c%c", letter[i], letter[j], letter[k], letter[l], letter[m], letter[n], letter[o]);
                        }
                    }
                }
            }
        }
    }
}
return 0;
}

我想知道是否有人对这样的事情有任何经验,并且可以提供提示或建议。

具体来说,我遇到的困难是如何阅读.txt文件以用作字典来比较单词。此外,我在使用strcmp()时遇到问题,这是我计划用来将打乱的单词与字典进行比较的方法。因此,如果有任何其他更简单的方法来比较两个字符串,我们将不胜感激。

提前谢谢。


大家好,所以我刚刚完成了我的程序,我希望它可以帮助其他人。非常感谢您的帮助。

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <array>
using namespace std;

//declaring variables
int i;
int scores[531811]; //array for scores of found words
string wordlist[531811]; //array for found matched words
string word[531811]; //array of strings for dictionary words about to be read it
string tester;//string for scrambled letters that will be read in
int scorefinder(string scrab) //SCORE FINDER FUNCTION
{
    int score = 0;
    int x = 0;
    int j = 0;
    while (scrab[j])
    {
        char ltr = toupper(scrab[j]); //converts to all caps
        //assings values to each letter and adds it to itself
        if(ltr == 'A' || ltr == 'E' || ltr == 'I' || ltr == 'L' || ltr == 'N' || ltr == 'O' || ltr == 'R' || ltr == 'S' || ltr == 'T' || ltr == 'U')
            x += 1;
        else if(ltr == 'D' || ltr == 'G')
            x += 2;
        else if(ltr == 'B' || ltr == 'C' || ltr == 'M' || ltr == 'P')
            x += 3;
        else if(ltr == 'F' || ltr == 'H' || ltr == 'V' || ltr == 'W' || ltr == 'Y')
            x += 4;
        else if(ltr == 'K')
            x += 5;
        else if(ltr == 'J' || ltr == 'X')
            x += 8;
        else if(ltr == 'Q' || ltr == 'Z')
            x += 10;
        ++j;
    }
    score = x;
    return score;
}
int main () {
//READS IN DICTIONARY
    ifstream file("words.txt"); //reads in dictionary
    if (!file.is_open()){ //checks if file is being NOT read correctly
        cout << "BROEKN n"; //prints error message if so
    }
    if(file.is_open()){ //checks if file IS being read correctly
        for(int i = 0; i < 531811; i++){ 
            file >> word[i]; //read in each word from the file and 
        }   //assigns each to it's position in the words array
    }
//END OF READ IN DICTIONARY
    cout << "Enter scrambled letters: ";
    cin >> tester; //reads in scrambled letters
    sort(tester.begin(),tester.end()); //sorts scrambled letters for next_permutation
    while (next_permutation(tester.begin(),tester.end())){  //while there are still permutations available
        for(i=0;i<531811;i++){
            if ( is_permutation (word[i].begin(),word[i].end(), tester.begin())){
                wordlist[i] = word[i]; //assigns found word to foundword array
                scores[i] = scorefinder(word[i]); //assigns found word score to foundscore array
            }
        }
    }
    //PRINTS OUT ONLY MATCHED WORDS AND SCORES
    for(i=0;i<531811;i++){
        if(scores[i]!=0){
            cout << "Found word: " << wordlist[i] << " " << scores[i] << "n";
        }
    }
}

好吧,你需要的是某种比较。C++不知道,英语中的正确单词是什么。所以你可能需要一个词表。然后你可以蛮力(这就是你目前正在做的事情),直到你找到匹配。

为了比较你的粗暴结果,你可以使用一个.txt,尽可能多地使用你能找到的英语单词。然后,您必须使用FileStream来遍历每个单词并将其与您的暴力结果进行比较。

在你成功地解开了一个词之后,你应该再次考虑你的解决方案。如您所见,您仅限于特定数量的字符,这不是那么好。

对于初学者来说,这听起来像是一个有趣的任务;)

假设您在Internet上找到了一个纯文本文件形式的单词列表,您可以先将所有单词加载到字符串的向量中。

ifstream word_list_file("word_list.txt");
string buffer;
vector<string> all_words;
while (getline(word_list_file, buffer))
    all_words.push_back(buffer);

然后我们要将输入字母与 all_words 的每个条目进行比较。我建议使用std::is_permutation.无论顺序如何,它都会比较两个序列。但是当两个序列的长度不同时可能会有问题,所以先自己比较长度。

// Remember to #include <algorithm>
bool match(const string& letters, const string& each_word)
{
    if (letters.size() != each_word.size())
        return false;
    return is_permutation(begin(letters), end(letters), begin(each_word));
}

请注意,我还没有测试我的代码。但这就是想法。


回复评论的编辑:

简而言之,只需使用std::string,而不是std::array。或者直接复制我的match函数,并调用它。这对您的情况来说会更容易。

详:

std::is_permutation可以与任何容器和任何元素类型一起使用。例如:

#include <string>
#include <array>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//Example 1
    string str1 = "abcde";
    string str2 = "ecdba";
    is_permutation(begin(str1), end(str1), begin(str2));
//Example 2
    array<double, 4> array_double_1{ 4.1, 4.2, 4.3, 4.4 };
    array<double, 4> array_double_2{ 4.2, 4.1, 4.4, 4.3 };
    is_permutation(begin(array_double_1), end(array_double_1), begin(array_double_2));
//Example 3
    list<char> list_char = { 'x', 'y', 'z' };
    string str3 = "zxy";
    is_permutation(begin(list_char), end(list_char), begin(str3));
// Exampl 4
    short short_integers[4] = { 1, 2, 3, 4 };
    vector<int> vector_int = { 3, 4, 2, 1 };
    is_permutation(begin(list_char), end(list_char), begin(str3));
    return 0;
}
  • 示例 1 使用 std::string 作为 char 的容器,这正是我的 match 函数的工作方式。
  • 示例 2 使用大小为 4 的 double 的两个array
  • 示例 3 甚至使用两种不同类型的容器,具有相同的元素类型。(你听说过"std::list"吗?没关系,先关注我们的问题。
  • 示例 4 更奇怪。一个容器是旧式原始数组,另一个是std::vector。还有两种元素类型,shortint ,但它们都是整数。(shortint之间的确切区别在这里无关紧要。

然而,所有四种情况都可以使用 is_permutation .非常灵活。

灵活性是由以下事实实现的:

  1. is_permutation不完全是一个函数。它是一个函数模板,它是一种语言功能,用于根据您传递给它的数据类型生成新函数。
  2. 容器和is_permutation算法彼此不认识。它们通过称为"迭代器"的中间人进行通信。beginend 函数一起为我们提供了一对表示元素"范围"的迭代器。

需要更多的研究来理解这些事实。但总体思路并不难。此外,这些事实也适用于标准库中的其他算法。

试试这个:

# include <stdio.h>
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n) 
{
   int j; 
   if (i == n)
     printf("%sn", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }
} 
/* Driver program to test above functions */
int main()
{
   char a[] = "vlei";  
   permute(a, 0, 3);
   getchar();
   return 0;
}