นี่คือโปรแกรม C++ สำหรับสร้างลำดับ N ตัวอักษรสำหรับกรณีเฉพาะ
อัลกอริทึม
เริ่มต้น ฟังก์ชัน GenerateSequence() สร้างลำดับ N ตัวอักษรสำหรับกรณีเฉพาะ: ใช้ rand() สำหรับสร้างดัชนีแบบสุ่ม เก็บตัวอักษรแรกโดยตรงเข้าในลำดับ ถ้าลำดับนั้นเคยใช้ไปแล้ว ให้ทิ้งและสร้างดัชนีสุ่มใหม่ จบ
ตัวอย่างโค้ด
#include<iostream> #include<stdlib.h> #include<string.h> 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++) { //เก็บตัวอักษรแรกโดยตรงเข้า sequence 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'; //จบลำดับด้วย null character } int main() { int n, m, l, i; char string[100]; cout<<"Enter the original string: "; 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 "<<i+1<<": "<<sequence; } return 0; }
ผลลัพธ์
Enter the original string: tutorialspoint 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