|
| 1 | +use std::collections::BTreeMap; |
| 2 | +use std::fmt::{Display, Formatter}; |
| 3 | +use std::io; |
| 4 | +use std::ops::{Index, IndexMut, Range}; |
| 5 | +use std::str::FromStr; |
| 6 | +use crate::vector::Vector; |
| 7 | + |
| 8 | +pub type Pos = Vector<i64, 2>; |
| 9 | + |
| 10 | +#[derive(Debug, Clone)] |
| 11 | +pub struct Grid { |
| 12 | + data: BTreeMap<Pos, char>, |
| 13 | + end: Pos, |
| 14 | +} |
| 15 | + |
| 16 | +impl Grid { |
| 17 | + pub fn range(&self) -> (Range<i64>, Range<i64>) { |
| 18 | + let width = self.end[0] + 1; |
| 19 | + let height = self.end[1] + 1; |
| 20 | + |
| 21 | + (0..width, 0..height) |
| 22 | + } |
| 23 | + |
| 24 | + pub fn positions(&self) -> Positions { |
| 25 | + Positions { |
| 26 | + cur: Pos::new([0, 0]), |
| 27 | + end: self.end, |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl Display for Grid { |
| 33 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 34 | + for y in 0..=self.end[1] { |
| 35 | + for x in 0..=self.end[0] { |
| 36 | + let pos = Pos::new([x, y]); |
| 37 | + write!(f, "{}", *self.data.get(&pos).unwrap_or(&' '))?; |
| 38 | + } |
| 39 | + write!(f, "\n")?; |
| 40 | + } |
| 41 | + |
| 42 | + Ok(()) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl FromStr for Grid { |
| 47 | + type Err = io::Error; |
| 48 | + |
| 49 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 50 | + let mut data = BTreeMap::new(); |
| 51 | + |
| 52 | + let mut max_x = 0; |
| 53 | + let mut max_y = 0; |
| 54 | + |
| 55 | + for (y, line) in s.lines().enumerate() { |
| 56 | + for (x, c) in line.trim().chars().enumerate() { |
| 57 | + let pos = Pos::new([x as i64, y as i64]); |
| 58 | + |
| 59 | + data.insert(pos, c); |
| 60 | + max_x = max_x.max(x as i64); |
| 61 | + } |
| 62 | + max_y = max_y.max(y as i64); |
| 63 | + } |
| 64 | + |
| 65 | + let end = Pos::new([max_x, max_y]); |
| 66 | + |
| 67 | + Ok(Grid { data, end }) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl Index<Pos> for Grid { |
| 72 | + type Output = char; |
| 73 | + |
| 74 | + fn index(&self, index: Pos) -> &Self::Output { |
| 75 | + self.data.get(&index).unwrap() |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl IndexMut<Pos> for Grid { |
| 80 | + fn index_mut(&mut self, index: Pos) -> &mut Self::Output { |
| 81 | + self.data.get_mut(&index).unwrap() |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +pub struct Positions { |
| 86 | + cur: Pos, |
| 87 | + end: Pos, |
| 88 | +} |
| 89 | + |
| 90 | +impl Iterator for Positions { |
| 91 | + type Item = Pos; |
| 92 | + |
| 93 | + fn next(&mut self) -> Option<Self::Item> { |
| 94 | + if self.cur[0] < self.end[0] { |
| 95 | + self.cur[0] += 1; |
| 96 | + return Some(self.cur); |
| 97 | + } |
| 98 | + |
| 99 | + self.cur[0] = 0; |
| 100 | + |
| 101 | + if self.cur[1] < self.end[1] { |
| 102 | + self.cur[1] += 1; |
| 103 | + return Some(self.cur); |
| 104 | + } |
| 105 | + |
| 106 | + None |
| 107 | + } |
| 108 | +} |
0 commit comments