Skip to content

Commit

Permalink
Refactor calculation of next world.
Browse files Browse the repository at this point in the history
The usage of the `destrucuring_assignment` feature was added just for
fun, it only saves two lines of code. The feature is soon stable, see
rust-lang/rust#71126.
  • Loading branch information
magnunm committed Oct 17, 2021
1 parent 65da62f commit ed49020
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
2 changes: 1 addition & 1 deletion README.org
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

Playing with [[https://en.wikipedia.org/wiki/Elementary_cellular_automaton][elementary cellular automata]].
#+BEGIN_SRC shell
cat spaceship_1.txt | xargs cargo run
cat spaceship_1.txt | xargs cargo +nightly run
#+END_SRC
Zoom the terminal out to avoid line wrapping.
30 changes: 12 additions & 18 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![feature(destructuring_assignment)]
use std::{thread, time, env, fmt};

const ALIVE: &str = "▒";
Expand Down Expand Up @@ -48,30 +49,23 @@ impl<'a> Simulation<'a> {
}

fn next_world(&self) -> Vec<bool> {
let current_world = &self.world;
let mut next_world: Vec<bool> = Vec::new();
let world_length = current_world.len();

next_world.push(
self.rule.apply(
[current_world[world_length - 1], current_world[0], current_world[1]]
)
);
let world_start = [self.world[0]];
let world_end = [self.world[self.world.len() - 1]];
let mut cyclic_world = world_end.iter()
.chain(self.world.iter())
.chain(world_start.iter());

for i in 1..(world_length - 1) {
let (mut prev, mut current, mut next) =
(cyclic_world.next(), cyclic_world.next(), cyclic_world.next());

while next.is_some() {
next_world.push(
self.rule.apply(
[current_world[i - 1], current_world[i], current_world[i + 1]]
)
self.rule.apply([*prev.unwrap(), *current.unwrap(), *next.unwrap()])
);
(prev, current, next) = (current, next, cyclic_world.next());
}

next_world.push(
self.rule.apply(
[current_world[world_length - 2], current_world[world_length - 1], current_world[0]]
)
);

return next_world;
}
}
Expand Down

0 comments on commit ed49020

Please sign in to comment.