作者mantour (朱子)
看板Fortran
标题Re: [问题] 20个人中随机抽取10个人
时间Sat Apr 17 00:25:11 2010
之前好像在别的地方回过一个洗牌的问题
这边可能可以用类似的方法解决
希望效率会比较不惊人一点XD
Program sampling
implicit none
integer,
parameter:: M
=20,N
=10
integer::people(
1:M),i,p
real::ran
call random_seed()
do i
=1,M,
1
people(i)
=i
! 数字代表人的编号
end do
do i
=1,N,
1
call random_number(ran)
! 把抽过的人丢到阵列最後
p
=int(ran
*float(M
-i
+1))
+ 1 ! 只把抽到的那个跟倒数第
write(
*,
*) people(p)
! i个交换即可,不需要整排
call swap(people(p),people(M
-i
+1))
! 住前递补
end do
end program
subroutine swap(a,b)
implicit none
integer,
intent(
inout)::a,b
integer::temp
temp
=a
a
=b
b
=temp
end subroutine
※ 引述《janewinnie (逃离)》之铭言:
: 忘了回来板上看@@
: 我已经写出一个方法了
: 先给每个人一个乱数
: 如果100人要取20人,就取乱数最大的20人
: main program
: implicit none
: integer,parameter::k=20,n=100 !k是要选出的人数,n为总人数
: integer::who(n) !who作为有无选上的标记
: call choose(k,n,who)
: write(*,*) who !1表是选上,0表示未选上
: stop
: end program
: subroutine choose(k,n,who)
: implicit none
: integer::thft,i,n,person,loca(1)
: real::rand(n)
: integer::who(n)
: call random_number(rand) !叫出"n"个乱数(每个人配一个乱数)
: do i=1,k,1
: loca=maxloc(rand) !找拥有最大乱数的那个人
: person=loca(1)
: who(person)=0 !这个人的who=1
: rand(person)=0 !将这个人的乱数设为0,下次就不会再选到
: enddo
: return
: end
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.213.158
※ 编辑: mantour 来自: 140.112.213.158 (04/17 00:25)
※ 编辑: mantour 来自: 140.112.213.158 (04/17 00:25)
※ 编辑: mantour 来自: 140.112.213.158 (04/17 00:31)