2020: day14: refacto to prepare part 2
This commit is contained in:
parent
514a93213c
commit
b0c1b83c19
|
@ -22,22 +22,25 @@ fn part1(input: &str) -> aoc::Result<u64> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
enum MaskType {
|
enum Mask {
|
||||||
And,
|
Floating,
|
||||||
Or,
|
One,
|
||||||
|
Zero,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct BitMask {
|
struct BitMask {
|
||||||
masks: Vec<(MaskType, u64)>,
|
masks: Vec<Mask>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BitMask {
|
impl BitMask {
|
||||||
fn apply(&self, mut n: u64) -> u64 {
|
/// function used for part 1: 'X' bits just don't do anything
|
||||||
for (mask_type, mask) in &self.masks {
|
fn apply_no_floating(&self, mut n: u64) -> u64 {
|
||||||
match mask_type {
|
for (offset, mask) in self.masks.iter().enumerate() {
|
||||||
MaskType::And => n &= mask,
|
match mask {
|
||||||
MaskType::Or => n |= mask,
|
Mask::Floating => {}
|
||||||
|
Mask::One => n |= 1 << offset,
|
||||||
|
Mask::Zero => n &= !(1 << offset),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -52,18 +55,14 @@ impl std::str::FromStr for BitMask {
|
||||||
let masks = s
|
let masks = s
|
||||||
.chars()
|
.chars()
|
||||||
.rev()
|
.rev()
|
||||||
.enumerate()
|
.map(|c| {
|
||||||
.filter_map(|(idx, c)| match c {
|
// idx will never be higher than 36 so this is fine
|
||||||
'1' => {
|
match c {
|
||||||
let m = 1 << idx;
|
'1' => Ok(Mask::One),
|
||||||
Some(Ok((MaskType::Or, m)))
|
'0' => Ok(Mask::Zero),
|
||||||
|
'X' => Ok(Mask::Floating),
|
||||||
|
_ => Err(err!("unknown character in mask: `{}`", c)),
|
||||||
}
|
}
|
||||||
'0' => {
|
|
||||||
let m = !(1 << idx);
|
|
||||||
Some(Ok((MaskType::And, m)))
|
|
||||||
}
|
|
||||||
'X' => None,
|
|
||||||
_ => Some(Err(err!("unknown character in mask: `{}`", c))),
|
|
||||||
})
|
})
|
||||||
.collect::<aoc::Result<_>>()?;
|
.collect::<aoc::Result<_>>()?;
|
||||||
|
|
||||||
|
@ -134,7 +133,8 @@ impl Program {
|
||||||
|
|
||||||
Instruction::MemWrite { offset, value } => match &self.current_mask {
|
Instruction::MemWrite { offset, value } => match &self.current_mask {
|
||||||
Some(bitmask) => {
|
Some(bitmask) => {
|
||||||
self.memory.insert(*offset, bitmask.apply(*value));
|
self.memory
|
||||||
|
.insert(*offset, bitmask.apply_no_floating(*value));
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
return Err(err!("tried to execute MemWrite but mask isn't initialized"))
|
return Err(err!("tried to execute MemWrite but mask isn't initialized"))
|
||||||
|
|
Loading…
Reference in a new issue