นี่คือโปรแกรม C++ สำหรับสร้าง Random Partition (การแบ่งแบบสุ่ม) จากชุดตัวเลขหรือตัวอักษรที่กำหนด
อัลกอริทึม
เริ่มต้น รับจำนวนเต็มหรือตัวอักษรเป็นอินพุต สำหรับตัวเลือก 1: รับอินพุตอาร์เรย์จำนวนเต็ม n ตัว กำหนด l = 0 เพื่อท่องอาร์เรย์ ใช้ rand() สร้างการแบ่งจำนวนเต็มแบบสุ่มของ n สำหรับแต่ละ partition i พิมพ์ i จำนวนเต็มถัดไปจากดัชนี l สำหรับตัวเลือก 2: รับอินพุตสตริงใน ch[] คำนวณความยาวสตริงและกำหนด l เป็น 0 จะท่องสตริง สร้างการแบ่งจำนวนเต็มแบบสุ่มของความยาวสตริง สำหรับแต่ละ partition i พิมพ์ i ตัวอักษรถัดไปจากดัชนี l จบ
ตัวอย่างโค้ด
#include<iostream> #include<stdlib.h> #include<string.h> using namespace std; int main() { int n, i, j, l, c; cout<<"Enter 1 for integer and 2 for character array to generate array: "; cin>>c; //สำหรับตัวเลือก 1: if(c== 1) { cout<<"\nEnter the number of element in the integer array: "; cin>>n; int a[n]; cout<<"\nEnter the elements of the array: \n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; } cout<<"\nThe random partition of the given array is: \n"; l = 0; while(n > 0) { cout<<"\t["; i = rand()%n + 1; n = n-i; for(j = 0; j < i; j++) { cout<<a[l]<<" "; l++; } cout<<"]"; } } //สำหรับตัวเลือก 2: else { char ch[100]; cout<<"Enter the characters: "; cin>>ch; n = strlen(ch); cout<<"\nThe random partition of the given string is: \n"; l = 0; //กำหนด l= 0 เพื่อท่องอาร์เรย์ while(n > 0) { cout<<"\t[ "; i = rand()%n + 1; n = n-i; for(j = 0; j < i; j++) { cout<<ch[l]<<" "; l++; } cout<<"]"; } } return 0; }
ผลลัพธ์
Enter 1 for integer and 2 for character array to generate array: 1 Enter the number of element in the integer array: 10 Enter the elements of the array: Enter 1 element: 10 Enter 2 element: 9 Enter 3 element: 8 Enter 4 element: 7 Enter 5 element: 6 Enter 6 element: 5 Enter 7 element: 4 Enter 8 element: 3 Enter 9 element: 2 Enter 10 element: 1 The random partition of the given array is: [10 9 ] [8 7 6 5 ] [4 3 2 ] [1 ]
ผลลัพธ์
Enter 1 for integer and 2 for character array to generate array: 2 Enter the characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ The random partition of the given string is: [ A B C D E F G H I J K L M N O P ] [ Q R S T U V W X ] [ Y ] [ Z ]