-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquest19.rs
90 lines (73 loc) · 2.14 KB
/
quest19.rs
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
use crate::util::grid::*;
use crate::util::point::*;
const NEIGHBOURS: [Point; 8] = [
Point::new(-1, -1),
Point::new(0, -1),
Point::new(1, -1),
Point::new(1, 0),
Point::new(1, 1),
Point::new(0, 1),
Point::new(-1, 1),
Point::new(-1, 0),
];
pub fn part1(notes: &str) -> String {
decode(notes, 1)
}
pub fn part2(notes: &str) -> String {
decode(notes, 100)
}
pub fn part3(notes: &str) -> String {
decode(notes, 1048576000)
}
fn decode(notes: &str, rounds: u32) -> String {
let (prefix, suffix) = notes.split_once("\n\n").unwrap();
let mut operations = prefix.bytes().cycle();
let mut grid @ Grid { width, height, .. } = Grid::parse(suffix);
// Map points to points
let mut lookup = Grid {
width,
height,
bytes: (0..width * height).map(|i| Point::new(i % width, i / width)).collect(),
};
// Apply 1 round of unscrambling
for y in 1..height - 1 {
for x in 1..width - 1 {
let point = Point::new(x, y);
let mut cells = NEIGHBOURS.map(|n| lookup[point + n]);
if operations.next().unwrap() == b'R' {
cells.rotate_right(1);
} else {
cells.rotate_left(1);
}
NEIGHBOURS.iter().zip(cells).for_each(|(&n, c)| lookup[point + n] = c);
}
}
// Exponentation by squaring
let mut exponent = 1;
while exponent <= rounds {
if exponent & rounds != 0 {
grid = unscramble(&grid, &lookup);
}
lookup = unscramble(&lookup, &lookup);
exponent *= 2;
}
// Extract message
let left = grid.find(b'>').unwrap();
let right = grid.find(b'<').unwrap();
let mut message = String::new();
for x in left.x + 1..right.x {
let point = Point::new(x, left.y);
message.push(grid[point] as char);
}
message
}
fn unscramble<T: Copy>(grid: &Grid<T>, lookup: &Grid<Point>) -> Grid<T> {
let mut next = grid.clone();
for y in 0..grid.height {
for x in 0..grid.width {
let point = Point::new(x, y);
next[point] = grid[lookup[point]];
}
}
next
}