-4

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

DIA_YA
  • 1
  • 2
  • What do you mean by each digit is different? why do you use random? can you add an example of input and output please? – Axeltherabbit Jul 21 '22 at 09:14
  • 4
    Don't call `srand` more than once during the whole program execution. Not only is it "wrong" - it also makes the program slower. – Ted Lyngmo Jul 21 '22 at 09:14
  • 1
    Instead of an array, use a [hash table](https://en.wikipedia.org/wiki/Hash_table). Then it's very fast to see collisions. – Schwern Jul 21 '22 at 09:14
  • Make an array with all the digits. Then shuffle it randomly. – Barmar Jul 21 '22 at 09:20
  • Ted Lyngmo Thank you! Your answer was helpful – DIA_YA Jul 21 '22 at 09:20
  • 1
    @limserhane You can take the first N elements of the array if you need fewer. – Barmar Jul 21 '22 at 09:23
  • Break out of the inner loop when you set `sameNum = 1;` – Barmar Jul 21 '22 at 09:24
  • @Schwern Since the array is at most 10 elements long, linear search will probably be faster than hashing. – Barmar Jul 21 '22 at 09:25
  • 2
    @SupportUkraine When you get to the last element, it will probably generate lots of collisions before it picks the remaining available number. So it slows down considerably near the end. – Barmar Jul 21 '22 at 09:27

2 Answers2

2

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() {
    for (int i = arrScale; i > 1; --i) {
        // pick a number never picked before and swap with the last number
        swap(numArr + (rand() % i), numArr + (i-1));
    }
}

Not only is it pretty fast - every possible permutation will have an equal chance of appearing (with the little detail that rand() % i is not uniformly distributed).

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

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.

limserhane
  • 1,022
  • 1
  • 6
  • 17