aboutsummaryrefslogtreecommitdiff
path: root/2024/day_04.f90
blob: 3be12da0bf9fb0b24291a12379fc793763f6d664 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
module day_04_utils
   implicit none
contains
   recursive function find_xmas(arr, row, col,row_dir, col_dir, search_letter) result(found)
      implicit none
      character(len=140), intent(in), allocatable :: arr(:)
      character(len=1), intent(in) :: search_letter
      integer, intent(in) :: row, col, row_dir, col_dir
      integer :: new_row, new_col
      logical :: found

      if(arr(row)(col:col) == search_letter) then
         if(search_letter == 'S') then
            found = .true.
         else
            new_row = row + row_dir
            new_col = col + col_dir
            if(new_row > len(arr(row)) .or. new_row < 1 .or. new_col > size(arr) .or. new_col < 1) then
               found = .false.
            else
               select case(search_letter)
                case('M')
                  found = find_xmas(arr, new_row, new_col, row_dir, col_dir, 'A')
                case('A')
                  found = find_xmas(arr, new_row, new_col, row_dir, col_dir, 'S')
               end select
            end if
         end if
      else
         found = .false.
      end if
   end function find_xmas
end module day_04_utils
program day_04
   use day_04_utils
   implicit none
   character(len=140) , allocatable :: lines(:)
   integer :: io, row, col, score, z
   logical :: found

   score = 0
   open(newunit=io, file='./day_04_input.txt', status='old', action='read')
   allocate(lines(140))
   read(io, '(a)') lines
   do row = 1, size(lines)
      do col = 1, len(lines(row))
         if (lines(row)(col:col) == 'X') then
            do z = 1, 8
               found = .false.
               select case (z)
                case(1)
                  found = find_xmas(lines, row, col-1, 0, -1, 'M')
                case(2)
                  found = find_xmas(lines, row-1, col-1, -1, -1, 'M')
                case(3)
                  found = find_xmas(lines, row-1, col, -1, 0, 'M')
                case(4)
                  found = find_xmas(lines, row-1, col+1,  -1, 1, 'M')
                case(5)
                  found = find_xmas(lines, row, col+1, 0, 1, 'M')
                case(6)
                  found = find_xmas(lines, row+1, col+1, 1, 1, 'M')
                case(7)
                  found = find_xmas(lines, row+1, col, 1, 0, 'M')
                case(8)
                  found = find_xmas(lines, row+1, col-1, 1, -1, 'M')
               end select
               if(found) then
                  score = score + 1
               end if
            end do
         end if
      end do
   end do
   deallocate(lines)
   print*, score

end program day_04