2013-02-07 148 views
1

我一直在努力解決問題,所以如果任何人可以提供任何建議或例子,它將非常感激。使用Fortran90。使用隨機數字刪除文件的隨機行。 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 

謝謝!

回答

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)是假的,你可以刪除你的文件的行ix。至於實際上從文件中刪除行,我建議您逐行讀取文件,並僅向另一個文件寫出那些不會被刪除的行。像這樣的東西可能會奏效

請注意,我採取的方法並不能保證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