Search code examples
crandomnumbersgenerate

Simple C random lottery number


I would like to generate 5 different numbers in the simplest way and put them into an array. Something is wrong with my way of thinking, could you please correct my code?

void lottery(int *array){
    int i = 0;
    while(i != 5){
        bool good = true;
        int number = rand()%90+1;
        for(int j=0; j<5; j++){
            if(array[j] == number)
                good = false;
                break;

        }
        if(good){
            array[i] == number;
            i = i+1;
        }
    }
}

int main(){
    srand(time(0));
    int numbers[5];
    lottery(numbers);

    for(int i =0; i<5; i++){
        printf("%d, ",numbers[i]);
    }
    return 0;
}

Solution

  • Including the findings of kingW3 and rici and cleaning it up a little:

    // compiles without errors with:
    // clang -O3 -g3 -Weverything -W -Wall -Wextra -Wpedantic -fsanitize=bounds  -std=c11  -o stacktest stacktest.c 
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    #include <time.h>
    
    void lottery(int *array);
    void lottery(int *array){
        int i = 0;
        while(i != 5){
            bool good = true;
            int number = rand()%90+1;
            // limit is 'i' because you fill the array in order
            for(int j=0; j<i; j++){
                // Would always `break` without the curly brackets
                if(array[j] == number){
                    good = false;
                    break;
                }
            }
            if(good){
                // Use '=' instead of '=='
                array[i] = number;
                i = i+1;
            }
        }
    }
    
    int main(void){
        // time returns type 'type_t', needs casting to get rid of
        // warning
        srand( (unsigned int) time(0));
        // return of rand() is always >= 0, so 
        // initialize with a negative number
        int numbers[5] = {-1};
        int i;
        lottery(numbers);
        for(i =0; i<4; i++){
            printf("%d, ",numbers[i]);
        }
        printf("%d\n",numbers[i]);
        return 0;
    }
    

    The missing brackets were another error.

    Caveat: time() has most probably a resolution of one second, so don't run it too fast in sequence or you'll get the same numbers.