63 204
Assignments Done
99,3%
Successfully Done
In July 2018

Answer to Question #62422 in C for LEE JIA WEI

Question #62422
Generate a 2D array of size 20 x 20 comprising 0 or 1 using a RAND generator. Ensure the following: 1- Seed your generator with a different seed (time of the day for instance) each time you re-execute the code. 2- Your 2D array must be symmetric, i.e., corresponds to a valid adjacency matrix. That is, if there is an edge between (i,j) then this means there is an edge between nodes (j,i). So think carefully in generating your 2D matrix.
Expert's answer
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions