排列问题
Permutation Issue
所以我这里有一个程序,它应该打印到用户输入单词的排列,长度可以是 4 到 10 个字符,并且应该有与单词中的字母一样多的排列。我几乎取得了完全的成功,但有一个问题。当它打印排列时,在第一个大约 2 个排列之后,它开始不使用所有字母和/或同一个字母两次。
例如,如果用户输入的单词是"bill",则输出如下:
llib illb ibll lbii
第四个显然是不正确的。对于具有更多字母的单词,问题更为明显。我需要它只使用它有一次的字母。如何在代码中解决此问题?这是我的代码。
int main(void)
{
string word;
string randword;
string reverse;
int length;
int i = 0;
int j = 0;
string randCH;
cout << "Enter any word 4 to 10 letters in length: ";
cin >> word;
//Checks if word is less than 4 or greater than 10
while (1)
{
/*The code here is in the final program and I know it works. The problem is not here*/
}
length = word.length();
//Uses reverse function
reverse = reverseit(word);
/*reverseit is a function outside of main that makes the word backwards*/
//Prints all permutations
cout << endl << reverse << " ";
for (i = 0; i < word.length() - 1; i++)
{
for (j = 0; j < word.length(); j++)
{
randCH = word.substr(rand() % length, 1);
cout << randCH;
}
cout << " ";
cout << endl;
您可以使用已经构建的std::next_permutation
来实现此目的:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string word;
cin >> word;
sort(word.begin(),word.end());
do {
cout << word <<endl;
} while(next_permutation(word.begin(),word.end()));
}
相关文章:
- 警告处理为错误这里有什么问题
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 为什么不;名字在地图上是按顺序排列的吗
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 重新排列数组的行和列时出现问题
- 问题 - 递归函数以返回文本文件排列
- 排列函数和交换字符串值的问题
- iomanip有问题,专栏没有按我预期的方式排列
- 如何随机排列数组问题
- 排列问题
- c++中生成排列中的递归问题
- 关于歧义排列的代码问题
- 字符串实现的排列问题