Two-color ball lottery random algorithm-Java implementation, two-color ball algorithm-java
The first time I wrote a technical blog, I wrote a random two-color ball lottery algorithm.
The principle is as follows:
1. Initialize an array nums to be drawn, whose length is k.
2. Random number ranging from 1 to k, and obtain nums [k]. In this way, the first lucky draw number is obtained. Remove this number 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> (); // lottery pool 5 6 // Number of lottery pools generated 7 // For example, if you select 33, select 6, then 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 // how to delete an element 24 mNums. remove (_ index); 25} 26 return xString; 27} 28}
The call method is as follows:
MyLuck _ red = new myLuck (33, 6 );
MyLuck _ blue = new myLuck (16, 1 );
String Str = _ red. GetNums () + "," + _ blue. GetNums ();
It's easy to output the result ~