Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

c - how to make a random generation number between 1 to 9 without repitition

i search about this issue in site and one of them help me a little. i want to make a puzzle with random number between 1 to 9 and i use this method :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()  {
   int i = 1, num[9] = {1,2,3,4,5,6,7,8,9}, k = 1;

   srand(time(NULL));
   for (i = 1; i < 10; i++) {
      num[i] = i;
   }
   for (i = 1; i < 10; i++) {
      int j = i + rand()%(10 - i);
      int temp = num[i];
      num[i] = num[j];
      num[j] = temp;

      if ((i - 1) % 3 == 0)
      {
         printf(" %i: ", k);
         k++;
      }


      printf(" %i", num[i]);

      if (i % 3 == 0)
      {
         printf("
");
      }
   }
   return 0;
}

but i have a problem with this code.it makes the two last number same!!! can any one help me ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can generate a unique range of random numbers like this. It works by creating a pool of all the available numbers, selects one at random, and then removes that number from the pool. The same method could be used for dealing a deck of cards, without the need to explicitly shuffle.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE   9                   // range of numbers

int main() {
    int pool[RANGE];
    int size, n;
    for (size=0; size<RANGE; size++) {
        pool[size] = size+1;        // create number pool 1...
    }
    srand((unsigned)time(NULL));
    while (size) {                  // generate random sequence
        n = rand() % size;          // random array index
        printf("%d ", pool[n]);     // select number from pool
        pool[n] = pool[--size];     // remove from pool
    }
    printf("
");
    return 0;
}

Here too is a debugged version of your program. Apart from bad array indexing, your mistake was to print from the array before the randomizing was finished.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()  {
    int i = 1, num[9] = {1,2,3,4,5,6,7,8,9};

    srand((unsigned)time(NULL));
    for (i=0; i<9; i++) {
        int j = rand() % 9;
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }

    for (i=0; i<9; i++) {
        if (i % 3 == 0)
            printf("
 %d: ", 1+i/3);
        printf(" %i", num[i]);
    }
    printf("
");
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...