In: Computer Science
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct NODE_s* NODE;
typedef struct NODE_s {
char name;
NODE link[10];
} NODE_t[1];
#define nodeA 0
#define nodeB 1
#define nodeC 2
#define nodeD 3
#define nodeE 4
#define nodeF 5
int main()
{
srand(time(NULL));
//printf("%d\n", random());
NODE_t node[6];
node[nodeA]->name = 'A';
node[nodeB]->name = 'B';
node[nodeC]->name = 'C';
node[nodeD]->name = 'D';
node[nodeE]->name = 'E';
node[nodeF]->name = 'F';
int i, j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 10; j++) {
node[i]->link[j] = NULL;
}
}
//a -> c,d,e,f.
node[nodeA]->link[0] = node[nodeC];
node[nodeA]->link[1] = node[nodeD];
node[nodeA]->link[2] = node[nodeE];
node[nodeA]->link[3] = node[nodeF];
//b -> c,f.
node[nodeB]->link[0] = node[nodeC];
node[nodeB]->link[1] = node[nodeF];
//c -> a,b,e.
node[nodeC]->link[0] = node[nodeA];
node[nodeC]->link[1] = node[nodeB];
node[nodeC]->link[2] = node[nodeE];
//d -> a,e,f.
node[nodeD]->link[0] = node[nodeA];
node[nodeD]->link[1] = node[nodeE];
node[nodeD]->link[2] = node[nodeF];
//e -> a,c,d.
node[nodeE]->link[0] = node[nodeA];
node[nodeE]->link[1] = node[nodeC];
node[nodeE]->link[2] = node[nodeD];
//f -> a,b,d.
node[nodeF]->link[0] = node[nodeA];
node[nodeF]->link[1] = node[nodeB];
node[nodeF]->link[2] = node[nodeD];
//Random walk.
int choice = rand() % 6;
printf("%c\n", node[choice]->name);
//storing current node in a variable
NODE current = node[choice];
//generating a random length between 5 and 15
int length = (rand() % 11) + 5;
//looping for length times
for (int i = 0; i < length; i++) {
//generating a random index between 0 and 9
int next = rand() % 10;
//looping as long as the link at this next is NULL
//assuming each node has at least one valid link
while (current->link[next] == NULL) {
//generating another index
next = rand() % 10;
}
//moving current to the link pointed by next
current = current->link[next];
//printing new location
printf("%c\n", current->name);
}
return 0;
}
/*OUTPUT*/
B
F
D
E
D
F
B
C
B
C
B
F
A
E