I want to compute (for a project) self-avoiding random walks by using a recursive function. I've managed to do that with two arrays StepX
and StepY
that keep track of the x and y, respectively, of the path. The recursive function is something like:
go(int x, int y, int n,int* StepX,int* StepY)
which can be summarised at "for the n-th step go at (x,y) remembering that you've been in StepX and StepY".
The project is finished and I am happy, but I would like to know how to make it work using (also) a lattice, with 1 and 0 describing visited / not yet visited locations, in order to improve its speed.
I thought that extending the function as
go(int x, int y, int n,int* StepX,int* StepY, int* lattice)
would be what I was looking for, because I thought that everytime the function go
is called, it creates a new copy of the lattice and works with it. But apparently this is not the case, since after having explored one direction (and after having reached the maximum level of the recursion allowed), going to a lower level of recursion, the lattice is still the same, with the visited location (of the deeper level) marked , while I wanted each level of the recursion to work on a different copy of the lattice.
Is it a wrong expectation? Is it just a wrong implementation? Any advice to reduce the memory size required by this approach?
My code (actually I didn't write most of it) can be found here: https://gist.github.com/4144833
Be patient, I'm not an experienced programmer.
No, you are misunderstanding the rules for parameters in C. What is copied for the recursive call is the pointer to the lattice, not the lattice array itself. You'd have to do that yourself.
The easiest way would be to allocate a new array (with malloc
) at the begginning of your call, copy the data with memcpy
and then free
the array at the end of the recursive call.