随机打印"0" "1" "2",但保证"0" "1" "2"出现的概率是可配置的的,例如
2:1:3
note:程序要求的输入格式也是a:b:c
主要思路是先int A[a+b+c] = {a个0,b个1,c个2}...再在数组中不重复的随机取数
a*n : b*n : c*n
就在对A数组操作n次而已
#include <stdio.h> #include <stdlib.h> #include <time.h>
void swap(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; }
void process_A(int A[], int num0, int num1, int num2) { int i; int num; int total = num0+num1+num2; for(i=0;i<num0;i++) A[i] = 0; for(i=0;i<num1;i++) A[num0+i] = 1; for(i=0;i<num2;i++) A[num0+num1+i] = 2; for(i=0;i<total;i++) { num = rand()%(total-i)+i; swap(A+i, A+num); } }
void print_array(int A[], int total) { int i = 0; for(;i<total;i++) printf("%d\t", A[i]); printf("\n"); }
int main(int argc, char *argv[]) { int num0; int num1; int num2; srand((unsigned int)time(NULL)); while(1) { printf("Please input the ratio:\n"); scanf("%d:%d:%d",&num0,&num1,&num2); //printf("%d:%d:%d\n",num0, num1, num2);
int* A = (int*)malloc(sizeof(int)*(num0+num1+num2)); process_A(A, num0, num1, num2); print_array(A, num0+num1+num2); free(A); A=NULL; } system("PAUSE"); return 0; }
|
阅读(693) | 评论(0) | 转发(0) |