day22 refactored part1 into extra struct

This commit is contained in:
Johannes
2018-12-24 15:49:00 +01:00
parent d5aa1ddc74
commit 31075fa449

View File

@@ -1,19 +1,40 @@
use crate::tasks::day22::Equipment::*;
pub fn task1() { pub fn task1() {
let depth: usize = 3879; let cave = Cave::create(3879, Node(8, 713, Torch));
//let target: (usize, usize) = (8, 713);
const TARGET_X: usize = 8;
const TARGET_Y: usize = 713;
let mut map: Vec<Vec<usize>> = Vec::with_capacity(TARGET_X + 1); println!("Sum of erosion indexes: {}", cave.erosion_sum());
let mut inner_vec = Vec::with_capacity(TARGET_Y + 1); }
inner_vec.resize(TARGET_Y + 1, 0);
map.resize(TARGET_X + 1, inner_vec);
for x in 0..=TARGET_X { #[derive(PartialEq)]
for y in 0..=TARGET_Y { enum Equipment {
Torch,
Climbing,
Neither,
}
struct Node(usize, usize, Equipment);
struct Cave {
map: Vec<Vec<usize>>,
target: Node,
}
impl Cave {
fn create(depth: usize, target: Node) -> Self {
if target.2 != Torch {
panic!("A valid target point needs the torch equipped");
}
let mut map: Vec<Vec<usize>> = Vec::with_capacity(target.0 + 1);
let mut inner_vec = Vec::with_capacity(target.1 + 1);
inner_vec.resize(target.1 + 1, 0);
map.resize(target.0 + 1, inner_vec);
for x in 0..=target.0 {
for y in 0..=target.1 {
let geo_index = match (x, y) { let geo_index = match (x, y) {
(0, 0) => 0, (0, 0) => 0,
(TARGET_X, TARGET_Y) => 0, _ if target.0 == x && target.1 == y => 0,
(x, 0) => x * 16807, (x, 0) => x * 16807,
(0, y) => y * 48271, (0, y) => y * 48271,
(x, y) => map[x - 1][y] * map[x][y - 1], (x, y) => map[x - 1][y] * map[x][y - 1],
@@ -23,10 +44,20 @@ pub fn task1() {
} }
} }
// println!("{:?}", map); Cave { map, target }
}
let result: usize = (0..=TARGET_X)
.map(|x| (0..=TARGET_Y).map(|y| map[x][y] % 3).sum::<usize>()) fn erosion_sum(&self) -> usize {
.sum(); (0..=self.target.0)
println!("Sum of erosion indexes: {}", result); .map(|x| {
(0..=self.target.1)
.map(|y| self.field_type(x, y))
.sum::<usize>()
})
.sum()
}
fn field_type(&self, x: usize, y: usize) -> usize {
self.map[x][y] % 3
}
} }