Wednesday, 22 November 2017

C++ Program to Generate Random Partition out of a Given Set of Numbers or Characters


Code:

#include   iostream
#include   stdlib.h
#include   string.h

using namespace std;

int main()
{
int n, i, 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{ ";
i = rand()%n + 1;
// Reduce the given number by i.
n = n-i;
// Print the first i characters from the 'l' counter.
for(j = 0; j < i; j++)
{
cout<
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(i = 0; i < n; i++)
{
cout<<"Enter "<
cin>>arr[i];
}

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{ ";
i = rand()%n + 1;
// Reduce the given number by i.
n = n-i;
// Print the first i numbers from the 'l' counter.
for(j = 0; j < i; j++)
{
cout<
l++;
}
cout<<"}";
}
}
return 0;
}


Output:

Case 1:
Enter 1 for string and 2 for integer array to generate array: 2

Enter the number of element in the integer array: 10

Enter the elements of the array:
Enter 1 element: 0
Enter 2 element: 1
Enter 3 element: 2
Enter 4 element: 3
Enter 5 element: 4
Enter 6 element: 5
Enter 7 element: 6
Enter 8 element: 7
Enter 9 element: 8
Enter 10 element: 9

The random partition of the given array is:
        { 0 1 } { 2 3 4 5 }     { 6 7 8 }       { 9 }


Case 2:
Enter 1 for string and 2 for integer array to generate array: 1
Enter the string: 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 }




More C++ Programs:















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...