day 6 part 2 1.5 times faster
This commit is contained in:
@@ -64,7 +64,7 @@ fn parse(input: &str) -> (Grid<char>, Coord) {
|
||||
}
|
||||
|
||||
fn is_loop(m: &Grid<char>, block: Coord, mut pos: Coord, mut dir: char) -> bool {
|
||||
let mut visited = HashSet::new();
|
||||
let mut visited: Grid<[bool; 5]> = Grid::from_default(m.content_width, m.content_height);
|
||||
loop {
|
||||
let (x, y) = pos;
|
||||
|
||||
@@ -79,10 +79,11 @@ fn is_loop(m: &Grid<char>, block: Coord, mut pos: Coord, mut dir: char) -> bool
|
||||
return false;
|
||||
} else if next == block || '#' == m[next] {
|
||||
// we only check for loops on a collision to speed things up
|
||||
if visited.contains(&(pos, dir)) {
|
||||
// this is our own little hash function to speed things up
|
||||
if visited[pos][dir as usize % 5] {
|
||||
return true;
|
||||
}
|
||||
visited.insert((pos, dir));
|
||||
visited[pos][dir as usize % 5] = true;
|
||||
|
||||
dir = match dir {
|
||||
'^' => '>',
|
||||
|
||||
@@ -69,7 +69,7 @@ fn part2(input: &str) -> i64 {
|
||||
let width = 101;
|
||||
let height = 103;
|
||||
let mut robots = parse(input);
|
||||
let max_seconds = width * height as i64;
|
||||
let max_seconds = width * height;
|
||||
for second in 0.. {
|
||||
if second > max_seconds {
|
||||
panic!("Seen all combinations but no christmas tree. So sad!");
|
||||
|
||||
@@ -89,6 +89,15 @@ impl<T> Grid<T> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn entries_mut(&mut self) -> impl Iterator<Item = (Coord, &mut T)> {
|
||||
self.content.iter_mut().enumerate().map(|(i, val)| {
|
||||
(
|
||||
(i as i64 % self.content_width, i as i64 / self.content_width),
|
||||
val,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_values<U>(self, f: fn(T) -> U) -> Grid<U> {
|
||||
let new_content = self.content.into_iter().map(f).collect_vec();
|
||||
Grid {
|
||||
|
||||
Reference in New Issue
Block a user