Skip to content

Commit

Permalink
day03: And now the semi-efficient point set.
Browse files Browse the repository at this point in the history
  • Loading branch information
jld committed Dec 19, 2019
1 parent f4a558d commit 4d2a81a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions day03/src/main.rs
@@ -1,4 +1,5 @@
mod geom;
mod point_set;

fn main() {
println!("Hello, world!");
Expand Down
45 changes: 45 additions & 0 deletions day03/src/point_set.rs
@@ -0,0 +1,45 @@
use std::collections::HashMap;

use crate::geom::{Point, Coord};

type BitSet = u64;

fn split(p: Point) -> (Point, BitSet) {
let xh = p.x >> 3;
let yh = p.y >> 3;
let xl = p.x & 7;
let yl = p.y & 7;
let b = (yl << 3) + xl;
(Point { x: xh, y: yh }, 1 << b)
}

pub struct PointSet {
inner: HashMap<Point, BitSet>
}

impl PointSet {
pub fn new() -> Self {
Self { inner: HashMap::new() }
}

pub fn contains(&self, p: Point) -> bool {
let (key, mask) = split(p);
self.inner.get(&key).cloned().unwrap_or(0) & mask != 0
}

pub fn insert(&mut self, p: Point) -> bool {
let (key, mask) = split(p);
let grid_ptr = self.inner.entry(key).or_insert(0);
let old = *grid_ptr & mask != 0;
*grid_ptr |= mask;
return old;
}

pub fn remove(&mut self, p: Point) -> bool {
let (key, mask) = split(p);
let grid_ptr = self.inner.entry(key).or_insert(0);
let old = *grid_ptr & mask != 0;
*grid_ptr &= !mask;
return old;
}
}

0 comments on commit 4d2a81a

Please sign in to comment.