我正在尝试使用 ndarray 库在 Rust 中实现康威生命游戏 (Conway's Game of Life) 的一个迭代。我认为可以通过循环遍历数组的 3x3 窗口来简单地计算活着的邻居数量,但是我在进行实际更新时遇到了问题。
数组中用 #
表示生命,用 表示没有生命:
let mut world = Array2::<String>::from_elem((10, 10), " ".to_string());
for mut window in world.windows((3, 3)) {
let count_all = window.fold(0, |count, cell| if cell == "#" { count + 1 } else { count });
let count_neighbours = count_all - if window[(1, 1)] == "#" { 1 } else { 0 };
match count_neighbours {
0 | 1 => window[(1, 1)] = " ".to_string(), // Under-population
2 => {}, // Live if alive
3 => window[(1, 1)] = "#".to_string(), // Re-produce
_ => window[(1, 1)] = " ".to_string(), // Over-population
}
}
这段代码无法编译!报错信息在
match
块内,出现了"error: cannot borrow as mutable"和"error: cannot assign to immutable index"。我尝试过使用for &mut window...
,但是库貌似没有实现该方法(?)。我对Rust相对陌生,我认为这可能与库提供的窗口实现有关。但我不确定,也不知道是否有某种变化/修复可以让我继续使用这种方式。我需要完全舍弃这种方式吗?我不确定在这种情况下最好的方法是什么。
非常欢迎任何其他建议或代码改进。
(这段代码没有实现正确的规则,因为我正在循环中进行变更并忽略了外部边缘,但在这种情况下这是可以接受的。而且,任何这样做的变化都可以——细节并不重要。)