[2016][rust][2.1]

profile
Alpha Chen 8 years ago
parent b63381ffa8
commit 1abcc5d723

@ -2,24 +2,38 @@ use std::char;
pub fn solve(input: &str) -> String { pub fn solve(input: &str) -> String {
let arrangement = vec![ let arrangement = vec![
vec!['1', '2', '3'], vec![None, None, Some('1'), None, None],
vec!['4', '5', '6'], vec![None, Some('2'), Some('3'), Some('4'), None],
vec!['7', '8', '9'], vec![Some('5'), Some('6'), Some('7'), Some('8'), Some('9')],
vec![None, Some('A'), Some('B'), Some('C'), None],
vec![None, None, Some('D'), None, None],
]; ];
let mut keypad = Keypad { let mut keypad = Keypad {
arrangement: arrangement, arrangement: arrangement,
current: (1, 1), current: (0, 2),
}; };
let mut answer = String::new(); let mut answer = String::new();
for c in input.chars() { for c in input.chars() {
match c { match c {
'U' => { keypad.move_(Dir::Up); }, 'U' => {
'D' => { keypad.move_(Dir::Down); }, keypad.move_(Dir::Up);
'L' => { keypad.move_(Dir::Left); }, }
'R' => { keypad.move_(Dir::Right); }, 'D' => {
'\n' => { answer.push(keypad.button()); }, keypad.move_(Dir::Down);
_ => { unreachable!(); }, }
'L' => {
keypad.move_(Dir::Left);
}
'R' => {
keypad.move_(Dir::Right);
}
'\n' => {
answer.push(keypad.button());
}
_ => {
unreachable!();
}
} }
} }
answer.push(keypad.button()); answer.push(keypad.button());
@ -33,11 +47,11 @@ RRDDD
LURDL LURDL
UUUUD"; UUUUD";
assert_eq!(solve(instructions), "1985".to_string()); assert_eq!(solve(instructions), "5DB3".to_string());
} }
struct Keypad { struct Keypad {
arrangement: Vec<Vec<char>>, arrangement: Vec<Vec<Option<char>>>,
current: (usize, usize), current: (usize, usize),
} }
@ -60,16 +74,19 @@ impl Keypad {
fn button(&self) -> char { fn button(&self) -> char {
let (x, y) = self.current; let (x, y) = self.current;
self.arrangement[y][x].clone() self.arrangement[y][x].unwrap().clone()
} }
fn button_at(&self, x: usize, y: usize) -> Option<char> { fn button_at(&self, x: usize, y: usize) -> Option<char> {
self.arrangement.get(y).and_then(|row| row.get(x)).cloned() self.arrangement.get(y).and_then(|row| row.get(x).and_then(|c| *c))
} }
} }
enum Dir { enum Dir {
Up, Down, Left, Right Up,
Down,
Left,
Right,
} }
#[test] #[test]
@ -78,7 +95,10 @@ fn test_keypad() {
vec!['1', '2', '3'], vec!['1', '2', '3'],
vec!['4', '5', '6'], vec!['4', '5', '6'],
vec!['7', '8', '9'], vec!['7', '8', '9'],
]; ]
.iter()
.map(|row| row.iter().map(|x| Some(*x)).collect())
.collect();
let mut keypad = Keypad { let mut keypad = Keypad {
arrangement: arrangement, arrangement: arrangement,
current: (1, 1), current: (1, 1),

Loading…
Cancel
Save