C++ Programming Code Examples C++ > Beginners Lab Assignments Code Examples Program to Generate Random Partition out of a Given Set of Numbers or Characters Program to Generate Random Partition out of a Given Set of Numbers or Characters - This algorithm generates a random partition of the given set of characters or integers. - The time complexity of this algorithm is O(n). - This algorithm takes the input of a set of integers or characters. - It firstly generates the random partition of the length of the set. - Then starting from the beginning, it prints the number of element from the beginning, mentioned in the partition. - Exit. #include<iostream> #include<stdlib.h> #include<string.h> using namespace std; int main() { int n, x, j, l, ch; // Enter choice. cout<<"Enter 1 for string and 2 for integer array to generate array: "; cin>>ch; if(ch == 1) { char str[100]; cout<<"Enter the string: "; cin>>str; n = strlen(str); cout<<"\nThe random partition of the given string is: \n"; // Generate the random partition. l = 0; while(n > 0) { // Generate a random number from 1 to n. cout<<"\t{ "; x = rand()%n + 1; // Reduce the given number by x. n = n-x; // Print the first x characters from the 'l' counter. for(j = 0; j < x; j++) { cout<<str[l]<<" "; l++; } cout<<"}"; } } else { cout<<"\nEnter the number of element in the integer array: "; cin>>n; int arr[n]; cout<<"\nEnter the elements of the array: \n"; for(x = 0; x < n; x++) { cout<<"Enter "<<x+1<<" element: "; cin>>arr[x]; } cout<<"\nThe random partition of the given array is: \n"; // Generate the random partition. l = 0; while(n > 0) { // Generate a random number from 1 to n. cout<<"\t{ "; x = rand()%n + 1; // Reduce the given number by x. n = n-x; // Print the first x numbers from the 'l' counter. for(j = 0; j < x; j++) { cout<<arr[l]<<" "; l++; } cout<<"}"; } } return 0; }