在一维数组A中搜索非零条目并在fortran中创建一些数组B_k?

时间:2015-10-15 22:00:48

标签: arrays search fortran

给出一维数组

    A=(1,2,3,0,0,0,4,5,0,6,0)

我想通过搜索A的非零元素来打印具有相同大小的一维数组列表。从A的每个非零元素,我想要后续连续的非零元素的部分列表(在末尾用零填充)。在这种情况下,B中的元素数量将为3(因为A中恰好有3个非零子列表),预期结果为:

    B1=(1,2,3,0,0,0,0,0,0,0,0)
    B2=(4,5,0,0,0,0,0,0,0,0,0)
    B3=(6,0,0,0,0,0,0,0,0,0,0)

有人可以就如何解决这个问题给我一个建议吗?然后我就可以开始在Fortran编码了。

1 个答案:

答案 0 :(得分:3)

Fortran要求所有变量在编译时都是已知的,这意味着您无法创建未知数量的数组。

然而,处理此类问题的标准方法是使用二维数组B代替。

implicit none
integer :: nsize,i,nsubarray,j,k
integer, dimension(:), allocatable :: A
integer, dimension(:,:), allocatable :: B
logical :: insubarray

    read(*,*) nsize !enter length of array A at the command line
    allocate(A(nsize))
    read(*,*) A !enter the array at the command line

    !first count the number of subarrays nsubarray we need
    nsubarray = 0
    insubarray = .False.
    do i = 1,nsize
        if (A(i).ne.0) then
            if (.not.insubarray) nsubarray = nsubarray + 1
            insubarray = .True.
        else
            insubarray = .False.
        end if
    end do

    !then allocate the appropriate 2D-array
    allocate(B(nsize,nsubarray))
    B = 0 !fill with zeros
    insubarray = .False.
    k = 1 !counts the "number" of subarray B_k
    j = 1 !counts the position inside B_k

    !now write the numbers into the correct subarrays
    do i = 1,nsize
        if (A(i).ne.0) then
            insubarray = .True.
            B(j,k) = A(i)
            j = j + 1
        else
            insubarray = .False.
        end if
        if (.not.insubarray) j = 1
        if (i.gt.1) then
            if ((A(i-1).ne.0).and.(A(i).eq.0)) then
                k = k + 1
            end if
        end if
    end do

    !finally write output in the required format:
    !this is obviously far more complex than it has to be, the expected arrays
    !are simply in B(:,1), B(:,2), B(:,3), ...
    do i = 1,nsubarray
        write(*,'(a1,i1,a2)', advance="no") 'B',i,'=('
        do j = 1,nsize
            if (j.lt.nsize) then
                write(*,'(i1,a1)', advance="no") B(j,i),','
            else
                write(*,'(i1)', advance="no") B(j,i)
            end if
        end do
        write(*,'(a1)') ')'
    end do
end

另一个解决方案当然是声明足够大量的(一维)数组B_k,而不是使用那些不需要的数组,但这样做会很草率并且需要大量的条件语句。