blob: 2d65cd97a8094af2a3689a063bb2995871af2c7d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
use std::fs;
use std::path::Path;
#[derive(PartialEq)]
enum SeaCucumber {
East,
South,
Empty
}
impl From<char> for SeaCucumber {
fn from(c: char) -> Self {
match c {
'>' => Self::East,
'v' => Self::South,
'.' => Self::Empty,
_ => unreachable!()
}
}
}
struct Field {
steps: usize,
field: Vec<Vec<SeaCucumber>>
}
impl From<&str> for Field {
fn from(s: &str) -> Self {
let field = s.lines().map(|l| l.chars().map(|c| SeaCucumber::from(c)).collect::<Vec<_>>()).collect();
Self::new(field)
}
}
impl Field {
fn new(field: Vec<Vec<SeaCucumber>>) -> Self {
Self { steps: 0, field }
}
fn step_east(&mut self) -> bool {
let mut updated = false;
for y in 0..self.field.len() {
let len = self.field[y].len();
let to_update = (0..len).filter(|&x| {
let n = (x + 1) % len;
self.field[y][x] == SeaCucumber::East && self.field[y][n] == SeaCucumber::Empty
}).collect::<Vec<_>>();
to_update.iter().for_each(|&x| {
let n = (x + 1) % len;
self.field[y][x] = SeaCucumber::Empty;
self.field[y][n] = SeaCucumber::East;
});
updated |= to_update.len() > 0;
}
updated
}
fn step_south(&mut self) -> bool {
let mut updated = false;
let len = self.field.len();
for x in 0..self.field[0].len() {
let to_update = (0..len).filter(|&y| {
let n = (y + 1) % len;
self.field[y][x] == SeaCucumber::South && self.field[n][x] == SeaCucumber::Empty
}).collect::<Vec<_>>();
to_update.iter().for_each(|&y| {
let n = (y + 1) % len;
self.field[y][x] = SeaCucumber::Empty;
self.field[n][x] = SeaCucumber::South;
});
updated |= to_update.len() > 0;
}
updated
}
fn step(&mut self) -> bool {
self.steps += 1;
let east = self.step_east();
let south = self.step_south();
east || south
}
fn evolve(&mut self) -> usize {
while self.step() { }
self.steps
}
}
/* AOC21 Day 25: https://adventofcode.com/2021/day/25 */
fn main() {
let input = Path::new("resources").join("input.txt");
let content = fs::read_to_string(input).expect("Unable to read input file");
let mut field = Field::from(&content[..]);
println!("The result is {}", field.evolve());
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "v...>>.vv>
.vv>>.vv..
>>.>v>...v
>>v>>.>.v.
v>v.vv.v..
>.>>..v...
.vv..>.>v.
v.v..>>v.v
....v..v.>";
#[test]
fn example() {
let mut field = Field::from(INPUT);
assert_eq!(58, field.evolve());
}
}
|