jeudi 24 octobre 2019

Generating random integer in C

First, I'm not allowed to use third party libraries.

I am trying to make a randomized 2D 5x5 coordinate in C. To achieve this, method I used is

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

int main () {
    for (int i; i < 10; i++) {
        int x = rand() % 5;   // 0, 1, 2, 3, 4
        int y = rand() % 5;
        printf("%d %d", x, y);
    }
    return 0;
}

However, I figured out that this returns the same value every time I execute the program. So, I searched and found I can use srand() and time() to set the seed. I changed my code to

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

int main () {
    for (int i; i < 10; i++) {
        srand(time(0));
        int x = rand() % 5;
        srand(time(0));
        int y = rand() % 5;
        printf("%d %d", x, y);
    }
    return 0;
}

This gives me different numbers every time I execute the program. However, x and y is the same per execute. I believe its because the time interval that time() uses is longer than the time of the execution of the for loop.

I read most of the posts I could find on google, but couldn't utilize it to my project. Is there a way to get 2 unique random numbers without third party codes?




Aucun commentaire:

Enregistrer un commentaire