Re: [問題]這個有辦法簡化媽? (亂數問題)

看板Perl作者 (檸檬汁)時間19年前 (2006/07/21 10:49), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/3 (看更多)
※ 引述《qrtt1 (愚者)》之銘言: : ※ 發信站: 批踢踢實業坊(ptt.cc) : ◆ From: 140.120.15.17 : 推 LiloHuang:print join $/,(sort{rand>.5?-1:1}1..10); 07/14 01:33 : → darenhu:perlfaq4: How do I shuffle an array randomly? 07/14 07:55 : → darenhu:use Util::List qw(shffle); @hitno = shuffle 0..9; 07/14 08:05 : → darenhu:更正: use List::Util qw(shuffle); 才對 07/14 08:08 : haha. 如果只是想亂排的話 : 那用sort就好了壓:) : @a = (4,5,6,7,8,2,2334,345,1,-23,4); : @b = sort { $a <=> $b } @a; : @c = sort { rand() <=> rand() } @a; : print "@b\n@c\n"; 這效果和LiloHuang大的演算法是相同的,但多用了一倍的rand()。 而且重點是,這樣得到的結果不是均勻分佈的。 以perl 5.8中的sort缺省使用的mergesort為例,我簡單計算一下就可以斷定: 8和2出現在$c[0]的機率是除最後那個4外其他數的2倍,是最後那個4的1/2。 我在知道好物List::Util之後就都用它的shuffle了, List::Util超好用的你都不知道 b( ̄︶ ̄)> 而之前我都是用這個演算法的: $a=int(rand($_+1)), @a[$_, $a] = @a[$a, $_] foreach (1..$#a); 其實這和List::Util的shuffle的演算法是一樣的,但不如它寫得巧妙。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 143.89.144.107 ※ 編輯: Andor 來自: 143.89.144.107 (07/21 12:50)

07/23 22:11, , 1F
亂數的學問真大啊orz
07/23 22:11, 1F
文章代碼(AID): #14m42nSH (Perl)
文章代碼(AID): #14m42nSH (Perl)