Obtain different random numbers in JAVA

Source: Internet
Author: User
Tags rand

I just started learning JAVA and recently made a small game of guessing numbers on my own. It seems that obtaining four different random numbers is the key of this program. I previously searched for some methods to obtain random numbers on the Internet, but I am not familiar with JAVA, so I am not very familiar with them. As a result, I had the knowledge and thought of an algorithm for obtaining different random numbers.

I will select four random numbers from 0-9 as an example.

Int [] anArray = new int [10];
For (int I = 0; I <10; I ++)
  {
AnArray [I] = I;
  }

Int [] rand = new int [4];
For (int I = 0; I <4 ;)
  {

Int j = (int) (Math. random () * 10 );
If (j <(10-I ))
   {
Rand [I] = anArray [j];
AnArray [j] = anArray [9-i];
AnArray [9-i] = rand [I];
I ++;
   }

Self-perception: this algorithm can be used to obtain different random numbers within a certain range. It is still relatively fast in terms of efficiency.
  



</

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.