C++ 程序,从给定数字或字符集中生成随机分区


这是一个 C++ 程序,它可以从给定的数字或字符集中生成随机分区。

算法

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

示例

#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;
}

输出

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 ]

更新于:2019 年 7 月 30 日

233 次浏览

开启你的职业生涯

完成本课程即可获得认证

开始学习
广告