作者eieio (好多目标)
看板java
标题Re: [问题] 请问有更好方法吗? 乐透程式
时间Wed Apr 4 00:08:11 2012
※ 引述《jodo1984 (XDDD)》之铭言:
: 今天自己练习 乐透小程式
: 因为取乱数会有"相同的数目"和"0"
: 想要撇除这两项 所以自己写了一个程式
: public static void main(String[] args) {
: int l_index = 0;
: int[] LotteryArray = new int[6];
: while(l_index < 6){
: double d=100*Math.random();
: int l_intTemp=(int)d;
: l_intTemp %= 50;
: LotteryArray [l_index] = l_intTemp;
: for(int i = 0; i< l_index; i++){
: //这里是满足上述讲的那两种状况 先把阵列减一
: if(LotteryArray [i] == l_intTemp | l_intTemp == 0){
: l_index--;
: break;
: }
: }
: l_index++;
: }
: }
: 这是我刚刚想的 请问有更好方法吗? 谢谢
我会使用 List<Integer> 而不使用 array。先在 List 里面放进 1-49 的数
字,然後使用 shuffle 这个现成的 API
http://tinyurl.com/7uwl6wa。最後取
出 List 最前面的六个 elements 即可。这个作法应该最接近 uniform
distribution。可读性我猜也会高一点。要自己写 shuffle 的话,可以参考
http://tinyurl.com/o5uk3t。最後的 shuffle algorithm 很有用,在美国面
试 google facebook 之类很常有人被考 shuffle XD
其实你写的方法也很 ok 了。
--
Just because you deserve this
doesn't mean they're gonna give it to you.
Sometimes you gotta take what's yours.
── Kenny Ray Carter
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 207.171.191.60
※ 编辑: eieio 来自: 207.171.191.60 (04/04 00:14)
※ 编辑: eieio 来自: 207.171.191.60 (04/04 00:15)