2013-02-07 154 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