···
3
+
subroutine append_to_integer_array(arr, val)
4
+
integer, allocatable, intent(inout) :: arr(:)
5
+
integer, intent(in) :: val
6
+
integer, allocatable :: temp(:)
7
+
if(.not. allocated(arr)) then
8
+
ERROR STOP 'Array not allocated'
10
+
allocate(temp(size(arr) + 1))
11
+
temp(1:size(arr)) = arr
12
+
temp(size(arr) + 1) = val
13
+
call move_alloc(temp, arr)
14
+
end subroutine append_to_integer_array
15
+
end module day_05_utils
19
+
integer :: io, ios, idx, a, b, ct, i, j, res
20
+
integer, allocatable :: left(:), right(:), print_list(:), work(:)
21
+
character(len=100) ::line
24
+
open(newunit=io, file='./day_05_input.txt', status='old', action='read')
27
+
read(io, '(a)', iostat=ios) line
28
+
if(ios /= 0) exit !eof
29
+
idx = index(line, '|')
30
+
if(idx > 0) then ! rules
31
+
read(line(1:idx-1), *) a
32
+
read(line(idx+1:), *) b
33
+
if(.not. allocated(left)) then
37
+
call append_to_integer_array(left, a)
39
+
if(.not. allocated(right)) then
43
+
call append_to_integer_array(right, b)
46
+
idx = index(line, ',')
47
+
if (idx > 0 ) then ! print_list
49
+
do i = 1 , len_trim(line)
50
+
if(line(i:i) == ',') then
54
+
allocate(print_list(ct))
55
+
read(line, *) print_list
57
+
do i = 1, size(print_list)
58
+
if(i+1 < size(print_list)) then ! if we can check forward
59
+
do j = 1, size(right) ! find value in right and save left to work
60
+
if (print_list(i) == right(j)) then
61
+
if(.not. allocated(work)) then
65
+
call append_to_integer_array(work, left(j))
69
+
do j = 1, size(work)
70
+
if(any(print_list(i+1:size(print_list)) == work(j))) then
77
+
if(.not. found) then ! if we are still valid lets keep going
78
+
if(i-1 > 0) then ! if we can check backwards
79
+
do j = 1, size(left) ! find value in left and save left to work
80
+
if (print_list(i) == left(j)) then
81
+
if(.not. allocated(work)) then
85
+
call append_to_integer_array(work, right(j))
89
+
do j = 1, size(work)
90
+
if(any(print_list(1:i-1) == work(j))) then
101
+
if (.not. found) then
102
+
res = res + print_list((size(print_list) + 1)/2)
105
+
deallocate(print_list)
111
+
print*, "Result ", res