Oct 23, 2014

Make a Random number by Java(Android)


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

  1. int lotto_first=(int)((Math.random()*44)+1);

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'.

  1. ArrayList<Integer> lotto = new ArrayList<Integer>(45);
  2. lotto.add(1);lotto.add(2);lotto.add(3);lotto.add(4);lotto.add(5);
  3. lotto.add(6);lotto.add(7);lotto.add(8);lotto.add(9);lotto.add(10);
  4. .....
  5. lotto.add(36);lotto.add(37);lotto.add(38);lotto.add(39);lotto.add(40);
  6. lotto.add(41);lotto.add(42);lotto.add(43);lotto.add(44);lotto.add(45);
  7. Collections.shuffle(lotto);
  8. lotto_first=lotto.get(0);
  9. lotto_second=lotto.get(1);
  10. lotto_third=lotto.get(2);
  11. lotto_fourth=lotto.get(3);
  12. lotto_fifth=lotto.get(4);
  13. lotto_sixth=lotto.get(5);
  14. 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