Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@archer884
Last active December 4, 2017 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archer884/bb3f1b9b595b3b5cfd30f5f466b81ca5 to your computer and use it in GitHub Desktop.
Save archer884/bb3f1b9b595b3b5cfd30f5f466b81ca5 to your computer and use it in GitHub Desktop.
AOC/4 (Rust)
#![feature(test)]
#[cfg(test)]
extern crate test;
extern crate fxhash;
extern crate rayon;
static INPUT: &str = include_str!("../input.txt");
fn main() {
println!("{}", count_valid_passphrases(INPUT));
}
fn count_valid_passphrases(s: &str) -> usize {
use rayon::prelude::*;
s.par_lines().filter(|&s| is_valid(s)).count()
}
fn is_valid(s: &str) -> bool {
use fxhash::FxHashSet;
let mut set = FxHashSet::default();
s.split_whitespace().map(WordMap::new).all(|map| set.insert(map))
}
#[derive(Eq, PartialEq, Hash)]
struct WordMap([u8; 26]);
impl WordMap {
fn new<T: AsRef<[u8]>>(s: T) -> Self {
let mut map = [0u8; 26];
for u in s.as_ref() {
unsafe {
// Believe it or not, this is worth 30 nanoseconds per iteration.
// I know. I'm a little surprised myself.
*map.get_unchecked_mut((u - b'a') as usize) += 1;
}
}
WordMap(map)
}
}
#[cfg(test)]
mod tests {
use test::{self, Bencher};
#[test]
fn count_valid_passphrases() {
assert_eq!(208, super::count_valid_passphrases(super::INPUT));
}
#[bench]
fn bench_version1(b: &mut Bencher) {
let input = "qvuv wteohr daynue nehs gzqu porzrsk cqokye zzsbqox rqh ogxtn pskorrz";
b.iter(|| test::black_box(super::is_valid(input)));
}
#[bench]
fn bench_whole_thing(b: &mut Bencher) {
b.iter(|| test::black_box(super::count_valid_passphrases(super::INPUT)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment