Randomize one-dimensional array
A problem: Assume that there is a one-dimensional integer array that is randomization, even if each element appears randomly in the array, and the probability is the same.
Ii. Solution ideas:
1. Construct two arrays, one secondary array for hash, and the other for retaining the priority. For example, enter 2, 1, 0
Then, the secondary array is 0, 1, 2, that is, the first random generation of an integer within 3, for example, 2. If there is no element at the position of 2, put it. Otherwise, the element is randomly generated again, until all elements in the secondary array are different, put these elements that are not the same into the priority array.
2. Sort the original array by priority.
Code 3
/************************************************************************* > File Name: randomArray.c > Author: ma6174 > Mail: ma6174@163.com > Created Time: Mon 25 Aug 2014 09:44:03 PM CST ************************************************************************/#include
#include
#include
#include
#define random(m) (rand() % m)#define N 10int main() {srand((int)time(0)); // set the seedint array[N]; // input arrayint assist_array[N];int prority[N]; // indicate prority of every element in the arrayint e;int i, j;int tmp, tmp1;for(i = 0;i < N;i++) {assist_array[i] = -1; // initialize}for(i = 0;i < N;i++) {scanf("%d", &array[i]);}for(i = 0;i < N;i++) {e = random(N);if(assist_array[e] == -1) { // if the e is only one assist_array[e] = e;prority[i] = e; // put in the prority}else {i--; // game is continuing}}/* * insert sort in terms of prority * */for(i = 1;i < N;i++) { tmp = prority[i];tmp1 = array[i];j = i - 1;while(j >= 0 && prority[j] > tmp) {array[j + 1] = array[j];j--;}array[j + 1] = tmp1;}printf("random the array is:\n");for(i = 0;i < N;i++) {printf("%d\n", array[i]);}return 0;}
4. Test