1

私は問題に苦しんでいるので、誰かがアドバイスや例を提供できれば、本当に感謝しています. Fortran90 を使用しています。

プログラムの目的:

選択した量で、ファイルからランダムな行を削除するには。私が考える最善の方法は、乱数を使用して行番号に対応させることでした。

現時点での機能:

毎回新しい乱数を生成し、別のファイルに出力します。

問題:

(1) 行番号に対応する整数を生成しません。(2) これらの番号を使用してファイルから行を削除する方法がわかりません。

program random1
implicit none
integer :: i, seed, removed
real :: r
open (unit=10,file='random.dat')
removed=5

call init_random_seed() 
do i=1,removed
call random_number(r)
write(10,*) r
end Do

end program random1

subroutine init_random_seed()
        integer :: i,n,clock
        integer, dimension(:),allocatable :: seed

        call random_seed(size=n)
        allocate(seed(n))

        call system_clock(count=clock)

        seed=clock+37*(/(i-1,i=1,n)/)
        call random_seed(put=seed)

        deallocate(seed)
end subroutine

ありがとうございました!

4

1 に答える 1

2

ここに答えの断片があります。最初にいくつかの宣言

integer :: num_lines ! number of lines in file
integer :: ix        ! loop index variable
real :: fraction     ! what fraction of lines are to be deleted
logical, dimension(:), allocatable :: lines_index
real, dimension(:), allocatable :: rands

現在、いくつかの実行可能ファイル

read(*,*) num_lines  ! or figure it out some other way
read(*,*) fraction   ! likewise 

allocate(rands(num_lines)) ! no error checking
call random_number(rands)
allocate(lines_index(num_lines), source=rands<fraction)      ! no error checking

そして今どこlines_index(ix)がfalseであるかあなたixはあなたのファイルの行を削除することができます。実際にファイルから行を削除することに関しては、ファイルを1行ずつ読み取り、削除されない行だけを別のファイルに書き出すことをお勧めします。このようなものが機能する可能性があります

do ix = 1, num_lines
    read(infile,*) aline
    if(lines_index(ix)) write(outfile,*) aline
end do

私が採用したアプローチは、20%(または設定fractionしたもの)の行が削除されることを保証するものではなく、削除される可能性が最も高い行数であることに注意してください。n行が削除されることを保証したい場合は、次のようにします。

integer :: num_lines ! number of lines in file
integer :: ix, jx    ! loop index variables
integer :: n         ! number of lines to delete
integer, dimension(:), allocatable :: lines_index    ! line numbers for deletion
real :: rand

read(*,*) n

allocate(del_ix(n))         

do ix = 1,n
    call random_number(rand)
    lines_index(ix) = 1.0+num_lines*rand   ! lines_index(ix) will be between 1 and num_lines
end do

このアプローチは、同じ行が複数回削除対象として選択されないことを保証するものではありません。その状況に対処するために、いくつかのコードを作成する必要があります。次に続行します:

do ix = 1, num_lines
    read(infile,*) aline
    if(any(lines_index==ix)) then
        ! do not write the line
    else
        write(outfile,*) aline
    end if
end do
于 2013-02-07T11:18:58.083 に答える