从给定的一组数字或字符中生成随机分区的 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#include #include 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 "<>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<>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< 输出结果 为整数输入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 ]