为给定的特定情况生成 N 个字符序列的 C++ 程序
这是一个C++程序,用于为给定的特定情况生成N个字符的序列。
算法
Begin function GenerateSequence() generate a Sequence of N Characters for a Given Specific Case: Use rand() for generating random indexes. Store the first character directly into the sequence. If that sequence is used earlier, then it discards that and generates random index again. End
示例
#include#include #include using namespace std; void GenerateSequence(char string[], int n, int l, char *sequence) { int i, j=0, k,in; for(i = 0; i < n; i++) { //将第一个字符直接存储到序列中 if(j == 0) sequence[j++] = string[rand()%l]; else { h: in = rand()%l; for(k = 0; k < j; k++) { if(string[in] == sequence[k]) goto h; } sequence[j++] = string[in]; } } sequence[j] = '\0'; //以空字符结束序列 } int main() { int n, m, l, i; char string[100]; cout<<"输入原始字符串: "; cin>>string; cout<<"\nEnter the number of strings to be generated from the Base string: "; cin>>n; cout<<"\nEnter the length of each string to be generated: "; cin>>m; l = strlen(string); for(i = 0; i < n; i++) { char sequence[m]; GenerateSequence(string, m, l, sequence); cout<<"\nSequence "<输出结果 输入原始字符串: nhooo Enter the number of strings to be generated from the Base string: 7 Enter the length of each string to be generated: 6 Sequence 1: tuanol Sequence 2: itlurp Sequence 3: tonaiu Sequence 4: untlri Sequence 5: liorpt Sequence 6: liusto Sequence 7: luisot