Compare commits

...

3 Commits

Author SHA1 Message Date
1e34e0abea Day 4 try using bit comparisons to find bingo.
This is actually slower for some reason.
2021-12-06 20:42:24 -08:00
10fe6a570e Day 4 perf improvments v1 2021-12-06 20:01:48 -08:00
343707c63c Day 6 part 2 slightly faster over pre-rotate_left version. 2021-12-06 19:13:46 -08:00
2 changed files with 50 additions and 19 deletions

View File

@ -140,10 +140,45 @@ impl FromStr for Game {
}
}
#[derive(Default)]
struct MarkerBoard(u32);
impl MarkerBoard {
fn mark(&mut self, (x, y): (usize, usize)) {
let bit = 1 << (x + y * 5);
self.0 |= bit;
}
fn is_marked(&self, (x, y): (usize, usize)) -> bool {
let bit = 1 << (x + y * 5);
(self.0 & bit) != 0
}
fn is_bingo(&self) -> bool {
let h = 0b11111;
let v = 0b00001_00001_00001_00001_00001;
let m = self.0;
// Bingo horizontally
false
|| (m & h == h)
|| ((m >> 5 & h) == h)
|| ((m >> 10 & h) == h)
|| ((m >> 15 & h) == h)
|| ((m >> 20 & h) == h)
// Bingo vertically
|| ((m & v) == v)
|| ((m >> 1 & v) == v)
|| ((m >> 2 & v) == v)
|| ((m >> 3 & v) == v)
|| ((m >> 4 & v) == v)
}
}
#[derive(Default)]
struct Board {
numbers: HashMap<(usize, usize), u64>,
marked: HashSet<(usize, usize)>,
marked: MarkerBoard,
}
#[derive(Debug, Error)]
@ -154,23 +189,13 @@ enum BoardError {
impl Board {
fn is_bingo(&self) -> bool {
for y in 0..5 {
if (0..5).all(|x| self.marked.contains(&(x, y))) {
return true;
}
}
for x in 0..5 {
if (0..5).all(|y| self.marked.contains(&(x, y))) {
return true;
}
}
false
self.marked.is_bingo()
}
fn sum_uncovered(&self) -> u64 {
self.numbers
.iter()
.map(|((x, y), v)| {
if !self.marked.contains(&(*x, *y)) {
if !self.marked.is_marked((*x, *y)) {
*v
} else {
0
@ -182,7 +207,7 @@ impl Board {
fn mark(&mut self, num: u64) -> bool {
for ((x, y), v) in self.numbers.iter() {
if *v == num {
self.marked.insert((*x, *y));
self.marked.mark((*x, *y));
return true;
}
}
@ -195,7 +220,7 @@ impl Debug for Board {
writeln!(f)?;
for y in 0..5 {
for x in 0..5 {
if self.marked.contains(&(x, y)) {
if self.marked.is_marked((x, y)) {
let v = format!("{:3}", self.numbers[&(x, y)]);
write!(f, "{}", Green.bold().paint(v))?;
} else {

View File

@ -88,10 +88,16 @@ fn part2(input: &str) -> Result<usize> {
.into_iter()
.for_each(|n| counts[n] += 1);
for _ in 0..256 {
let ready = counts[0];
counts.rotate_left(1);
counts[6] += ready;
counts[8] = ready;
let mut tmp = [0; 9];
for (i, c) in counts.iter().enumerate() {
if i == 0 {
tmp[6] = *c;
tmp[8] = *c;
} else {
tmp[i - 1] += *c;
}
}
counts = tmp;
}
Ok(counts.iter().sum())
}