Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Generate Random Partition out of a Given Set of Numbers or Characters
This is a C++ program to generate Random Partition out of a given set of numbers or characters.
Algorithm
Begin Take the integers or characters as input. For choice 1: Take the input of the n integer array. Assign l = 0 to traverse the array. Using rand(), generate random integer partition of n. For each partition i, print next i integer from index value l. For choice is 2: Take the input of a string in ch[]. Calculate the length of the string and assign l to 0, it will traverse the string. Generate random integer partition of the length of the string. For each partition i, print next i characters from index value l. End
Example
#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;
//For choice 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<<"]";
}
}
//For choice is 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; //Assign l= 0 to traverse the array.
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;
}
Output
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 ]
Output
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 ]
Advertisements