AdventOfFortran/2023/src/day08.f90

77 lines
2.0 KiB
Fortran

program day8
implicit none
integer, parameter :: max_chars = 400
integer, parameter :: max_nodes = 1000
integer, parameter :: max_iter = 100000
character(200) :: fname
character(max_chars) :: fline
integer :: n_arguments
integer :: istat
character(max_chars) :: dir_ins
integer :: n_dir_ins
integer :: n_nodes
character(len=3) :: node
character(len=1) :: dir
character(len=3) :: nodes(1:max_nodes), lnodes(1:max_nodes), rnodes(1:max_nodes)
integer :: i, i2, cur, LRcur
n_arguments = command_argument_count()
if (n_arguments .eq. 1) then
call get_command_argument(1, fname)
print *, "File: ", trim(fname)
print *
else
print *, "Wrong number of arguments: ", n_arguments
stop
end if
open(10, file=fname)
read(10, "(a)") dir_ins
n_dir_ins = len_trim(dir_ins)
read(10, "(a)") fline
n_nodes = 0
do i=1,max_nodes
read(10, "(a)", iostat=istat) fline
if ((len_trim(fline) .eq. 0) .or. (is_iostat_end(istat))) then
exit
end if
read(fline(1:3), "(a)") nodes(i)
read(fline(8:10), "(a)") lnodes(i)
read(fline(13:15), "(a)") rnodes(i)
n_nodes = n_nodes + 1
end do
close(10)
cur = -1
do i=1, n_nodes
if (nodes(i) .eq. "AAA") then
cur = i
exit
end if
end do
do i=1,max_iter
LRcur = mod(i-1, n_dir_ins) + 1
dir = dir_ins(LRcur:LRcur)
if (dir .eq. "L") then
node = lnodes(cur)
else
node = rnodes(cur)
end if
do i2=1, n_nodes
if (nodes(i2) .eq. node) then
cur = i2
exit
end if
end do
if (nodes(cur) .eq. "ZZZ") then
exit
end if
end do
if (nodes(cur) .eq. "ZZZ") then
print *, "Found node ZZZ after ", i, " iterations"
else
print *, "Did not find node ZZZ after ", i, " iterations"
end if
end program day8