Please help. The program for generating random numbers is not working
I am writing a program which have to generate N random not repeating numbers
the prototype should be voidrandom_int(int array[], int N); it is not having any errors but it is not workin开发者_开发知识库g. Not even giving any number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void random_init(int array[], int N)
{
   srand(time(NULL));
   int i, j;
   array[0]=rand()%N;
   for(i=1;i<N;i++)
   {
       array[i]=rand()%N;
       if(array[i]==0)
           array[i]=1;
       for(j=0;j<i;j++)
       {
           if(array[i]==array[j])
           break;
       }
       if((i-j)==1)
           continue;
       else
           i--;
   }
}
int main(void)
{
    int a[5], i, N;
    N=5;
    random_init(a,N);
    for(i=0;i<N;i++)
    printf("%d    ", a[i]);
    return 0;
}
- This part makes no sense: - if(array[i]==0) array[i]=1;- It will limit your choices to N-1 numbers (1 to N-1), out of which you try to find N numbers without repetition - leading to an infinite loop. 
- if((i-j)==1) continue;- Here you probably want - if (i==j)instead, to check if the previous loop ran to completion.
A faster and simpler way to generate the numbers 0..N-1 in a random order, is to put these numbers in an array (in sequential order), and then use Fisher-Yates Shuffle to shuffle the array.
This method is biased. Do not use it other than for educational purposes.
Other than Ficher-Yates, which uses another array, you can use the method of going through all the available numbers and find a "random" spot for them (effectively "initializing" the array twice). If the spot is taken, choose the next one. Something like this, in pseudo-code:
fill array with N
for all numbers from 0 to N-1
    find a random spot
    while spot is taken (value is N) consider next spot /* mind wrapping */
    set value in current spot
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论