Home  >  Article  >  Java  >  Example of random algorithm for double color ball lottery implemented in Java

Example of random algorithm for double color ball lottery implemented in Java

PHP中文网
PHP中文网Original
2017-06-20 14:32:232017browse

This is my first time writing a technical blog, and I will write about a random algorithm for a double color ball lottery that I wrote before.

The principle is as follows:

1 First initialize an array nums to be drawn, the length of the array is k

2. Randomly select a random number between 1-k to get nums [k], in this way, the first lottery number is obtained, and the number is deleted from nums, k--.

3. Repeat step 2 until you get all the winning numbers

 1 class myLuck 
 2 {        
 3     private int mTarget;    
 4     List<Integer> mNums = new ArrayList<Integer>(); //摇奖池 5      6     ///从多少个数中产生多少个数 7     ///例如 33选6 则Source=33,Target=6; 8     myLuck(int vSource,int vTarget) {        
 9         for (int i = 1; i <=vSource ; i++) {            
10             mNums.add(i);11         }12         mTarget=vTarget;13     }14     15     public String GetNums()16     {        
17         String xString="";18         for (int i =0;i<mTarget; i++) 
19         {20             int _index=(int)(Math.random()* mNums.size());21             xString+=mNums.get(_index)+" ";22             //System.out.print("("+(_index+1)+")"+mNums.get(_index)+"-");    
23             //如何删除一个元素24             mNums.remove(_index);25         }    
26         return xString;27     }    
28 }

The calling method is as follows:

myLuck _red=new myLuck(33, 6);
myLuck _blue=new myLuck(16,1);
String Str =_red.GetNums() +","+_blue.GetNums();

It’s very simple, just output the result~

The above is the detailed content of Example of random algorithm for double color ball lottery implemented in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn