从给定的一组数字或字符中生成随机分区的 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<<"为整数输入 1,为字符数组输入 2 以生成数组: ";
   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<<"输入字符: ";
      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;
}
输出结果
为整数输入 1,为字符数组输入 2 以生成数组: 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 ]
输出结果
为整数输入 1,为字符数组输入 2 以生成数组: 2
输入字符: 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 ]