My yearly advent-of-code solutions
1program day_06_part_2 2 implicit none 3 character(len=130) :: line, lines(130), temp_lines(130) 4 integer:: io, x,y, xd,yd, i, j, ct, o_ct, init_x, init_y, init_xd, init_yd 5 6 open(newunit=io, file='./day_06_input.txt', status='old', action='read') 7 read(io, '(a)') lines 8 9 ct = 0 10 ! find starting position 11 do i = 1, size(lines) 12 if (index(lines(i), '^') > 0) then 13 y = i 14 x = index(lines(i), '^') 15 lines(i)(x:x) = '.' ! replace with a dot to not confuse this part 16 xd = 0 17 yd = -1 18 init_x = x 19 init_y = y 20 init_xd = xd 21 init_yd = yd 22 exit 23 end if 24 end do 25 26 do i = 1, size(lines) 27 do j = 1, len(lines(i)) 28 o_ct = 0 29 ! reset positions 30 x = init_x 31 y = init_y 32 xd = init_xd 33 yd = init_yd 34 temp_lines = lines ! fresh board every run 35 if(temp_lines(i)(j:j) == '.') then 36 temp_lines(i)(j:j) = 'O' ! place obstacle to test 37 ! move until we leave the bounds when we hit a valid spot mark it with an X and increase count 38 do 39 ! are we going out of bounds? 40 if (x+xd < 1 .or. x+xd > len(temp_lines(y)) .or. y+yd < 1 .or. y+yd > size(temp_lines)) then 41 exit 42 end if 43 44 ! try to move 45 select case(temp_lines(y+yd)(x+xd:x+xd)) 46 case('.') 47 ! valid move 48 x = x + xd 49 y = y + yd 50 case('O') 51 ! we are blocked lets rotate 90 degrees and count obstacle 52 o_ct = o_ct + 1 53 if(xd == 0 .and. yd == -1) then 54 xd = 1 55 yd = 0 56 else if (xd == 1 .and. yd == 0) then 57 xd = 0 58 yd = 1 59 else if (xd == 0 .and. yd == 1) then 60 xd = -1 61 yd = 0 62 else if (xd == -1 .and. yd == 0) then 63 xd = 0 64 yd = -1 65 end if 66 case('#') 67 ! we are blocked lets rotate 90 degrees 68 ! change this to an O to try and detect when stuck 69 temp_lines(y+yd)(x+xd:x+xd) = 'O' 70 if(xd == 0 .and. yd == -1) then 71 xd = 1 72 yd = 0 73 else if (xd == 1 .and. yd == 0) then 74 xd = 0 75 yd = 1 76 else if (xd == 0 .and. yd == 1) then 77 xd = -1 78 yd = 0 79 else if (xd == -1 .and. yd == 0) then 80 xd = 0 81 yd = -1 82 end if 83 case default 84 exit 85 end select 86 if(o_ct > 100) then 87 exit ! probably stuck 88 end if 89 end do 90 end if 91 if(o_ct > 100) then ! we got stuck probably 100 is so arbitrary 92 ct = ct + 1 93 end if 94 end do 95 end do 96 print*, "block points: ", ct 97end program day_06_part_2