···
integer :: io, ios, i, j, block_n, ct, block_start, block_end, space_start, space_end
integer(kind=int64) :: res
41
-
integer, allocatable :: system(:), work(:)
41
+
integer, allocatable :: system(:), work(:), done(:)
logical :: is_space, space_block_start
open(newunit=io, file='./day_09_input.txt', status='old', action='read', access='stream')
···
100
-
do i = 0, size(work) -1
101
-
if(block_n == -1 .and. work(size(work) - i) > -1) then
100
+
do i = size(work), 1, -1
101
+
if(block_n == -1 .and. work(i) /= -1) then
! we are starting a block
103
-
block_end = size(work) - i
104
-
block_n = work(size(work) - i)
105
-
else if (block_n /= -1 .and. block_n /= work(size(work)-i)) then
105
+
if(allocated(done) .and. count(done == block_n) > 0) then
110
+
else if(.not. allocated(done)) then
114
+
call append_to_integer_array_times(done, block_n, 1)
116
+
else if (block_n /= -1 .and. block_n /= work(i)) then
! we are ending the block
107
-
block_start = size(work) - i
! lets try to move the block
space_block_start = .true.
111
-
if (j >= block_start) exit
123
+
if (j > block_start) exit
if(space_block_start .and. work(j) == -1) then
space_block_start = .false.
···
space_block_start = .true.
if(space_end - space_start >= block_end - block_start) then
119
-
work(space_start:(space_start + (block_end - (block_start +1) ))) = work((block_start +1):block_end)
131
+
work(space_start:space_start + (block_end - (block_start +1))) = block_n
work(block_start+1:block_end) = -1
129
-
block_n = work(size(work) - i)
130
-
block_end = size(work) - i
135
-
if(work(i) > -1) then
145
+
if(work(i) /= -1) then
res = res + ((i-1) * work(i))