Skip to content

Instantly share code, notes, and snippets.

@matklad
Last active February 14, 2017 09:37
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 matklad/3dc7b75e2d2961e0ab7b18f97a6d6eee to your computer and use it in GitHub Desktop.
Save matklad/3dc7b75e2d2961e0ab7b18f97a6d6eee to your computer and use it in GitHub Desktop.
Adeven of code 2016 day 5
extern crate crypto; // [dependencies] rust-crypto = "0.2"
extern crate rayon; // [dependencies] rayon = "0.6"
use std::io::Cursor;
use std::io::Write;
use crypto::digest::Digest;
use rayon::prelude::*;
//http://adventofcode.com/2016/day/5
fn main() {
let id = "wtnhxymk";
let start = ::std::time::Instant::now();
println!("{}", fast_and_furious(id));
let duration = ::std::time::Instant::now() - start;
println!("{} ms", (duration.as_secs() as u32) * 1000 + duration.subsec_nanos() / 1_000_000);
}
fn fast_and_furious(id: &str) -> String {
let chunk_size = 100000;
(0..)
.map(|i| i * chunk_size..(i + 1) * chunk_size)
.map(|chunk| {
chunk.into_par_iter()
.map(|n| {
// Yay, 0 allocation hashing!
let id_buff: &mut [u8] = &mut [0u8; 32];
let full_id = {
let mut cursor = Cursor::new(id_buff);
write!(cursor, "{}{}", id, n).unwrap();
let last = cursor.position() as usize;
&cursor.into_inner()[..last]
};
let full_hash = {
let mut hash_buf = [0u8; 256];
let mut hasher = crypto::md5::Md5::new();
hasher.input(full_id);
hasher.result(&mut hash_buf);
hash_buf
};
let mut hash = [0u8; 3]; // 6 characters is 3 bytes with hex encoding
hash.copy_from_slice(&full_hash[..3]);
hash
})
.filter(|h| h[0] == 0 && h[1] == 0 && h[2] >> 4 == 0)
.map(|h| h[2] & 0xff)
.collect::<Vec<_>>()
})
.flat_map(|xs| xs.into_iter())
.take(8)
.map(|d| ::std::char::from_digit(d as u32, 16).unwrap())
.collect()
}
fn fast(id: &str) -> String {
(0..)
.map(|n| {
// Yay, 0 allocation hashing!
let id_buff: &mut [u8] = &mut [0u8; 32];
let full_id = {
let mut cursor = Cursor::new(id_buff);
write!(cursor, "{}{}", id, n).unwrap();
let last = cursor.position() as usize;
&cursor.into_inner()[..last]
};
let full_hash = {
let mut hash_buf = [0u8; 256];
let mut hasher = crypto::md5::Md5::new();
hasher.input(full_id);
hasher.result(&mut hash_buf);
hash_buf
};
let mut hash = [0u8; 3]; // 6 characters is 3 bytes with hex encoding
hash.copy_from_slice(&full_hash[..3]);
hash
})
.filter(|h| h[0] == 0 && h[1] == 0 && h[2] >> 4 == 0)
.map(|h| h[2] & 0xff)
.take(8)
.map(|d| ::std::char::from_digit(d as u32, 16).unwrap())
.collect()
}
fn short(id: &str) -> String {
(0..)
.map(|n| format!("{}{}", id, n))
.map(|full_id| {
let mut hasher = crypto::md5::Md5::new();
hasher.input_str(&full_id);
hasher.result_str()
})
.filter(|h| h.starts_with("00000"))
.map(|h| h.chars().nth(5).unwrap())
.take(8)
.collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment