Skip to content

Instantly share code, notes, and snippets.

@whiter4bbit
Created December 24, 2019 19:04
Show Gist options
  • Save whiter4bbit/bd4a7b1090b9865ec467f16a2a5da2e3 to your computer and use it in GitHub Desktop.
Save whiter4bbit/bd4a7b1090b9865ec467f16a2a5da2e3 to your computer and use it in GitHub Desktop.
use std::fs::File;
use std::io::{BufRead, BufReader, Result};
use std::collections::HashSet;
type Grid = (i32, isize, isize);
fn load_grid(path: &str) -> Result<Grid> {
let f = File::open(path)?;
let f = BufReader::new(f);
let (mut grid, mut rows, mut cols) = (0, 0, 0);
for (r, line) in f.lines().enumerate() {
let line = line.unwrap();
cols = line.len();
rows = rows.max(r + 1);
for (c, cell) in line.chars().enumerate() {
if cell == '#' {
let pos = (r * cols + c);
grid = grid | (1 << pos);
}
}
}
Ok((grid, rows as isize, cols as isize))
}
const DIRS: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, 1), (0, -1)];
fn solve() {
let (mut current, rows, cols) = load_grid("input-day24.txt").unwrap();
println!("{} {} {}", current, rows, cols);
let mut seen: HashSet<i32> = HashSet::new();
loop {
let mut next = 0i32;
for r in 0..rows {
for c in 0..cols {
let mut adjacent = 0;
for (dr, dc) in &DIRS {
let (ar, ac) = (r + dr, c + dc);
if ar >= 0 && ar < rows && ac >= 0 && ac < cols {
adjacent += (current >> (ar * cols + ac) & 1);
}
}
let next_cell = match (current >> (r * cols + c) & 1) {
1 if adjacent != 1 => 0,
0 if adjacent == 1 || adjacent == 2 => 1,
x => x,
};
next = next | (next_cell << (r * cols + c));
}
}
current = next;
if seen.contains(&current) {
break;
}
seen.insert(current);
}
println!("{}", current);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment