Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::env;
- use std::io::{self, prelude::*, BufReader};
- use std::fs::File;
- use std::collections::HashMap;
- const BOOT_CYCLES: i64 = 6;
- #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
- enum Square {
- Active,
- Inactive,
- }
- fn neighbors(pt: (i64,i64,i64,i64)) -> Vec<(i64,i64,i64,i64)> {
- let mut neighbors: Vec<(i64,i64,i64,i64)> = Vec::new();
- for x in -1..=1 {
- for y in -1..=1 {
- for z in -1..=1 {
- for w in -1..=1 {
- let nxyzw = (pt.0+x, pt.1+y, pt.2+z, pt.3+w);
- if nxyzw != pt { neighbors.push(nxyzw); }
- }
- }
- }
- }
- neighbors
- }
- fn count_neighbors(map: &HashMap<(i64,i64,i64,i64),Square>, pt: (i64,i64,i64,i64)) -> i64 {
- neighbors(pt)
- .iter()
- .map(|n| match map.get(&n) {
- Some(Square::Active) => 1,
- _ => 0,
- })
- .sum()
- }
- fn expand_map(map: &mut HashMap<(i64,i64,i64,i64),Square>) {
- let temp = map.clone();
- for (pt,_) in temp.iter() {
- for neighbor in neighbors(*pt) {
- match map.get(&neighbor) {
- Some(_) => {},
- None => { map.insert(neighbor, Square::Inactive); }
- }
- }
- }
- }
- fn part2(input: &str) -> io::Result<()> {
- let file = File::open(input).expect("Input file not found.");
- let reader = BufReader::new(file);
- let input: Vec<String> = match reader.lines().collect() {
- Err(err) => panic!("Unknown error reading input: {}", err),
- Ok(result) => result,
- };
- // Build map
- let mut map: HashMap<(i64,i64,i64,i64),Square> = HashMap::new();
- for (y,line) in input.iter().enumerate() {
- for (x,ch) in line.chars().enumerate() {
- let pt = (x as i64, y as i64, 0 as i64, 0 as i64);
- match ch {
- '#' => { map.insert(pt,Square::Active); },
- '.' => { map.insert(pt,Square::Inactive); },
- other => panic!("Unknown square: {}", other),
- }
- }
- }
- let mut cycle = 0;
- 'main_lp: loop {
- // Expand map to track neighbors
- expand_map(&mut map);
- cycle += 1;
- let current = map.clone();
- for (pt,sq) in current.iter() {
- let active_neighbors = count_neighbors(¤t,*pt);
- match sq {
- Square::Active => {
- if !(2..=3).contains(&active_neighbors) {
- map.insert(*pt,Square::Inactive);
- }
- },
- Square::Inactive => {
- if active_neighbors == 3 {
- map.insert(*pt,Square::Active);
- }
- }
- }
- }
- if cycle == BOOT_CYCLES { break 'main_lp; }
- }
- let part2 = map
- .iter()
- .filter(|(_,v)| v == &&Square::Active)
- .count();
- println!("Part 2: {}", part2); // 2084
- Ok(())
- }
- fn main() {
- let args: Vec<String> = env::args().collect();
- let filename = &args[1];
- part2(&filename).unwrap();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement