-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
131 lines (106 loc) · 2.5 KB
/
lib.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use common::Answer;
use std::fmt::Display;
#[derive(Debug, Clone, Copy)]
struct Letter(u8);
impl From<char> for Letter {
fn from(value: char) -> Self {
Letter(value as u8)
}
}
impl Display for Letter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0 as char)
}
}
impl Letter {
fn increment(&mut self) -> bool {
match self.0 {
122 => {
self.0 = 97;
false
}
104 | 107 | 110 => {
self.0 += 2;
true
}
_ => {
self.0 += 1;
true
}
}
}
}
#[derive(Debug, Clone)]
struct Password(Vec<Letter>);
impl From<&str> for Password {
fn from(value: &str) -> Self {
Password(value.trim_end().chars().map(Letter::from).collect())
}
}
fn repetitions(arr: &[u8]) -> usize {
let mut prev = 0;
let mut count = 0;
for &c in arr.iter() {
if c == prev {
count += 1;
prev = 0;
} else {
prev = c;
}
}
count
}
impl Password {
fn increment(&mut self) {
for c in self.0.iter_mut().rev() {
if c.increment() {
break;
}
}
}
fn to_vec(&self) -> Vec<u8> {
self.0.iter().map(|c| c.0).collect()
}
fn is_valid(&self) -> bool {
let vec = self.to_vec();
vec.windows(3).any(|w| w[0] + 1 == w[1] && w[1] + 1 == w[2]) && repetitions(&vec) >= 2
}
}
impl Display for Password {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for l in self.0.iter() {
l.fmt(f)?;
}
Ok(())
}
}
pub fn step1(s: &str) -> Answer {
let mut pw = Password::from(s);
while !pw.is_valid() {
pw.increment();
}
pw.to_string().into()
}
pub fn step2(s: &str) -> Answer {
let mut pw = Password::from(s);
while !pw.is_valid() {
pw.increment();
}
pw.increment();
while !pw.is_valid() {
pw.increment();
}
pw.to_string().into()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn validate_can_validate_passwords() {
assert!(!Password::from("hijklmmn").is_valid());
assert!(!Password::from("abbceffg").is_valid());
assert!(!Password::from("abbcegjk").is_valid());
assert!(!Password::from("ghijklmn").is_valid());
assert!(Password::from("ghjaabcc").is_valid());
}
}