I have to create a function that initializes k cluster choosing the starting center based on the distance between the point.
This is the code i wrote:
int *inizialize_centroids(int *p_dataset, int d, int k, int **p_discard_set) {
int* centroids = (int*) malloc(k*((2*d)+1)*sizeof(int)), *point_to_compare = (int*) malloc(d*sizeof(int)),
*cluster_point = (int*) malloc(d*sizeof(int));
float* distance = (float*) malloc(2*k*sizeof(float));
if(centroids == NULL || point_to_compare == NULL || cluster_point == NULL || distance == NULL){
printf("Something went wrong in inizialize_centroids(), memory allocation failed! (row 94/95)");
exit(1);
}
centroids[0]=1;
for(int i = 1; i < d; i++){
centroids[i] = p_dataset[i];
centroids[i+d] = pow(p_dataset[i],2);
}
*p_discard_set[0] = 1;
*p_discard_set[1] = p_dataset[0];
memcpy(cluster_point, &p_dataset[0], (d + 1)*sizeof(int));
int j;
int i = 1;
int t;
while (i < k){
j = 0;
while(j < 2*CHUNK ){
memcpy(point_to_compare, &p_dataset[j/2 * (d + 1)], (d + 1) * sizeof(int));
distance[j] = (float) point_to_compare[0];
j++;
distance[j] = compare(cluster_point, point_to_compare, i, d);
j++;
}
int id = (int) distance[0];
float max = distance[1];
j = 0;
while (j < 2* CHUNK){
if(distance[j+1] > max){
max = distance[j+1];
id = distance[j];
}
j+=2;
}
i++;
*p_discard_set[0] = i;
*p_discard_set[i] = id; //HERE OCCURE THE PROBLEM
[....]
}
return centroids;
The problem is that, i can't assign
*p_discard_set[i] = id;
and i don't understand why it gives me "interrupted by signal 11: SIGSEGV"
This is how i use it in main:
int *discard_set = (int*) malloc((k + 1) * sizeof(int)), *compressed_set = (int*) malloc(sizeof(int)), *retained_set = (int*) malloc(sizeof(int));
// discard_set è così fatto: [n, id_1, ... , id_n]
if(discard_set == NULL || compressed_set == NULL || retained_set == NULL){
printf("Something went wrong in main(), memory allocation failed! (row 39)");
exit(1);
}
int* centroids = inizialize_centroids(dataset, d, k, &discard_set);
The stange thing is that i can do
*p_discard_set[0] = i;
and k > 2, so it isn't out of bound, I think.
The precedence of postfix operators in C is higher than prefix, so when you say
*p_discard_set[i] = ...
you actually get
*(p_discard_set[i]) = ...
and what you actually want is
(*p_discard_set)[i] = ...
so you need the explicit parentheses to make it work the way you are expecting.
So I'm trying to implement the code, but it's not working properly. I'll put into comments where I'm pretty sure I'm making a mistake. I just started learning this chapter, and it's pretty hard and confusing, but I'm getting into it, that's why I have no idea what's wrong or not, please help.
#include "graph.h"
#include "queue.c"
#include "queue.h"
#include "topsort.c"
#include "fatal.h"
#include <stdlib.h>
#include <stdio.h>
Graph CreateDirectGraph(void)
{
int N, i;
Vertex v, w;
Graph G;
PtrToNode p;
printf("Create Directed Graph:\n");
printf("Number of vertexs in the graph:\n");
scanf("%d",&N);
G = (struct GraphRecord *)malloc(sizeof(struct GraphRecord));
G->vertices = (struct VertexRecord *)malloc(sizeof(struct VertexRecord) * (N + 1));
G->vexnum = N;
for (i = 1; i <= N; i++)
G->vertices[i].adjto = NULL;
printf("Number of edges in the graph:\n");
scanf("%d",&N);
printf("Input %2d edges:\n", N);
for (i = 1; i <= N; i++) {
scanf("%d%d", &v, &w);
p = ( struct Node *) malloc( sizeof( struct Node ) );
p->adjvex = NextAdjVex(G, v, w); /* <-- HERE */
p->next = G->vertices[v].adjto; /* <-- HERE */
G->vertices[v].adjto = p;
}
return G;
}
void DestroyGraph(Graph G)
{ /*free space*/
free(G->vertices);
free(G);
return;
}
Vertex FirstAdjVex(Graph G, Vertex v)
{
if (G->vertices[v].adjto)
return G->vertices[v].adjto->adjvex;
else return 0;
}
Vertex NextAdjVex(Graph G, Vertex v, Vertex w)
{
PtrToNode p;
p = G->vertices[v].adjto;
while (p->adjvex != w)
p = p->next;
if (p->next) return p->next->adjvex;
return 0;
}
int NumOfVex(Graph G)
{
return G->vexnum;
}
int Topsort( Graph G, int TopNum[] )
{
Queue Q;
int V, W, N;
int Counter = 0;
int *Indegree;
PtrToNode p;
N = NumOfVex(G);
Indegree = (int *)malloc(sizeof(int)*(N + 1));
for (V=1; V<=N; V++)
Indegree[V] = 0;
for (V=1; V<=N; V++)
for (p =G->vertices[V].adjto; p; p = p->next)
Indegree[p->adjvex]++;
Q = CreateQueue( N );
for (V = 1; V <= N; V++)
if ( Indegree[ V ] == 0 ) Enqueue( V, Q );
while ( !IsEmpty( Q ) ) {
V = Dequeue( Q );
TopNum[ ++ Counter ] = V; /* assign next */ /* <-- HERE */
for (W = FirstAdjVex(G, V); W; W = NextAdjVex(G, V, W))
if ( --Indegree[W] == 0 ) Enqueue( W, Q ); /* <-- HERE */
} /* end-while */
DisposeQueue( Q ); /* free memory */
if ( Counter != N )
return 0;
return 1;
}
/* <-- HERE */ means I probably made a mistake there, because I'm 99% sure the rest is correct, as I was being partly guided
OUTPUT:
Number of vertexs in the graph:
4
Number of edges in the graph:
4
Input 4 edges:
1 2
Then the runtime stops
#include <stdio.h>
#include <stdlib.h>
typedef struct listNode *listPointer;
struct listNode{
int data;
listPointer link;
};
int boolean_search(listPointer f, int q) {
listPointer t = f;
while(t){
if(q == t->data){
return 1;
}
t = t ->link;
}
return 0;
}
listPointer elem_search(listPointer f, int q) {
listPointer t = (listPointer) malloc(sizeof(listPointer));
t->data = -1;
t->link =f;
while(t){
if(q == t->data){
//printf("Match Found");
return t;
}
t = t ->link;
}
return NULL;
}
void del_num(listPointer f, int q) {
listPointer temp = elem_search(f, q), z;
if(temp) {
z=temp;
temp = temp->link;
free(z);
}
}
void delete_trial(listPointer x,int num) {
del_num(x, num);
}
listPointer create(int start, int finish)
{
int i = 0, flag = 1;
listPointer created = (listPointer) malloc(sizeof(listPointer)), st = NULL;
for( i = start; i < finish; i++)
{
listPointer temp = (listPointer) malloc(sizeof(listPointer));
int num = rand() % 50;
//printf("%d",search(st, num));
if(flag == 1 && num !=0) {
temp->data = num;
temp->link = NULL;
created = temp;
st = created;
flag = 0;
} else if(!boolean_search(st, num) && num !=0)
{
//printf("I am here");
temp->data = num;
temp->link = NULL;
created->link = temp;
created = temp;
}
}
return st;
}
void display(listPointer start){
listPointer temp = start;
printf("\nContents of given pointer : ");
while(temp){
printf("%d ",temp->data);
temp = temp->link;
}
}
int count_list( listPointer x) {
listPointer y =x;
int count = 0;
while(y) {
count ++;
y = y->link;
}
return count;
}
int count_non_zero(listPointer x) {
listPointer y =x;
int count = 0;
while(y) {
if(y->data != 0 )count ++;
y = y->link;
}
return count;
}
int scan_least_no(listPointer x){
int least = x->data, z;
listPointer y = x;
while(y)
{
z = y->data;
if(( z < least) && z != 0){
least = z;
}
y = y->link;
}
return least;
}
listPointer scan_least_ptr(listPointer x){
int least = x->data, z;
listPointer y = x, f = x;
while(y)
{
z = y->data;
if(( z < least) && z != 0){
least = z;
f = y;
}
y = y->link;
}
return f;
}
listPointer merge_asc(listPointer a, listPointer b) {
listPointer result = (listPointer) malloc(sizeof(listPointer));
result->data = -1;
result ->link = NULL;
int countA = count_non_zero(a), countB = count_non_zero(b), flag =0;//flag 0 for A, flag 1 for B
int leastNum = 0, leastNumA = 0, leastNumB = 0;
listPointer result_start = result, copyA = a, copyB =b;
printf("Count of listA : %d, listB : %d", countA, countB);
//scanning least element
//compare every element to existing ,the least one in connected to the link of that node
while((countA + countB) != 0)
{
printf("Stuck in here");
if(countA > 0)
{
//if least from here flag 0
leastNumA = scan_least_no(copyA);
} else if(countB > 0)
{
//if least from here flag 1
leastNumB = scan_least_no(copyA);
}
if(leastNumA < leastNumB)
{
flag = 0;
leastNum = leastNumA;
} else {
flag =1;
leastNum = leastNumB;
}
if(flag == 0)
{
result ->link = elem_search(copyA, leastNum);
result = result ->link;
delete_trial(a, leastNum);
}else if(flag == 1){
result ->link = elem_search(copyB, leastNum);
result = result ->link;
delete_trial(b, leastNum);
}
countA = count_non_zero(copyA);
countB = count_non_zero(copyB);
}
printf("\nMerged Pointer : ");
display(result_start);
return result_start;
}
int main()
{
listPointer a = create(10,20), b = create(1, 30), c;
display(a);
display(b);
c = merge_asc(a, b);
display(c);
return 0;
}
This program takes two linked lists and makes a new linked list from the existing linked lists.
Constraints: elements should be in ascending order, new linked list should use the existing nodes
Q: "let x = x1,x2, x3, xn and y = y1, y2, y3, yn be two linked lists. Write a program to merge the two lists together to form a new linked list z in which nodes are in ascending order. Following the merge x,y do not exist as individual lists. Each node initially in x ad y is now in z".
I couldn't figure out what is wrong with my merge_asc function because output is stuck "Contents of given pointer : 33 36 27 15 43 35 42 49 21 "
I am thinking that in delete function, due to the free function there is something going on that I didn't considered in my program.
Can anyone tell me what is wrong or what is the solution of it and what approach I should take in these situations?
I have tested every other function and they are working fine.
I am using ubuntu 14.04 and gcc4.8.4
Given two unsorted lists
2 -> 7 -> 1
5 -> 3 -> 4
If the input lists were sorted then you would use a merge sort and could do it in linear time but since these are unsorted lists you will need to take atleast NlogN time. I would advise starting by sorting one of the input lists and then doing an insertion sort with the elements of the other list.
so start by sorting the first list to get
1 -> 2 -> 7
then run an insertion sort with the other list to get
1 -> 2 -> 5 -> 7
1 -> 2 -> 3 -> 5 -> 7
1 -> 2 -> 3 -> 4 -> 5 -> 7
I have this question for my programming class which I have been struggling to complete for the past day ... and I have no real idea what to do.
I understand the basic concept of Prim's algorithm:
1. Start at an arbitrary node (the first node will do) and
add all of its links onto a list.
2. Add the smallest link (which doesn't duplicate an existing path)
in the MST, to the Minimum Spanning Tree.
Remove this link from the list.
3. Add all of the links from the newly linked node onto the list
4. repeat steps 2 & 3 until MST is achieved
(there are no nodes left unconnected).
I have been given this implementation of a Graph (using an Adjacency List) to implement Prim's algorithm on. The problem is I don't really understand the implementation. My understanding of the implementation so far is as follows:
Being an adjacency list, we have all the nodes in array form: Linked to this is a list of links, containing details of the weight, the destination, and a pointer to the rest of the links of the specific node:
Something that looks a bit like this:
[0] -> [weight = 1][Destination = 3] -> [weight = 6][Destination = 4][NULL]
[1] -> [weight = 4][Destination = 3][NULL]
and so on...
We also have an "Edge" struct, which I think is supposed to make things simpler for the implementation, but I'm not really seeing it.
Here is the code given:
GRAPH.h interface:
typedef struct {
int v;
int w;
int weight;
} Edge;
Edge EDGE (int, int, int);
typedef struct graph *Graph;
Graph GRAPHinit (int);
void GRAPHinsertE (Graph, Edge);
void GRAPHremoveE (Graph, Edge);
int GRAPHedges (Edge [], Graph g);
Graph GRAPHcopy (Graph);
void GRAPHdestroy (Graph);
int GRAPHedgeScan (Edge *);
void GRAPHEdgePrint (Edge);
int GRAPHsearch (Graph, int[]);
Graph GRAPHmst (Graph);
Graph GRAPHmstPrim (Graph);
#define maxV 8
GRAPH.c implementation:
#include <stdlib.h>
#include <stdio.h>
#include "GRAPH.h"
#define exch(A, B) { Edge t = A; A = B; B = t; }
#define max(A,B)(A>B?A:B)
#define min(A,B)(A<B?A:B)
typedef struct node *link;
struct node {
int v;
int weight;
link next;
};
struct graph {
int V;
int E;
link *adj;
};
static void sortEdges (Edge *edges, int noOfEdges);
static void updateConnectedComponent (Graph g, int from, int to, int newVal, int *connectedComponent);
Edge EDGE (int v, int w, int weight) {
Edge e = {v, w, weight};
return e;
}
link NEW (int v, int weight, link next) {
link x = malloc (sizeof *x);
x->v = v;
x->next = next;
x->weight = weight;
return x;
}
Graph GRAPHinit (int V) {
int v;
Graph G = malloc (sizeof *G);
// Set the size of the graph, = number of verticies
G->V = V;
G->E = 0;
G->adj = malloc (V * sizeof(link));
for (v = 0; v < V; v++){
G->adj[v] = NULL;
}
return G;
}
void GRAPHdestroy (Graph g) {
// not implemented yet
}
void GRAPHinsertE(Graph G, Edge e){
int v = e.v;
int w = e.w;
int weight = e.weight;
G->adj[v] = NEW (w, weight, G->adj[v]);
G->adj[w] = NEW (v, weight, G->adj[w]);
G->E++;
}
void GRAPHremoveE(Graph G, Edge e){
int v = e.v;
int w = e.w;
link *curr;
curr = &G->adj[w];
while (*curr != NULL){
if ((*curr)->v == v) {
(*curr) = (*curr)->next;
G->E--;
break;
}
curr= &((*curr)->next);
}
curr = &G->adj[v];
while (*curr != NULL){
if ((*curr)->v == w) {
(*curr) = (*curr)->next;
break;
}
curr= &((*curr)->next);
}
}
int GRAPHedges (Edge edges[], Graph g) {
int v, E = 0;
link t;
for (v = 0; v < g->V; v++) {
for (t = g->adj[v]; t != NULL; t = t->next) {
if (v < t->v) {
edges[E++] = EDGE(v, t->v, t->weight);
}
}
}
return E;
}
void GRAPHEdgePrint (Edge edge) {
printf ("%d -- (%d) -- %d", edge.v, edge.weight, edge.w);
}
int GRAPHedgeScan (Edge *edge) {
if (edge == NULL) {
printf ("GRAPHedgeScan: called with NULL \n");
abort();
}
if ((scanf ("%d", &(edge->v)) == 1) &&
(scanf ("%d", &(edge->w)) == 1) &&
(scanf ("%d", &(edge->weight)) == 1)) {
return 1;
} else {
return 0;
}
}
// Update the CC label for all the nodes in the MST reachable through the edge from-to
// Assumes graph is a tree, will not terminate otherwise.
void updateConnectedComponent (Graph g, int from, int to, int newVal, int *connectedComponent) {
link currLink = g->adj[to];
connectedComponent[to] = newVal;
while (currLink != NULL) {
if (currLink->v != from) {
updateConnectedComponent (g, to, currLink->v, newVal, connectedComponent);
}
currLink = currLink->next;
}
}
// insertion sort, replace with O(n * lon n) alg to get
// optimal work complexity for Kruskal
void sortEdges (Edge *edges, int noOfEdges) {
int i;
int l = 0;
int r = noOfEdges-1;
for (i = r-1; i >= l; i--) {
int j = i;
while ((j < r) && (edges[j].weight > edges[j+1].weight)) {
exch (edges[j], edges[j+1]);
j++;
}
}
}
Graph GRAPHmst (Graph g) {
Edge *edgesSorted;
int i;
int *connectedComponent = malloc (sizeof (int) * g->V);
int *sizeOfCC = malloc (sizeof (int) * g->V);
Graph mst = GRAPHinit (g->V);
edgesSorted = malloc (sizeof (*edgesSorted) * g->E);
GRAPHedges (edgesSorted, g);
sortEdges (edgesSorted, g->E);
// keep track of the connected component each vertex belongs to
// in the current MST. Initially, MST is empty, so no vertex is
// in an MST CC, therefore all are set to -1.
// We also keep track of the size of each CC, so that we're able
// to identify the CC with fewer vertices when merging two CCs
for (i = 0; i < g->V; i++) {
connectedComponent[i] = -1;
sizeOfCC[i] = 0;
}
int currentEdge = 0; // the shortest edge not yet in the mst
int mstCnt = 0; // no of edges currently in the mst
int v, w;
// The MST can have at most min (g->E, g->V-1) edges
while ((currentEdge < g->E) && (mstCnt < g->V)) {
v = edgesSorted[currentEdge].v;
w = edgesSorted[currentEdge].w;
printf ("Looking at Edge ");
GRAPHEdgePrint (edgesSorted[currentEdge]);
if ((connectedComponent[v] == -1) ||
(connectedComponent[w] == -1)) {
GRAPHinsertE (mst, edgesSorted[currentEdge]);
mstCnt++;
if (connectedComponent[v] == connectedComponent[w]) {
connectedComponent[v] = mstCnt;
connectedComponent[w] = mstCnt;
sizeOfCC[mstCnt] = 2; // initialise a new CC
} else {
connectedComponent[v] = max (connectedComponent[w], connectedComponent[v]);
connectedComponent[w] = max (connectedComponent[w], connectedComponent[v]);
sizeOfCC[connectedComponent[w]]++;
}
printf (" is in MST\n");
} else if (connectedComponent[v] == connectedComponent[w]) {
printf (" is not in MST\n");
} else {
printf (" is in MST, connecting two msts\n");
GRAPHinsertE (mst, edgesSorted[currentEdge]);
mstCnt++;
// update the CC label of all the vertices in the smaller CC
// (size is only important for performance, not correctness)
if (sizeOfCC[connectedComponent[w]] > sizeOfCC[connectedComponent[v]]) {
updateConnectedComponent (mst, v, v, connectedComponent[w], connectedComponent);
sizeOfCC[connectedComponent[w]] += sizeOfCC[connectedComponent[v]];
} else {
updateConnectedComponent (mst, w, w, connectedComponent[v], connectedComponent);
sizeOfCC[connectedComponent[v]] += sizeOfCC[connectedComponent[w]];
}
}
currentEdge++;
}
free (edgesSorted);
free (connectedComponent);
free (sizeOfCC);
return mst;
}
// my code so far
Graph GRAPHmstPrim (Graph g) {
// Initializations
Graph mst = GRAPHinit (g->V); // graph to hold the MST
int i = 0;
int nodeIsConnected[g->V];
// initially all nodes are not connected, initialize as 0;
for(i = 0; i < g->V; i++) {
nodeIsConnected[i] = 0;
}
// extract the first vertex from the graph
nodeIsConnected[0] = 1;
// push all of the links from the first node onto a temporary list
link tempList = newList();
link vertex = g->adj[0];
while(vertex != NULL) {
tempList = prepend(tempList, vertex);
vertex = vertex->next;
}
// find the smallest link from the node;
mst->adj[0] =
}
// some helper functions I've been writing
static link newList(void) {
return NULL;
}
static link prepend(link list, link node) {
link temp = list;
list = malloc(sizeof(list));
list->v = node->v;
list->weigth = node->weight;
list->next = temp;
return list;
}
static link getSmallest(link list, int nodeIsConnected[]) {
link smallest = list;
while(list != NULL){
if((list->weight < smallest->weight)&&(nodeIsConnected[list->v] == 0)) {
smallest = list;
}
list = list->next;
}
if(nodeIsConnected[smallest->v] != 0) {
return NULL;
} else {
return smallest;
}
}
For clarity, file to obtain test data from file:
#include <stdlib.h>
#include <stdio.h>
#include "GRAPH.h"
// call with graph_e1.txt as input, for example.
//
int main (int argc, char *argv[]) {
Edge e, *edges;
Graph g, mst;
int graphSize, i, noOfEdges;
if (argc < 2) {
printf ("No size provided - setting max. no of vertices to %d\n", maxV);
graphSize = maxV;
} else {
graphSize = atoi (argv[1]);
}
g = GRAPHinit (graphSize);
printf ("Reading graph edges (format: v w weight) from stdin\n");
while (GRAPHedgeScan (&e)) {
GRAPHinsertE (g, e);
}
edges = malloc (sizeof (*edges) * graphSize * graphSize);
noOfEdges = GRAPHedges (edges, g);
printf ("Edges of the graph:\n");
for (i = 0; i < noOfEdges; i++) {
GRAPHEdgePrint (edges[i]);
printf ("\n");
}
mst = GRAPHmstPrim (g);
noOfEdges = GRAPHedges (edges, mst);
printf ("\n MST \n");
for (i = 0; i < noOfEdges; i++) {
GRAPHEdgePrint (edges[i]);
printf ("\n");
}
GRAPHdestroy (g);
GRAPHdestroy (mst);
free (edges);
return EXIT_SUCCESS;
}
Thanks in advance.
Luke
files in full: http://www.cse.unsw.edu.au/~cs1927/12s2/labs/13/MST.html
UPDATE: I have had another attempt at this question. Here is the updated code (One edit above to change the graph_client.c to use "GRAPHmstPrim" function that I have written.
GRAPH_adjlist.c::
#include <stdlib.h>
#include <stdio.h>
#include "GRAPH.h"
#define exch(A, B) { Edge t = A; A = B; B = t; }
#define max(A,B)(A>B?A:B)
#define min(A,B)(A<B?A:B)
typedef struct _node *link;
struct _node {
int v;
int weight;
link next;
}node;
struct graph {
int V;
int E;
link *adj;
};
typedef struct _edgeNode *edgeLink;
struct _edgeNode {
int v;
int w;
int weight;
edgeLink next;
}edgeNode;
static void sortEdges (Edge *edges, int noOfEdges);
static void updateConnectedComponent (Graph g, int from, int to, int newVal, int *connectedComponent);
Edge EDGE (int v, int w, int weight) {
Edge e = {v, w, weight};
return e;
}
link NEW (int v, int weight, link next) {
link x = malloc (sizeof *x);
x->v = v;
x->next = next;
x->weight = weight;
return x;
}
Graph GRAPHinit (int V) {
int v;
Graph G = malloc (sizeof *G);
G->V = V;
G->E = 0;
G->adj = malloc (V * sizeof(link));
for (v = 0; v < V; v++){
G->adj[v] = NULL;
}
return G;
}
void GRAPHdestroy (Graph g) {
// not implemented yet
}
void GRAPHinsertE(Graph G, Edge e){
int v = e.v;
int w = e.w;
int weight = e.weight;
G->adj[v] = NEW (w, weight, G->adj[v]);
G->adj[w] = NEW (v, weight, G->adj[w]);
G->E++;
}
void GRAPHremoveE(Graph G, Edge e){
int v = e.v;
int w = e.w;
link *curr;
curr = &G->adj[w];
while (*curr != NULL){
if ((*curr)->v == v) {
(*curr) = (*curr)->next;
G->E--;
break;
}
curr= &((*curr)->next);
}
curr = &G->adj[v];
while (*curr != NULL){
if ((*curr)->v == w) {
(*curr) = (*curr)->next;
break;
}
curr= &((*curr)->next);
}
}
int GRAPHedges (Edge edges[], Graph g) {
int v, E = 0;
link t;
for (v = 0; v < g->V; v++) {
for (t = g->adj[v]; t != NULL; t = t->next) {
if (v < t->v) {
edges[E++] = EDGE(v, t->v, t->weight);
}
}
}
return E;
}
void GRAPHEdgePrint (Edge edge) {
printf ("%d -- (%d) -- %d", edge.v, edge.weight, edge.w);
}
int GRAPHedgeScan (Edge *edge) {
if (edge == NULL) {
printf ("GRAPHedgeScan: called with NULL \n");
abort();
}
if ((scanf ("%d", &(edge->v)) == 1) &&
(scanf ("%d", &(edge->w)) == 1) &&
(scanf ("%d", &(edge->weight)) == 1)) {
return 1;
} else {
return 0;
}
}
// Update the CC label for all the nodes in the MST reachable through the edge from-to
// Assumes graph is a tree, will not terminate otherwise.
void updateConnectedComponent (Graph g, int from, int to, int newVal, int *connectedComponent) {
link currLink = g->adj[to];
connectedComponent[to] = newVal;
while (currLink != NULL) {
if (currLink->v != from) {
updateConnectedComponent (g, to, currLink->v, newVal, connectedComponent);
}
currLink = currLink->next;
}
}
// insertion sort, replace with O(n * lon n) alg to get
// optimal work complexity for Kruskal
void sortEdges (Edge *edges, int noOfEdges) {
int i;
int l = 0;
int r = noOfEdges-1;
for (i = r-1; i >= l; i--) {
int j = i;
while ((j < r) && (edges[j].weight > edges[j+1].weight)) {
exch (edges[j], edges[j+1]);
j++;
}
}
}
Graph GRAPHmst (Graph g) {
Edge *edgesSorted;
int i;
int *connectedComponent = malloc (sizeof (int) * g->V);
int *sizeOfCC = malloc (sizeof (int) * g->V);
Graph mst = GRAPHinit (g->V);
edgesSorted = malloc (sizeof (*edgesSorted) * g->E);
GRAPHedges (edgesSorted, g);
sortEdges (edgesSorted, g->E);
// keep track of the connected component each vertex belongs to
// in the current MST. Initially, MST is empty, so no vertex is
// in an MST CC, therefore all are set to -1.
// We also keep track of the size of each CC, so that we're able
// to identify the CC with fewer vertices when merging two CCs
for (i = 0; i < g->V; i++) {
connectedComponent[i] = -1;
sizeOfCC[i] = 0;
}
int currentEdge = 0; // the shortest edge not yet in the mst
int mstCnt = 0; // no of edges currently in the mst
int v, w;
// The MST can have at most min (g->E, g->V-1) edges
while ((currentEdge < g->E) && (mstCnt < g->V)) {
v = edgesSorted[currentEdge].v;
w = edgesSorted[currentEdge].w;
printf ("Looking at Edge ");
GRAPHEdgePrint (edgesSorted[currentEdge]);
if ((connectedComponent[v] == -1) ||
(connectedComponent[w] == -1)) {
GRAPHinsertE (mst, edgesSorted[currentEdge]);
mstCnt++;
if (connectedComponent[v] == connectedComponent[w]) {
connectedComponent[v] = mstCnt;
connectedComponent[w] = mstCnt;
sizeOfCC[mstCnt] = 2; // initialise a new CC
} else {
connectedComponent[v] = max (connectedComponent[w], connectedComponent[v]);
connectedComponent[w] = max (connectedComponent[w], connectedComponent[v]);
sizeOfCC[connectedComponent[w]]++;
}
printf (" is in MST\n");
} else if (connectedComponent[v] == connectedComponent[w]) {
printf (" is not in MST\n");
} else {
printf (" is in MST, connecting two msts\n");
GRAPHinsertE (mst, edgesSorted[currentEdge]);
mstCnt++;
// update the CC label of all the vertices in the smaller CC
// (size is only important for performance, not correctness)
if (sizeOfCC[connectedComponent[w]] > sizeOfCC[connectedComponent[v]]) {
updateConnectedComponent (mst, v, v, connectedComponent[w], connectedComponent);
sizeOfCC[connectedComponent[w]] += sizeOfCC[connectedComponent[v]];
} else {
updateConnectedComponent (mst, w, w, connectedComponent[v], connectedComponent);
sizeOfCC[connectedComponent[v]] += sizeOfCC[connectedComponent[w]];
}
}
currentEdge++;
}
free (edgesSorted);
free (connectedComponent);
free (sizeOfCC);
return mst;
}
edgeLink newEdgeList(void) {
return NULL;
}
edgeLink addEdgeList(edgeLink list, int node, link edge) {
printf("EdgeListStart");
edgeLink temp = list;
list = malloc(sizeof(edgeNode));
list->w = node;
list->v = edge->v;
list->weight = edge->weight;
list->next = temp;
printf("EdgeListEnd");
return list;
}
edgeLink findSmallest(edgeLink waitList, int nodeIsConnected[]) {
printf("SmallestSTart");
edgeLink smallest = waitList;
int small = 99999;
while(waitList != NULL) {
if((waitList->weight < small)&&(nodeIsConnected[waitList->v] == 0)) {
smallest = waitList;
small = smallest->weight;
} else {
printf("\n\n smallest already used %d", waitList->v);
}
waitList = waitList->next;
}
printf("SmallestEnd");
if(nodeIsConnected[smallest->v] == 0){
return smallest;
} else {
printf("Returning NULL");
return NULL;
}
}
link addList(edgeLink smallest, link list, int v) {
printf(":istsatt");
link temp = list;
list = malloc(sizeof(node));
list->v = v;
list->weight = smallest->weight;
list->next = temp;
printf("Listend");
return list;
}
Graph GRAPHmstPrim (Graph g) {
Graph mst = GRAPHinit (g->V); // graph to hold the MST
int i = 0;
int v = 0;
int w = 0;
int nodeIsConnected[g->V]; // array to hold whether a vertex has been added to MST
int loopStarted = 0;
edgeLink smallest = NULL;
// initially all nodes are not in the MST
for(i = 0; i < g->V; i++) {
nodeIsConnected[i] = 0;
}
while((smallest != NULL)||(loopStarted == 0)) {
printf("v is : %d", v);
// add the very first node to the MST
nodeIsConnected[v] = 1;
loopStarted = 1;
// push all of its links onto the list
link vertex = g->adj[v];
edgeLink waitList = newEdgeList();
while(vertex != NULL) {
waitList = addEdgeList(waitList, v, vertex);
vertex = vertex->next;
}
// find the smallest edge from the list
// which doesn't duplicate a connection
smallest = findSmallest(waitList, nodeIsConnected);
// no nodes don't duplicate a connection
// return the current MST
if(smallest == NULL){
return mst;
}
// otherwise add the attributes to the MST graph
w = smallest->w;
v = smallest->v;
mst->adj[v] = addList(smallest, mst->adj[v], w);
mst->adj[w] = addList(smallest, mst->adj[w], v);
}
return mst;
}
Summary of changes:
- Added edgeList to hold the edges that may be entered into the MST
- Array nodeIsConnected[] to track whether a node is in the MST
- Function to select the smallest node. If there is no node which doesn't duplicate a link this returns NULL
Seeing as this seems homework, I'm not going to give the entire answer in code. Your code seems to be on the right track. The next step you need is indeed to add the smallest link from your temporary list to to your mst. By adding the smallest one from your list, you are actually connecting your (partially built) mst to a node that is not yet in your mst. The link with the smallest weight will always be the cheapest way to connect the nodes in your mst to the other nodes.
When you add the smallest link, you are adding a node to the partially built tree and you need to update your temporary list. You need to add all the links of your new node to the list. Once you've done that, your temporary list contains all links of all nodes in your partially built mst. You continue that process of adding nodes until all nodes are in your mst.
When adding the cheapest link, you need to check if you are connecting a new node to your mst. The cheapest link could be connecting 2 nodes that are already in your mst. If so, that link needs to be skipped and you take the next cheapest one. There are actually several ways of handling this. You could maintain a set/vector of nodes that are already in your mst, maintain a vector of booleans to track the status of a node or make sure your temporary list only contains links that connect new nodes (although this is the most intensive approach).
So I'm trying to multiply matrices in c. However when I try to multiply the numbers in the two arrays, and put them in an answer array its always zero. heres the code for the method, thanks.
My matrix struct:
typedef struct matrix {
int r;
int c;
double **mat;
} *matrix_t;
My matrix multiplying method:
matrix_t mat_mult(matrix_t a, matrix_t b)
{
int i, j, k;
double x, temp1, temp2;
double tempsol = 0.0;
x = temp1 = temp2 = 0;
matrix_t answer;
if(a -> c == b -> r)
{
answer = mat_new(a -> r, b -> c);
for(i = 0; i < a -> r; i++)
for( j = 0; j < b -> c; j++)
{
for( k = 0; k < a -> c; k++)
{
tempsol += a->mat[i][k] * b->mat[k][j];
answer-> mat[i][j] = tempsol;
}
}
return answer;
}
else if(a -> r == b -> c)
{
answer = mat_new(a -> c, b -> r);
return answer;
}
else
{
printf("Matrices could not be multiplied");
exit(1);
return;
}
}
heres the code for my mat_new as well
matrix_t mat_new(int r,int c)
{
int i = 0;
double **a;
matrix_t matrix_a;
a = (double**)malloc(r *sizeof(double *));
for(i = 0; i < r; i++)
{
a[i] = (double*)malloc(c *sizeof(double));
}
matrix_a = (matrix_t) malloc ( sizeof(struct matrix));
matrix_a -> mat = a;
matrix_a -> r = r;
matrix_a -> c = c;
return matrix_a;
}
You need to free your objects. You need to reset tempsol. But most importantly, you need to review your mat_mult().
matrix_t mat_mult(matrix_t a, matrix_t b)
{
/* ... */
if(a -> c == b -> r)
{
/* ... */
}
else if(a -> r == b -> c)
{
/* BZZZZT! */
answer = mat_new(a -> c, b -> r); /* BZZZZT! mat_mult(b, a); */
/* BZZZZT! */
return answer;
}
else
{
/* ... */
}
}
Seems like all your issues stem from reading in matrix values as integers rather than doubles. Everything works fine if you change temp in read_mat() to an int, then cast it to a double when you're putting it in the matrix.
This should work for your example:
matrix_t mat_new(int r,int c)
{
matrix_t new = malloc(sizeof*new);
new->r = r;
new->c = c;
new->mat = malloc( r*c*sizeof(double) );
return new;
}
Your code doesn't contain any obvious errors. Perhaps the problem lies in your mat_new(). The way you defined mat in your matrix structure as double **mat;, which I wouldn't recommend, may be causing some problems.
To allocate a 2x2 matrix to mat, you would need to do:
mat = new (double*)[2];
mat[0] = new double[2];
mat[1] = new double[2];
or a n by m matrix:
mat = new (double*)[n];
for (int i=0;i<n;i++) {
mat[i] = new double[m];
}
Is this what you are doing?