implement FromIterator for Grid

This commit is contained in:
kageru 2020-12-17 14:13:02 +01:00
parent 49fac3e0a9
commit 804345629a
2 changed files with 28 additions and 26 deletions

View File

@ -9,24 +9,19 @@ fn read_input() -> String {
} }
fn parse_input(raw: &str) -> Parsed { fn parse_input(raw: &str) -> Parsed {
// TODO: implement FromIterator for Grid raw.lines()
Grid {
fields: raw
.lines()
.enumerate() .enumerate()
.flat_map(move |(y, l)| l.bytes().enumerate().map(move |(x, b)| ((x, y, 0).into(), b.into()))) .flat_map(move |(y, l)| l.bytes().enumerate().map(move |(x, b)| ((x, y, 0).into(), b.into())))
.collect(), .collect()
}
} }
fn count_live_neighbors(p: &Position3D, grid: &Parsed) -> usize { fn count_live_neighbors(p: &Position3D, grid: &Parsed) -> usize {
p.neighbors().iter().filter(|&n| grid.get(*n) == Cell::Alive).count() p.neighbors().iter().filter(|&n| grid.get(*n) == Cell::Alive).count()
} }
fn make_step(mut input: Parsed) -> Parsed { fn make_step(input: Parsed) -> Parsed {
let readonly = input.clone(); let readonly = input.clone();
Grid { input
fields: input
.fields .fields
.keys() .keys()
.flat_map(|p| p.neighbors()) .flat_map(|p| p.neighbors())
@ -39,8 +34,7 @@ fn make_step(mut input: Parsed) -> Parsed {
}; };
(pos, new) (pos, new)
}) })
.collect(), .collect()
}
} }
fn part1(parsed: &Parsed) -> usize { fn part1(parsed: &Parsed) -> usize {

View File

@ -1,5 +1,5 @@
use impl_ops::*; use impl_ops::*;
use itertools::{join, Itertools, iproduct}; use itertools::{iproduct, join, Itertools};
use std::{ use std::{
collections::HashMap, convert::TryInto, fmt::{self, Display, Formatter}, hash::{BuildHasher, Hash}, ops, ops::AddAssign collections::HashMap, convert::TryInto, fmt::{self, Display, Formatter}, hash::{BuildHasher, Hash}, ops, ops::AddAssign
}; };
@ -84,6 +84,14 @@ impl<P: Position + Eq + Hash, T: Display + Default + Copy> Grid<P, T> {
} }
} }
impl<P: Position + Hash + Eq, T: Display + Default> std::iter::FromIterator<(P, T)> for Grid<P, T> {
fn from_iter<I: IntoIterator<Item = (P, T)>>(iter: I) -> Self {
Grid {
fields: iter.into_iter().collect(),
}
}
}
impl<T: Display + Default + Copy> Grid<Position2D, T> { impl<T: Display + Default + Copy> Grid<Position2D, T> {
fn draw_ascii(&self) -> String { fn draw_ascii(&self) -> String {
draw_ascii(&self.fields) draw_ascii(&self.fields)