From 9f3644fab035277f2c375d91bd35776ee91841b8 Mon Sep 17 00:00:00 2001 From: HeNine <> Date: Wed, 19 Apr 2023 11:18:53 +0200 Subject: [PATCH] change to struct --- src/main.rs | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index c302d17..50c0077 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 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 { - let mut state = [false; 8]; +impl Into for u8 { + fn into(self) -> State { + let mut state = [false; 8]; - for i in 0..8 { - state[i] = (num >> i & 1) == 1; - } + for i in 0..8 { + 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::>() .join("\n");