File tree 5 files changed +94
-0
lines changed
5 files changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ [package ]
2
+ name = " advent-of-code-2024-12a"
3
+ version = " 0.1.0"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ description = " Solution to Advent of Code 2024, problem 12a"
7
+ authors.workspace = true
8
+ repository.workspace = true
9
+ license.workspace = true
10
+ publish.workspace = true
11
+
12
+ [dependencies ]
13
+ adventutil = { path = " ../../adventutil" }
14
+
15
+ [lints ]
16
+ workspace = true
Original file line number Diff line number Diff line change
1
+ use adventutil:: grid:: { Direction , Grid } ;
2
+ use adventutil:: { components, Input } ;
3
+
4
+ fn solve ( input : Input ) -> usize {
5
+ // Make this a reference to simplify the `move`-ing of `grid` into
6
+ // closures:
7
+ let grid = & input. parse :: < Grid < char > > ( ) ;
8
+ let comps = components ( grid. iter_coords ( ) , |c| {
9
+ Direction :: cardinals ( ) . filter_map ( move |d| {
10
+ grid. bounds ( )
11
+ . move_in ( c, d)
12
+ . filter ( |& c2| grid[ c] == grid[ c2] )
13
+ } )
14
+ } ) ;
15
+ let mut price = 0 ;
16
+ for region in & comps {
17
+ let area = region. len ( ) ;
18
+ let perimeter: usize = region
19
+ . iter ( )
20
+ . map ( |& c| {
21
+ Direction :: cardinals ( )
22
+ . filter ( move |& d| {
23
+ grid. bounds ( )
24
+ . move_in ( c, d)
25
+ . is_none_or ( |c2| !region. contains ( & c2) )
26
+ } )
27
+ . count ( )
28
+ } )
29
+ . sum ( ) ;
30
+ price += area * perimeter;
31
+ }
32
+ price
33
+ }
34
+
35
+ fn main ( ) {
36
+ println ! ( "{}" , solve( Input :: from_env( ) ) ) ;
37
+ }
38
+
39
+ #[ cfg( test) ]
40
+ mod tests {
41
+ use super :: * ;
42
+
43
+ #[ test]
44
+ fn test_example1 ( ) {
45
+ let input = Input :: from ( "AAAA\n BBCD\n BBCC\n EEEC\n " ) ;
46
+ assert_eq ! ( solve( input) , 140 ) ;
47
+ }
48
+
49
+ #[ test]
50
+ fn test_example2 ( ) {
51
+ let input = Input :: from ( "OOOOO\n OXOXO\n OOOOO\n OXOXO\n OOOOO\n " ) ;
52
+ assert_eq ! ( solve( input) , 772 ) ;
53
+ }
54
+
55
+ #[ test]
56
+ fn test_example3 ( ) {
57
+ let input = Input :: from ( concat ! (
58
+ "RRRRIICCFF\n " ,
59
+ "RRRRIICCCF\n " ,
60
+ "VVRRRCCFFF\n " ,
61
+ "VVRCCCJFFF\n " ,
62
+ "VVVVCJJCFE\n " ,
63
+ "VVIVCCJJEE\n " ,
64
+ "VVIIICJJEE\n " ,
65
+ "MIIIIIJJEE\n " ,
66
+ "MIIISIJEEE\n " ,
67
+ "MMMISSJEEE\n " ,
68
+ ) ) ;
69
+ assert_eq ! ( solve( input) , 1930 ) ;
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments