Randomize one-dimensional array

Source: Internet
Author: User

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.