1
1
// Usage: cd 2021/day02 && cargo run
2
2
3
- use itertools:: Itertools ;
3
+ use std:: io:: { self , Error , ErrorKind , Read , Write } ;
4
+ use std:: str:: FromStr ;
4
5
5
6
6
- // Command
7
+ // Command
7
8
enum CommandType {
8
9
Forward ( u8 ) ,
9
10
Down ( u8 ) ,
@@ -28,25 +29,58 @@ impl Submarine {
28
29
29
30
}
30
31
31
- fn process ( & self , cmds : & [ CommandType ] ) {
32
-
32
+ fn process ( & mut self , cmds : & [ CommandType ] ) {
33
+ for cmdin cmds{
34
+ match cmd{
35
+ CommandType :: Forward ( v) =>{
36
+ self . h_pos +=* vas u32 ;
37
+ }
38
+ CommandType :: Down ( v) =>{
39
+ self . depth +=* vas u32 ;
40
+ }
41
+ CommandType :: Up ( v) =>{
42
+ self . depth -=* vas u32 ;
43
+ }
44
+ }
45
+ }
33
46
}
47
+ }
34
48
35
-
49
+ use std:: num:: ParseIntError ;
50
+
51
+ impl FromStr for CommandType {
52
+
53
+ fn from_str ( line : & str ) ->Result < Self , ParseIntError > {
54
+ let mut words = line. split_ascii_whitespace ( ) ;
55
+ let first = words
56
+ . next ( )
57
+ . ok_or_else ( ||Err ( "Invalid input" ) ) ;
58
+ let second = words
59
+ . next ( )
60
+ . ok_or_else ( ||Err ( "Invalid input" ) ) ?
61
+ . parse :: < u8 > ( ) ?;
62
+ match first{
63
+ "forward" =>Ok ( CommandType :: Forward ( second) ) ,
64
+ "down" =>Ok ( CommandType :: Down ( second) ) ,
65
+ "up" =>Ok ( CommandType :: Up ( second) ) ,
66
+ _ =>Err ( "Invalid input" ) ,
67
+ }
68
+ }
36
69
}
37
70
38
- fn parse_input ( input : & str ) ->Vec < i32 > {
39
- input. lines ( )
40
- . filter_map ( |n| n. parse :: < i32 > ( ) . ok ( ) )
41
- . collect ( )
71
+ fn parse_input ( input : & str ) ->Vec < CommandType > {
72
+ input
73
+ . lines ( )
74
+ . map ( |line|CommandType :: from_str ( line) )
75
+ . collect :: < std:: result:: Result < Vec < _ > , _ > > ( ) ?;
42
76
}
43
77
44
- fn part_1 ( input : & [ i32 ] ) {
78
+ fn part_1 ( input : & [ CommandType ] ) {
45
79
46
- println ! ( "part_1={}" , sum) ;
80
+ // println!("part_1={}", sum);
47
81
}
48
82
49
- fn part_2 ( input : Vec < i32 > ) {
83
+ fn part_2 ( input : & [ CommandType ] ) {
50
84
51
85
}
52
86