Re: [問題] 請問有更好方法嗎? 樂透程式

看板java作者 (好多目標)時間13年前 (2012/04/04 00:08), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《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)
文章代碼(AID): #1FUo1khi (java)
文章代碼(AID): #1FUo1khi (java)