<p>To experiment, I've (long ago) implemented Conway's <a href="http://en.wikipedia.org/wiki/Conway&#39;s_Game_of_Life" rel="noreferrer">Game of Life</a> (and I'm aware of <a href="https://stackoverflow.com/questions/1823/writing-a-conways-game-of-life-program">this</a> related question!).</p>

<p>My implementation worked by keeping 2 arrays of booleans, representing the 'last state', and the 'state being updated' (the 2 arrays being swapped at each iteration). While this is reasonably fast, I've often wondered about how to optimize this.</p>

<p>One idea, for example, would be to precompute at iteration N the zones that <em>could</em> be modified at iteration (N+1) (so that if a cell does not belong to such a zone, it won't even be considered for modification at iteration (N+1)). I'm aware that this is very vague, and I never took time to go into the details...</p>

<p>Do you have any ideas (or experience!) of how to go about optimizing (for speed) Game of Life iterations?</p>

[{'answer_id': 40508, 'author': 'skinp', 'author_id': 2907, 'author_profile': 'https://Stackoverflow.com/users/2907', 'pm_score': 0, 'selected': False, 'text': "<p>Don't exactly know how this can be done, but I remember some of my friends had to represent this game's grid with a Quadtree for a assignment. I'm guess it's real good for optimizing the space of the grid since you basically only represent the occupied cells. I don't know about execution speed though.</p>\n"}, {'answer_id': 40509, 'author': 'Joseph Bui', 'author_id': 3275, 'author_profile': 'https://Stackoverflow.com/users/3275', 'pm_score': 0, 'selected': False, 'text': "<p>It's a two dimensional automaton, so you can probably look up optimization techniques. Your notion seems to be about compressing the number of cells you need to check at each step. Since you only ever need to check cells that are occupied or adjacent to an occupied cell, perhaps you could keep a buffer of all such cells, updating it at each step as you process each cell.</p>\n\n<p>If your field is initially empty, this will be much faster. You probably can find some balance point at which maintaining the buffer is more costly than processing all the cells.</p>\n"}, {'answer_id': 40520, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': '<p>There are table-driven solutions for this that resolve multiple cells in each table lookup. A google query should give you some examples.</p>\n'}, {'answer_id': 40526, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 4, 'selected': False, 'text': '<p>There are some super-fast implementations that (from memory) represent cells of 8 or more adjacent squares as bit patterns and use that as an index into a large array of precalculated values to determine in a single machine instruction if a cell is live or dead.</p>\n\n<p>Check out here:</p>\n\n<p><a href="http://dotat.at/prog/life/life.html" rel="noreferrer">http://dotat.at/prog/life/life.html</a></p>\n\n<p>Also XLife:</p>\n\n<p><a href="http://linux.maruhn.com/sec/xlife.html" rel="noreferrer">http://linux.maruhn.com/sec/xlife.html</a></p>\n'}, {'answer_id': 40529, 'author': 'Chris Marasti-Georg', 'author_id': 96, 'author_profile': 'https://Stackoverflow.com/users/96', 'pm_score': 5, 'selected': False, 'text': '<p>I am going to quote my answer from the other question, because the chapters I mention have some very interesting and fine-tuned solutions.  Some of the implementation details are in c and/or assembly, yes, but for the most part the algorithms can work in any language:</p>\n<blockquote>\n<p>Chapters <a href="http://www.jagregory.com/abrash-black-book/#chapter-17-the-game-of-life" rel="noreferrer">17</a> and <a href="http://www.jagregory.com/abrash-black-book/#chapter-18-its-a-plain-wonderful-life" rel="noreferrer">18</a> of\nMichael Abrash\'s <a href="http://www.jagregory.com/abrash-black-book/" rel="noreferrer">Graphics\nProgrammer\'s Black Book</a> are one of\nthe most interesting reads I have ever\nhad.  It is a lesson in thinking\noutside the box.  The whole book is\ngreat really, but the final optimized\nsolutions to the Game of Life are\nincredible bits of programming.</p>\n</blockquote>\n'}, {'answer_id': 40564, 'author': '1729', 'author_id': 4319, 'author_profile': 'https://Stackoverflow.com/users/4319', 'pm_score': 3, 'selected': False, 'text': "<p>As mentioned in Arbash's Black Book, one of the most simple and straight forward ways to get a huge speedup is to keep a change list.</p>\n\n<p>Instead of iterating through the entire cell grid each time, keep a copy of all the cells that you change.</p>\n\n<p>This will narrow down the work you have to do on each iteration.</p>\n"}, {'answer_id': 40582, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 1, 'selected': False, 'text': "<p>Two ideas:</p>\n\n<p>(1) Many configurations are mostly empty space.  Keep a linked list (not necessarily in order, that would take more time) of the live cells, and during an update, only update around the live cells (this is similar to your vague suggestion, OysterD :)</p>\n\n<p>(2) Keep an extra array which stores the # of live cells in each row of 3 positions (left-center-right).  Now when you compute the new dead/live value of a cell, you need only 4 read operations (top/bottom rows and the center-side positions), and 4 write operations (update the 3 affected row summary values, and the dead/live value of the new cell).  This is a slight improvement from 8 reads and 1 write, assuming writes are no slower than reads.  I'm guessing you might be able to be more clever with such configurations and arrive at an even better improvement along these lines.</p>\n"}, {'answer_id': 158834, 'author': 'A. Rex', 'author_id': 3508, 'author_profile': 'https://Stackoverflow.com/users/3508', 'pm_score': 4, 'selected': False, 'text': '<p>You should look into <a href="http://en.wikipedia.org/wiki/Hashlife" rel="noreferrer">Hashlife</a>, the ultimate optimization.  It uses the <a href="http://en.wikipedia.org/wiki/Quadtree" rel="noreferrer">quadtree</a> approach that skinp mentioned.</p>\n'}, {'answer_id': 6503242, 'author': 'Owen Knight', 'author_id': 621303, 'author_profile': 'https://Stackoverflow.com/users/621303', 'pm_score': 3, 'selected': False, 'text': "<p>The algorithm itself is inherently parallelizable. Using the same double-buffered method in an unoptimized CUDA kernel, I'm getting around 25ms per generation in a 4096x4096 wrapped world.</p>\n"}, {'answer_id': 37594397, 'author': 'Omran Shilunte', 'author_id': 6415209, 'author_profile': 'https://Stackoverflow.com/users/6415209', 'pm_score': 2, 'selected': False, 'text': '<p>what is the most efficient algo mainly depends on the initial state.</p>\n\n<p>if the majority of cells is dead, you could save a lot of CPU time by skipping empty parts and not calculating stuff cell by cell.</p>\n\n<p>im my opinion it can make sense to check for completely dead spaces first, when your initial state is something like "random, but with chance for life lower than 5%."</p>\n\n<p>i would just divide the matrix up into halves and start checking the bigger ones first.</p>\n\n<p>so if you have a field of 10,000 * 10,000, you´d first accumulate the states of the upper left quarter of 5,000 * 5,000.</p>\n\n<p>and if the sum of states is zero in the first quarter, you can ignore this first quarter completely now and check the upper right 5,000 * 5,000 for life next.</p>\n\n<p>if its sum of states is >0, you will now divide up the second quarter into 4 pieces again - and repeat this check for life for each of these subspaces.</p>\n\n<p>you could go down to subframes of 8*8 or 10*10 (not sure what makes the most sense here) now.</p>\n\n<p>whenever you find life, you mark these subspaces as "has life".</p>\n\n<p>only spaces which "have life" need to be divided into smaller subspaces - the empty ones can be skipped.</p>\n\n<p>when you are finished assigning the "has life" attribute to all possible subspaces, you end up with a list of subspaces which you now simply extend by +1 to each direction - with empty cells - and perform the regular (or modified) game of life rules to them.</p>\n\n<p>you might think that dividn up a 10,000*10,000 spae into subspaces of 8*8 is a lot os tasks - but accumulating their states values is in fact much, much less computing work than performing the GoL algo to each cell plus their 8 neighbours plus comparing the number and storing the new state for the net iteration somewhere...</p>\n\n<p>but like i said above, for a random init state with 30% population this wont make much sense, as there will be not many completely dead 8*8 subspaces to find (leave alone dead 256*256 subpaces)</p>\n\n<p>and of course, the way of perfect optimisation will last but not least depend on your language.</p>\n\n<p>-110</p>\n'}, {'answer_id': 48489130, 'author': 'romolero', 'author_id': 9280310, 'author_profile': 'https://Stackoverflow.com/users/9280310', 'pm_score': 0, 'selected': False, 'text': '<p>I implemented this in C#:</p>\n\n<p>All cells have a location, a neighbor count, a state, and access to the rule.</p>\n\n<ol>\n<li>Put all the live cells in array B in array A.</li>\n<li>Have all the cells in array A add 1 to the neighbor count of their\nneighbors.</li>\n<li>Have all the cells in array A put themselves and their neighbors in array B.</li>\n<li>All the cells in Array B Update according to the rule and their state.</li>\n<li>All the cells in Array B set their neighbors to 0.</li>\n</ol>\n\n<p>Pros:</p>\n\n<ol>\n<li>Ignores cells that don\'t need to be updated</li>\n</ol>\n\n<p>Cons:</p>\n\n<ol>\n<li>4 arrays: a 2d array for the grid, an array for the live cells, and an array \nfor the active cells.</li>\n<li>Can\'t process rule B0.</li>\n<li>Processes cells one by one.</li>\n<li>Cells aren\'t just booleans</li>\n</ol>\n\n<p>Possible improvements:</p>\n\n<ol>\n<li>Cells also have an "Updated" value, they are updated only if they haven\'t \nupdated in the current tick, removing the need of array B as mentioned above</li>\n<li>Instead of array B being the ones with live neighbors, array B could be the \ncells without, and those check for rule B0.</li>\n</ol>\n'}, {'answer_id': 70125563, 'author': 'InfiniteGamer', 'author_id': 15012953, 'author_profile': 'https://Stackoverflow.com/users/15012953', 'pm_score': 0, 'selected': False, 'text': "<p>If you don't want anything too complex, then you can use a grid to slice it up, and if that part of the grid is empty, don't try to simulate it (please view Tyler's answer). However, you could do a few optimizations:</p>\n<ol>\n<li>Set different grid sizes depending on the amount of live cells, so if there's not a lot of live cells, that likely means they are in a tiny place.</li>\n<li>When you randomize it, don't use the grid code until the user changes the data: I've personally tested randomizing it, and even after a long amount of time, it still fills most of the board (unless for a sufficiently small grid, at which point it won't help that much anymore)</li>\n<li>If you are showing it to the screen, don't use rectangles for pixel size 1 and 2: instead set the pixels of the output. Any higher pixel size and I find it's okay to use the native rectangle-filling code. Also, preset the background so you don't have to fill the rectangles for the dead cells (not live, because live cells disappear pretty quickly)</li>\n</ol>\n"}]
['https://Stackoverflow.com/questions/40485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2638/']