change to struct

main
HeNine 1 year ago
parent 8034cbd976
commit 9f3644fab0

@ -1,6 +1,17 @@
use std::{fmt::Display, ops::Index};
use rand::Rng;
type State = [bool; 8];
#[derive(Debug, Clone, Copy)]
struct State([bool; 8]);
impl Index<usize> for State {
type Output = bool;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
fn map_state(rule: u8, state: &State) -> State {
let mut new_state: [bool; 8] = [false; 8];
@ -12,21 +23,29 @@ fn map_state(rule: u8, state: &State) -> State {
new_state[i] = (rule >> pattern & 1) == 1;
}
new_state
State(new_state)
}
fn state_to_string(state: State) -> String {
state.map(|c| if c { "⬛" } else { "⬜" }).concat()
impl Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.0.map(|c| if c { "⬛" } else { "⬜" }).concat()
)
}
}
fn num_to_state(num: u8) -> State {
impl Into<State> for u8 {
fn into(self) -> State {
let mut state = [false; 8];
for i in 0..8 {
state[i] = (num >> i & 1) == 1;
state[i] = (self >> i & 1) == 1;
}
state
State(state)
}
}
fn main() {
@ -34,7 +53,7 @@ fn main() {
let seed: u16 = rng.gen();
let rule: u8 = (seed & 0xff) as u8;
let init_state = num_to_state((seed >> 8 & 0xff) as u8);
let init_state = ((seed >> 8 & 0xff) as u8).into();
let states: String = (0..8)
.scan(init_state, |state, _i| {
@ -42,7 +61,7 @@ fn main() {
*state = map_state(rule, state);
Some(old_state)
})
.map(state_to_string)
.map(|state| state.to_string())
.collect::<Vec<String>>()
.join("\n");

Loading…
Cancel
Save