【问题标题】:How can I simplify this program(anagram)?我怎样才能简化这个程序(字谜)?
【发布时间】:2019-11-10 09:31:07
【问题描述】:

这是一种计算字符移位次数的算法。我怎样才能简化这个?

#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
#define SIZE 20
int w[1 << (SIZE + 1)];

【问题讨论】:

  • 如果你有一个工作程序并且只是想要改进它的提示,更好的地方是codereview.stackexchange.com
  • 为了可读性而简化?使用有意义的变量名
  • 在您的代码中添加一些说明算法工作原理的文档。
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议遵循帮助文档中的发布指南。 On topichow to ask 和 ...the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。有关一般问题,请查看Which site?

标签: c++ algorithm anagram


【解决方案1】:

您可以使用 C++ 提供的算法来简化函数。

在下面的示例代码中,我们读取了 2 个字符串,然后旋转一个,并查看它是否等于另一个。我们将重复该操作,直到我们找到匹配项,或者,直到我们检测到不可能进行转换。代码已注释并且应该可以理解。如果没有,请询​​问。

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string string1{};  std::string string2{};
    std::cout << "Enter 2 strings with same number of digits:\n";
    std::cin >> string1 >> string2; // Read strings
    // Strings must have same size
    if (string1.size() == string2.size()) {
        // Countes the number of rotations to the right
        size_t rotateCounter{0};
        do  {
            // If rotated string is equal to original, then we found something
            if (string1 == string2) break;
            // Rotate right
            std::rotate(string1.rbegin(),string1.rbegin()+1,string1.rend());
            // We have done one more rotation
            ++rotateCounter;
        } while(rotateCounter < string1.size());
        // CHeck, if we could find a solution
        if ((rotateCounter == string1.size()) && (string1 != string2))  {
            std::cout << "Total different strings. No rotation transformation possible\n";
        } else {
            std::cout << "Number of right shifts needed: " << rotateCounter << '\n';
        }
    } else {
        std::cerr << "Size of strings not equal\n";
    }
    return 0;
}

编辑:

我用数组创建了第二个版本。我无法想象有人想使用数组的任何原因。也许出于教育目的。但在这里我也会发现它适得其反。反正。请看下文。

请注意std::rotate 也适用于普通数组,就像所有算法一样。

这个不是我自己编译测试过的!

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>

int main()
{
    std::cout << "Enter number of letters for a string: ";
    size_t numberOfLetters{}; std::cin >> numberOfLetters;
    if (numberOfLetters < 1000000)
    {
        // Create Array of char
        char* charArray1 = new char[numberOfLetters];
        char* charArray2 = new char[numberOfLetters];
        // Read the strings
        std::cout << "Enter s strings with excactly " << numberOfLetters << " digits:\n";
        std::string s1{}, s2{}; std::cin >> s1 >> s2;
        // Padding with spaces 
        s1.insert(0, numberOfLetters, ' ');s2.insert(0, numberOfLetters, ' ');

        // Copy the char Array
        s1.copy(charArray1, numberOfLetters);
        s2.copy(charArray2, numberOfLetters);

        // Countes the number of rotations to the right
        size_t rotateCounter{0};
        do  {
            // If rotated string is equal to original, then we found something
            if (0 == std::memcmp(charArray1, charArray2, numberOfLetters)) break;
            // Rotate right
            std::rotate(charArray1,charArray1+numberOfLetters-1,charArray1+numberOfLetters);
            // We have done one more rotation
            ++rotateCounter;
        } while(rotateCounter < numberOfLetters);
        // CHeck, if we could find a solution
        if (std::memcmp(charArray1, charArray2, numberOfLetters))  {
            std::cout << "Total different strings. No rotation transformation possible\n";
        } else {
            std::cout << "Number of right shifts needed: " << rotateCounter << '\n';
        }

        delete [] charArray1;
        delete [] charArray2;
    } else {
        std::cerr << "To many letters\n";
    }
    return 0;
}

最后但并非最不重要。带有纯静态数组和手工旋转算法的版本。

这应该足够了。也许下一次,非常明确的要求会有所帮助。然后我们可以选择正确的解决方案。

#include <iostream>
#include <algorithm>
#include <iterator>

constexpr size_t MaxDigits = 1000000;

char LetterArray1[MaxDigits] {};
char LetterArray2[MaxDigits] {};

// Rotate array one char to the right
inline void rotateRight(char(&arrayToRotate)[MaxDigits], size_t numberOfLetters)
{
    --numberOfLetters;  
    char temp = arrayToRotate[numberOfLetters];
    for (size_t i = numberOfLetters; i > 0; --i) arrayToRotate[i] = arrayToRotate[i - 1];
    arrayToRotate[0] = temp;
}

int main() {
    // Get the number of letters that the user wants to use
    std::cout << "Enter the number of letters:   ";
    size_t numberOfLetters{ 0 }; std::cin >> numberOfLetters;
    // Check input for underflow or overflow
    if (numberOfLetters <= MaxDigits)
    {
        // Now read to strings from the console
        std::cout << "\nEnter  2 strings:\n";
        std::string inputString1{}; std::string inputString2{};
        // Read 2 strings
        std::cin >> inputString1 >> inputString2;
        // If user enters too short string, we would run into trouble. Therefore, pad string with spaces
        inputString1 += std::string(numberOfLetters, ' ');
        inputString2 += std::string(numberOfLetters, ' ');

        // Copy strings to array
        inputString1.copy(LetterArray1, numberOfLetters);
        inputString2.copy(LetterArray2, numberOfLetters);

        // So, now we have the 2 strings in our arrays
        // We will rotate Array1 and compare the result with Array 2. And we count the number of shifts
        bool matchFound{ false };
        size_t rotateCounter{ 0 };
        while (!matchFound && (rotateCounter < numberOfLetters))
        {
            if (0 == std::memcmp(LetterArray1, LetterArray2, numberOfLetters)) {
                matchFound = true; break;
            }
            rotateRight(LetterArray1, numberOfLetters);
            ++rotateCounter;
        }
        if (matchFound)     {
            std::cout << "\nNecessary rotations: " << rotateCounter << '\n';
        }
        else {
            std::cout << "\nNo Match Found\n";
        }
    }
    else {
        std::cerr << "***** Number of letters entered is to big. Max allowed: " << MaxDigits << '\n';
    }
    return 0;
}


【讨论】:

  • 好的,但我应该使用数组和变量 n(表示字母数)。 n &lt; 1000 000
  • FWIW,reqs 中给出的最大值表明 OP 的老师期望 not 使用动态分配(而是像问题中所示的那样使用静态存储数组)。不是我会那样做。但是,嘿。
  • 哦,我插入n = 4, inputString1 = AACB and inputString2 = BACA。结果是“未找到”,但应该是 output: 4
  • 嗯?我不明白。我们如何通过旋转将 AACB 转换为 BACA?逻辑是什么?请 ss: AACB --> BAAC --> CBAA --> ACBA --> AACB
猜你喜欢
  • 2013-05-13
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2022-12-11
  • 2011-01-26
  • 1970-01-01
相关资源
最近更新 更多