program traffic
implicit none

integer, parameter :: n = 64
real, parameter :: p = 0.5e0
integer, parameter :: numit = 20 

character, dimension(0:n+1) :: street, newstreet
real :: x, v
integer :: i, j, k, moved, cars_num

cars_num = 0
do i = 1, n
  call random_number(x)
  if ( x < p ) then
    street(i) = 'D'
    cars_num = cars_num + 1
  else
    street(i) = 'O'
  end if
end do

write(*,*)
do k = 1, numit
  street(0)   = street(n)
  street(n+1) = street(1)

  moved = 0
  write(*,'(64A1)')(street(i),i=1,n)
  do i = 1, n
    if (street(i) .EQ. 'O') then
      newstreet(i) = street(i-1)
    else
      newstreet(i) = street(i+1)
    end if

    if (street(i) .NE. newstreet(i)) then
      moved = moved + 1
    end if
    
  end do

  street(1:n) = newstreet(1:n)

  v = moved / (2.e0 * cars_num)
end do
write(*,'(64A1)')(street(i),i=1,n)
write(*,*)
write(*,'(A17,I3,A16,F7.2,A20,F7.2)')'Number of cars = ',cars_num,' Fill ratio = ', cars_num * 1.0e0 / n ,' Estimated speed = ',v

end program
