1
1
use std:: fs;
2
2
3
3
enum Instr {
4
- Up ( usize ) ,
5
- Down ( usize ) ,
6
- Forward ( usize )
4
+ Up ( usize ) ,
5
+ Down ( usize ) ,
6
+ Forward ( usize ) ,
7
7
}
8
8
9
- fn to_instr ( line : & str ) -> Instr {
10
- let tokens: Vec < & str > = line. split_ascii_whitespace ( ) . collect ( ) ;
9
+ fn to_instr ( line : & str ) -> Instr {
10
+ let tokens: Vec < & str > = line. split_ascii_whitespace ( ) . collect ( ) ;
11
11
match ( tokens[ 0 ] , tokens[ 1 ] . parse :: < usize > ( ) . unwrap ( ) ) {
12
12
( "down" , num) => Instr :: Down ( num) ,
13
13
( "up" , num) => Instr :: Up ( num) ,
14
14
( "forward" , num) => Instr :: Forward ( num) ,
15
- _ => panic ! ( )
15
+ _ => panic ! ( ) ,
16
16
}
17
17
}
18
18
@@ -25,35 +25,37 @@ fn parse(fname: &str) -> Vec<Instr> {
25
25
}
26
26
27
27
#[ test]
28
- fn test_part1 ( ) {
28
+ fn test_part1 ( ) {
29
29
assert_eq ! ( part1( parse( "test0" ) ) , 150 )
30
30
}
31
31
32
32
fn part1 ( instrs : Vec < Instr > ) -> usize {
33
- let ( h, d) = instrs
33
+ let ( h, d) = instrs
34
34
. iter ( )
35
- . fold ( ( 0usize , 0usize ) , |( horiz, depth) , instr| match instr {
36
- Instr :: Up ( x) => ( horiz, depth- x) ,
37
- Instr :: Down ( x) => ( horiz, depth+ x) ,
38
- Instr :: Forward ( x) => ( horiz+ x, depth) ,
35
+ . fold ( ( 0usize , 0usize ) , |( horiz, depth) , instr| match instr {
36
+ Instr :: Up ( x) => ( horiz, depth - x) ,
37
+ Instr :: Down ( x) => ( horiz, depth + x) ,
38
+ Instr :: Forward ( x) => ( horiz + x, depth) ,
39
39
} ) ;
40
- h* d
40
+ h * d
41
41
}
42
42
43
43
#[ test]
44
- fn test_part2 ( ) {
44
+ fn test_part2 ( ) {
45
45
assert_eq ! ( part2( parse( "test0" ) ) , 900 )
46
46
}
47
47
48
48
fn part2 ( instrs : Vec < Instr > ) -> usize {
49
- let ( h, d, _) = instrs
50
- . iter ( )
51
- . fold ( ( 0usize , 0usize , 0usize ) , |( horiz, depth, aim) , instr| match instr {
52
- Instr :: Up ( x) => ( horiz, depth, aim-x) ,
53
- Instr :: Down ( x) => ( horiz, depth, aim+x) ,
54
- Instr :: Forward ( x) => ( horiz+x, depth+( aim* x) , aim) ,
55
- } ) ;
56
- h* d
49
+ let ( h, d, _) =
50
+ instrs. iter ( ) . fold (
51
+ ( 0usize , 0usize , 0usize ) ,
52
+ |( horiz, depth, aim) , instr| match instr {
53
+ Instr :: Up ( x) => ( horiz, depth, aim - x) ,
54
+ Instr :: Down ( x) => ( horiz, depth, aim + x) ,
55
+ Instr :: Forward ( x) => ( horiz + x, depth + ( aim * x) , aim) ,
56
+ } ,
57
+ ) ;
58
+ h * d
57
59
}
58
60
59
61
fn main ( ) {
0 commit comments