Two-dimensional lions

If we take my Fortran code for the goats, wolves and lions problem as shown in the F-word of programming, we know that memory usage may be a problem. So, if we compile it for 678 possible animals (217 goats, 255 wolves, 206 lions), the calculation performs neatly. However, my Windows task manager shows me that 1.22 Gigabyte of memory have been allocated for this comparably small example (without any optimisation).

Memory efficiency
Obviously, if we know the total number of animals in a universe of possible forests, it suffices to know number of animals of two species and obtain the number of the third one by subtraction. Hence, two two-dimensional arrays (one storing the forests before lunch, and one storing them after lunch) are enough. For the above example of 217 goats, 255 wolves and 206 lions, 4 Megabyte of memory are needed.

Efficiency may lead to bugs
As Sascha pointed out in Functional goats, this might lead to a higher danger of (hidden or not) bugs. In fact, in my first two dimensional reprograming of the problem, I obtained wrong results because I had forgotten to reassign .FALSE. to the after lunch forests before having the meals.

Medium size examples
For 1017 goats, 1055 wolves and 1006 lions, the corrected 2d implementaion allocates 75 MByte of memory (I was not brave enough to try the 3d version). In the specfic environment of my home computer (8 Gbyte of memory, i5 CPU,single core implementaion), it took 340 seconds to calculate more than 540 million possible forests. For 2017 goats, 2055 wolves and 2006 lions, it was 45 minutes (as I expected: the calculation time increases with the third power of the initial size).

Number of possible different forests when starting
with 1017 goats, 1055 wolves and 1006 lions=3078 animals


Relevance in finance
Obviously, when valuating a financial derivative based on some transition model (like in Black Scholes to name an easy one), we do not have to store the values at all times but just the before- and after transition values.
Dirty developments in regulation (xVA) makes it necessary to think very careful about an efficient memory management.