生命游戏内存优化
您好,我编写了一个简单的生命游戏代码,其中使用 2 个数组,一个数组维护当前状态,另一个数组维护下一个状态。 任何人都可以建议如何优化该程序的内存消耗。理想情况下,我希望它的空间复杂度低于 RC。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我推荐稀疏矩阵,正如 nonnb 和 Amber 所推荐的那样。如果您有处理器能力可以刻录,或者想要序列化到磁盘,您还可以研究编码。 RLE 或基于令牌的压缩可能会让您有所收获。
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.
其他回答者在为您的州寻找其他数据结构方面有很好的观点。但无论如何,一个简单的优化可能会使用两个指向状态的指针(您可能已经这样做了)。因此,您不需要执行两个数组副本,而是执行一个副本和三个指针分配:
对此:
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:
To this:
迟到的答复,但仍然。
查看 golly 的源代码: http://golly.sourceforge.net/
但在执行此操作之前,请先转到至:http://www.ibiblio.org/lifepatterns/lifeapplet.html
看看那里的代码。它是用 Java 编写的,但是速度非常非常快。
Alan Hensel 网站上的这句话应该可以回答您的问题:
然后阅读这段源代码: http://www.ibiblio.org/lifepatterns/ src.41d/LifeCell.java
它包含保存艾伦生命宇宙的数据结构。
忘记 hashlife,它太复杂了,会让你头晕的。
Late answer, but still.
Check out the sourcecode for golly: http://golly.sourceforge.net/
But before you do that, go to: http://www.ibiblio.org/lifepatterns/lifeapplet.html
And have a look at the code there. It's in Java, but it's very very fast.
This quote from Alan Hensel's website should answer your question:
Then read this piece of sourcecode: http://www.ibiblio.org/lifepatterns/src.41d/LifeCell.java
It contains the datastructures that hold Alan's Life universe.
Forget about hashlife, it is so complex it will make your head spin.
我对 GOL 不太了解,但假设有很多空的“方块”,你看过 稀疏矩阵?
I don't know too much about GOL, but assuming that there are many empty 'squares', have you looked at Sparse Matrixes?
这取决于你的比赛场地有多稀疏。如果您的竞争环境很密集,那么任何存储算法的空间复杂度都将趋向于 RC。 (具体来说,RC/2,因为一旦您获得的活动单元格多于非活动单元格,如果您确实非常关心最佳空间使用,则可以只存储非活动单元格。)
如果竞争环境稀疏,您可以获得的东西通过简单地存储每个活动单元的坐标对或其他一些稀疏矩阵结构。
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.