Here’s a question regarding saving states in a problem using dynamic programming.
-
Every problem of DP saves results and use them further to reduce computation. Let’s say, we calculate function value,
f(x,y)=290and save it in a 2-D array $save, such that,$save[x][y]=290. This can be done when'f'is dependent on just a small number of variables (for ex.- only 2 variables x and y in above example). But what can be done when'f'is dependent on say, 10 or 15 variables. Making an array of 10 or 15 dimensions would not be memory efficient. -
Another solution could be that we concatenate the values of variables(assuming they are unique) and store them in an associative array, using the string obtained by concatenation as key. But, concatenation is a time consuming operation. So, we have a trade off between memory and time.
Is there a way to store states if there are higher number of variables onto which the state depends? I think there might be some way using OOPS or pointers, but I am not quite able to frame anything. Any suggestions? Every idea is appreciated but solutions concerning ‘C’ or ‘PHP’ in mind, are preferred. I know ‘C’ doesn’t deal with associative arrays but I just want an algorithm/way to save states.
Saving states in sparsed data is commonly done using a
map(Associative Array) interface. Though C doesn’t have it built in – the internet is full of libraries that offer this functionality.
If You are going to compute most/all (x1,…,xk) values anyway – the usage of a
mapis discouraged – it will be slower and won’t save memory (the other way around for these cases, actually). If this is the case – a multidimensional array is probably the best solution.Many times in DP, you don’t need an array of all so far information, just the “line” previously calculated, and override the array. Effectively – for many DP problems that require k*N tables, you actually only need tables of size 2*N, and override the same lines iteratively. The same principle can hold for any dimension I believe – if all you need is the data from previous line, and not all the data.