Skip to content

Commit 83e8311

Browse files
committed
feat: add neighbors
1 parent 6231938 commit 83e8311

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

open_the_lock/src/lib.rs

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
11
pub struct Solution {}
22

33
impl Solution {
4-
fn digit_neighbors(n: u8) -> (u8, u8) {
5-
((n + 9) % 10, (n + 11) % 10)
4+
fn digit_neighbors(c: char) -> Vec<char> {
5+
let n = c.to_digit(10).unwrap();
6+
vec![
7+
char::from_digit((n + 9) % 10, 10).unwrap(),
8+
char::from_digit((n + 1) % 10, 10).unwrap(),
9+
]
10+
}
11+
12+
fn neighbors(wheels: &str) -> Vec<String> {
13+
wheels
14+
.char_indices()
15+
.map(|(i, c)| {
16+
Solution::digit_neighbors(c)
17+
.iter()
18+
.map(|x| {
19+
let mut w = wheels.to_string();
20+
w.replace_range(i..i + 1, &x.to_string());
21+
w
22+
})
23+
.collect()
24+
})
25+
.collect::<Vec<Vec<String>>>()
26+
.concat()
627
}
728

829
pub fn open_lock(deadends: Vec<String>, target: String) -> i32 {
@@ -16,13 +37,27 @@ mod tests {
1637

1738
#[test]
1839
fn test_digit_neighbors() {
19-
assert_eq!(Solution::digit_neighbors(0), (9, 1));
20-
assert_eq!(Solution::digit_neighbors(9), (8, 0));
40+
assert_eq!(Solution::digit_neighbors('0'), vec!['9', '1']);
41+
assert_eq!(Solution::digit_neighbors('9'), vec!['8', '0']);
2142
for n in 1..9 {
22-
assert_eq!(Solution::digit_neighbors(n), (n - 1, n + 1));
43+
assert_eq!(
44+
Solution::digit_neighbors(char::from_digit(n, 10).unwrap()),
45+
vec![
46+
char::from_digit(n - 1, 10).unwrap(),
47+
char::from_digit(n + 1, 10).unwrap()
48+
]
49+
);
2350
}
2451
}
2552

53+
#[test]
54+
fn test_neighbors() {
55+
assert_eq!(
56+
Solution::neighbors("0201"),
57+
vec!["9201", "1201", "0101", "0301", "0291", "0211", "0200", "0202"],
58+
);
59+
}
60+
2661
#[test]
2762
fn example_1() {
2863
let deadends = ["0201", "0101", "0102", "1212", "2002"];

0 commit comments

Comments
 (0)