Hi I have written a simple game of life code in that uses 2 arrays, one which maintains current state and another which maintains next state. Can anyone suggest how to optimize this program for memory consumption. Ideally, I would like its space complexity to be less than RC.
I don't know too much about GOL, but assuming that there are many empty 'squares', have you looked at Sparse Matrixes?
It depends on how sparse your playing field is. If your playing field is dense, then the space complexity of any storage algorithm will trend towards RC. (Specifically, RC/2, since once you get more active cells than inactive cells, you can just store the inactive cells instead if you really cared that much about optimal space usage.)
If the playing field is sparse, you can get something that scales instead with the number of active cells by simply storing coordinate pairs per active cell or some other sparse matrix structure.
The other answerers have a good point in looking for other data structures for your states. But regardless of that, a simple optimisation might be working with two pointers to states (you might do this already). So instead of doing two array copies you do one copy and three pointer assigments:
state curr, next;
[...]
for (;;) {
next = advance(curr);
curr = copy(next);
}
To this:
state s1, s2;
state *curr, *next;
[...]
for (;;) {
*next = advance(*curr);
/* swap pointers */
state *tmp = curr;
curr = next;
next = tmp;
}
I recommend sparse matrices, as nonnb and Amber recommended. You could also look into encoding, if you have processor power to burn, or want to serialize to disk. RLE or token based compression might get you somewhere.