adventofcode2022/day08/common.rs

56 lines
1.7 KiB
Rust
Raw Normal View History

2022-12-08 16:21:18 +01:00
// Copyright 2022 Christian Ulrich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::io;
pub struct Forest {
trees: Vec<Vec<u8>>,
}
impl Forest {
pub fn from_stdin() -> Result<Forest, &'static str> {
let mut trees = vec![];
for line in io::stdin().lines() {
let line = line.unwrap();
if line.len() > 0 {
trees.push(line.bytes().map(|b| b - '0' as u8).collect());
}
}
Ok(Self { trees: trees })
}
pub fn dimensions(&self) -> (usize, usize) {
(self.trees[0].len(), self.trees.len())
}
pub fn tree(&self, x: usize, y: usize) -> Option<u8> {
match y < self.trees.len() && x < self.trees[0].len() {
false => None,
true => Some(self.trees[y][x]),
}
}
pub fn line(&self, index: usize) -> Option<impl Iterator<Item = &u8>> {
Some(self.trees.get(index)?.iter())
}
pub fn column(&self, index: usize) -> Option<impl Iterator<Item = &u8>> {
match self.trees[0].len() > index {
false => None,
true => Some(self.trees.iter().map(move |line| &line[index])),
}
}
}