Two-color ball lottery random algorithm-Java implementation, two-color ball algorithm-java

Source: Internet
Author: User

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 ~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.