I know that there are many posts of this on the internet but I only see the lottery programs using input from a user. That would make it a lot easier to check if the same number where entered again.
But in my case I have to generate a random lottery row of 7 numbers, interval 1 - 35. And I have to remove the duplicates if there are any.
My first thought was to use a nested for-loop, but then I realized that my algorithm didn't work. That's because the elements in the array haven't been initialized in the outer for-loop. If I try to compare row[0] == row[i] in the inner for-loop it means I compare to unitialized elements in the array.
Also what's wrong is that when I do the if-statement I cannot be sure that the random number is different, it could be the same number again.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_VALUE 5
#define SIZE 7
void printArray(int arr[], int size);
int main() {
srand(time(NULL));
int row[SIZE] = {0};
int i;
int counter = 0;
for (i = 0; i < SIZE; i++) {
int randNum = rand()%MAX_VALUE + 1;
row[i] = randNum;
int j;
for (j = 0; j < SIZE; j++) {
if (row[counter] == row[i]) {
row[i] = rand()%MAX_VALUE + 1;
}
}
counter++;
}
printArray(row, SIZE);
return 0;
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d, ", arr[i]);
}