Math.random() method is useful for making random number.
Return value of Math.random() is double 0.0~1.0
If you want 'integer number',multiply 'integer number'.
For example, if you making lotto program.
In Korea, lotto has 45 numbers.
Math.random()*45
Why '+1' ??
Because lotto number's range is 1~45.
Okay, we can using this code. But we meet another problem.
Duplication!!
So, we need checking duplicate.
But I propose another method.
'arraylist' and 'collection.shuffle'.
- ArrayList<Integer> lotto = new ArrayList<Integer>(45);
- lotto.add(1);lotto.add(2);lotto.add(3);lotto.add(4);lotto.add(5);
- lotto.add(6);lotto.add(7);lotto.add(8);lotto.add(9);lotto.add(10);
- .....
- lotto.add(36);lotto.add(37);lotto.add(38);lotto.add(39);lotto.add(40);
- lotto.add(41);lotto.add(42);lotto.add(43);lotto.add(44);lotto.add(45);
- lotto_first=lotto.get(0);
- lotto_second=lotto.get(1);
- lotto_third=lotto.get(2);
- lotto_fourth=lotto.get(3);
- lotto_fifth=lotto.get(4);
- lotto_sixth=lotto.get(5);
- lotto_bonus=lotto.get(6);
We can make arraylist.
The arraylist's size is 45.
We add lotto number to the arraylist then shuffle using 'collections.shuffle'.
Then we getting lotto number from arraylist!!
No comments:
Post a Comment