-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
108 lines (95 loc) · 2.73 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
extern crate regex;
extern crate crypto;
#[macro_use] extern crate lazy_static;
use regex::Regex;
use std::collections::HashMap;
fn md5(s: String) -> String {
use crypto::digest::Digest;
let mut sh = crypto::md5::Md5::new();
sh.input_str(&s);
sh.result_str()
}
fn get_triple(s: &str) -> Option<char> {
lazy_static! {
static ref RE: Regex = Regex::new(r"(000|111|222|333|444|555|666|777|888|999|000|aaa|bbb|ccc|ddd|eee|fff)").unwrap();
}
match RE.captures(s) {
Some(caps) => caps.at(1).unwrap().chars().next(),
None => None
}
}
fn has_quintuple(digit: char, s: &str) -> bool {
let re = format!("{0}{0}{0}{0}{0}", digit);
regex::is_match(&re , s).unwrap_or(false)
}
#[derive(Debug)]
pub struct HashStore {
store: HashMap<usize, String>,
salt: String,
}
impl HashStore {
pub fn new(salt: &str) -> HashStore {
HashStore {
store: HashMap::new(),
salt: salt.to_owned(),
}
}
pub fn get<'a>(&'a mut self, index: usize) -> &'a str {
let ref salt = self.salt;
let entry = self.store.entry(index).or_insert_with(|| {
md5(format!("{}{}", salt, index))
});
entry
}
pub fn get_stretch<'a>(&'a mut self, index: usize) -> &'a str {
let ref salt = self.salt;
let entry = self.store.entry(index).or_insert_with(||{
let mut hash = md5(format!("{}{}", salt, index));
let mut iter = 0;
while iter < 2016 {
hash = md5(hash);
iter += 1;
}
hash
});
entry
}
}
fn main() {
let mut store = HashStore::new("ahsbgdzn");
let mut num_found = 0;
let mut index = 1;
while num_found < 64 {
match get_triple(store.get(index)) {
Some(digit) => {
for j in (index + 1)..(index + 1001) {
if has_quintuple(digit, store.get(j)) {
num_found += 1;
break;
}
}
index += 1;
},
None => { index += 1; },
}
}
println!("Part 1 answer = {}", index - 1);
store = HashStore::new("ahsbgdzn");
num_found = 0;
index = 1;
while num_found < 64 {
match get_triple(store.get_stretch(index)) {
Some(digit) => {
for j in (index + 1)..(index + 1001) {
if has_quintuple(digit, store.get_stretch(j)) {
num_found += 1;
break;
}
}
index += 1;
},
None => { index += 1; },
}
}
println!("Part 2 answer = {}", index-1);
}