Skip to content

Commit

Permalink
Day 22b
Browse files Browse the repository at this point in the history
  • Loading branch information
lpenz committed Dec 22, 2023
1 parent fedd6ba commit a1e1bb6
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 12 deletions.
13 changes: 1 addition & 12 deletions day22/src/bin/day22a.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,7 @@ fn can_disintegrate(bricks: &[Brick], b: &Brick) -> bool {

fn process(bufin: impl BufRead) -> Result<usize> {
let mut bricks = parser::parse(bufin)?;
let mut changed = true;
while changed {
let old = bricks.clone();
changed = false;
for b in &mut bricks {
if let Some(z) = falls_to(&old, b) {
let height = b.2.max() - b.2.min();
b.2 = Range::new(z, z + height);
changed = true;
}
}
}
settle_bricks(&mut bricks);
Ok(bricks
.par_iter()
.filter(|b| can_disintegrate(&bricks, b))
Expand Down
32 changes: 32 additions & 0 deletions day22/src/bin/day22b.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (C) 2023 Leandro Lisboa Penz <lpenz@lpenz.org>
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.

use day22::*;

use rayon::prelude::*;

fn would_fall(bricks: &[Brick], b: &Brick) -> usize {
let mut bricks = bricks
.iter()
.filter(|o| o != &b)
.copied()
.collect::<Vec<_>>();
settle_bricks(&mut bricks)
}

fn process(bufin: impl BufRead) -> Result<usize> {
let mut bricks = parser::parse(bufin)?;
settle_bricks(&mut bricks);
Ok(bricks.par_iter().map(|b| would_fall(&bricks, b)).sum())
}

#[test]
fn test() -> Result<()> {
assert_eq!(process(EXAMPLE.as_bytes())?, 7);
Ok(())
}

fn main() -> Result<()> {
do_main(|| process(stdin().lock()))
}
19 changes: 19 additions & 0 deletions day22/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
pub use aoc::*;

use std::cmp::min;
use std::collections::HashSet;

pub const EXAMPLE: &str = "1,0,1~1,2,1
0,0,2~2,0,2
Expand Down Expand Up @@ -114,3 +115,21 @@ pub fn falls_to(bricks: &[Brick], b: &Brick) -> Option<i64> {
(b.2.min() != 1).then_some(1)
}
}

pub fn settle_bricks(bricks: &mut [Brick]) -> usize {
let mut changed = true;
let mut fell = HashSet::<usize>::new();
while changed {
let old = bricks.to_vec();
changed = false;
for (i, b) in bricks.iter_mut().enumerate() {
if let Some(z) = falls_to(&old, b) {
let height = b.2.max() - b.2.min();
b.2 = Range::new(z, z + height);
fell.insert(i);
changed = true;
}
}
}
fell.len()
}

0 comments on commit a1e1bb6

Please sign in to comment.