作者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)