Long Claw
Long Claw

Reputation: 107

Synchronizing variables in C

I have a recursive function that goes through the elements of a matrix by a specific rule. Every time I go through an element I am calculating a result based on the element I am in the matrix at that moment, and when all the calls of the function end I am back to the first element I started at I have the result I need in that result I mentioned before.

Now the problem is that I have to replace every element of the matrix that I went through with this result. From what I am thinking i have 3 options :

  1. Use the same algorithm to call the function again from the starting element and go through it again, basically going through the same path and replacing the elements with the result (this would be the most inefficient as the algorithm and the size of the matrix are pretty big )

  2. Memorizing the addresses of the elements I am arriving at in the matrix on every callout, then I would have a vector of addresses and after the function finishes I am just going through
    that vector and replacing the values with the one I calculating.

  3. This is quite a longshot for me to implement but I was thinking that I could synchronize all the variables in the positions that I have arrived in the matrix with one external variable. When the function finishes and I have my result I just change the value of this external variable with the result and all the other elements in the matrix that I have linked this variable to would automatically change.

My question is how could I implement something like "3."? is there any way you can synchronize a variable(or multiple ones) to always have the same value as another one that is constantly updating ?

Upvotes: 1

Views: 98

Answers (1)

mevets
mevets

Reputation: 10445

From a definition of a Matrix like:

struct Matrix {
     int N, M;
     int *Mat;
};
Type Values[];

Where the value at (i,j) is Values[G->Mat[G->M * i + j]]; that is Mat just holds indexes into Values[] which can be dynamically extended. At the beginning if a path traversal, you could allocate a new Values[t], and change each visited node (i,j) to be t: G->Mat[G->M * i + j] = t. When you assign Values[t], all of the nodes linked to it will be automatically updated.

While you are making your traversal, you would use their value, then change their index as you moved to the next node. Serendipitously, if you encountered a node already with an index of t, you would know that you are caught in a cycle.

Although I might have misread your requirement terribly.

Upvotes: 1

Related Questions