Home > Back-end >  I want to make this program more quickly
I want to make this program more quickly

Time:07-21

I was made this program This program makes array which each digit is different but it takes so much time

void generateArr() {
    int randomNum;
    int sameNum = 0;
    for (int i = 0; i < arrScale; i  ) {
        while (true)
        {
            sameNum = 0;
            srand((unsigned int)time(NULL));
            randomNum = rand() % 10;
            for (int j = 0; j < arrScale; j  ) {
                if (numArr[j] == randomNum) {
                    sameNum = 1;
                }
            }
            if (sameNum == 0) {
                break;
            }
        }
        numArr[i] = randomNum;
    }
}

numArr and arrScale is made in front

CodePudding user response:

First: Don't call srand more than once per program run. Here's why

In order to speed up generating the numbers, you could make sure that you never pick a number that's been picked before.

Example:

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void generateArr() {
    static int numbers[10] = {0,1,2,3,4,5,6,7,8,9};

    for (int i = 0; i < arrScale; i  ) {
        int pos = rand() % (10-i);
        numArr[i] = numbers[pos];
        swap(&numbers[pos], &numbers[10-i-1]);
    }
}

CodePudding user response:

You can have a separate buffer t of size 10 and whenever you draw x, set t[x] to 1. So you can evaluate t[x] == 1 to check if x is already in your array and don't have to loop over it.

Note that your program won't work if your array has size greater than 10.

  •  Tags:  
  • c
  • Related