#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *random_matrix(const size_t v, const size_t e, const unsigned int seed);
int *random_sequence(const size_t n, const size_t k, const unsigned int seed);
int main(void)
{
int *graph;
graph = random_matrix(20, 11, time(0));
/* a chance to do something */
free(graph);
return 0;
}
int *random_matrix(const size_t v, const size_t e, const unsigned int seed)
{
int *matr;
size_t i, j;
int *seq;
if (e > (v - 1) * v / 2) exit(1);
matr = (int *) calloc(v * v, sizeof(int));
seq = random_sequence((v - 1) * v / 2, e, seed);
for (j = 0; j < v; j++)
for (i = 0; i < j; i++) {
/* or simply set matr[i + j * v] = seq[count++] */
matr[i + j * v] = seq[i + j * (j - 1) / 2];
/* in this way we guarantee that the matrix is valid */
matr[j + i * v] = matr[i + j * v];
}
free(seq);
return matr;
}
int *random_sequence(const size_t n, const size_t k, const unsigned int seed)
{
int *seq;
size_t i, s;
if (k > n) exit(1);
/* here we seed the generator used by rand() */
srand(seed);
seq = (int *) calloc(n, sizeof(int));
for (i = 0; i < k; i++) {
do s = rand() % n; while (seq[s] != 0);
seq[s] = 1;
}
return seq;
}
Comments
Leave a comment