samedi 27 mars 2021

Build random adjacency matrix with given probability [duplicate]

As a task I need to write a C program that receives a V (vertices) and a P (probability) parameters.

The function will then create a randomly generated graph, generating an edge between two nodes with a specific user inputted probability.

I've made a random adjacency matrix using rand(), but I'm having a hard time implementing the same idea with a given user probability instead of just randomly assigning 1/0.

Completely lost, how can I do that?

Code here:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int i, j;
float p = 0.3;
int g[5][5] = { 0,0,0,0,0,0,0,0,0,0 };
srand(time(0));
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (rand() / (double)RAND_MAX < p)
        {
            g[i][j] = 1;
        }
    }
}

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        printf("%d", g[i][j]);
    }
    printf("\n");
    }
}



Aucun commentaire:

Enregistrer un commentaire