简体   繁体   中英

Generate 3 random numbers from 1 to 25? (Java)

So, I'm trying to generate an array of length 3 with random unique numbers from 1 to 25. I can't understand why my code isn't working and I'd greatly appreciate some help!

public void generateRandom() {
    for(int j=0; j<3; j++) {
        dots[j] = (int) (Math.random()*(col*row)+1);
        System.out.println(dots[j]);
        for(int i=j; i>0; i--) {
            if(dots[j]==dots[j-1]) {
                generateRandom();
            }
        }
    }
}

dots[] is the array which I am trying to store the 3 unique random numbers. By the way, col*row == 25 .

Here is a bit different approach. It relies on creating an ArrayList with the specified set of values and then shuffling that list. Once the list is shuffled you can create an array based off of the first three elements in the shuffled list.

public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    for(int i = 0; i < 26; i++){
        list.add(i);
    }

    Collections.shuffle(list);
    Integer[] randomArray = list.subList(0, 3).toArray(new Integer[3]);

    for(Integer num:randomArray){
        System.out.println(num);
    }
}
for(int j=0;j<3;j++)
    dots[j]=(int)(Math.random()*Integer.MAX_VALUE)%25+1;

Since your Math.random is anyway a random number, multiplying by Integer.MAX_VALUE will not affect randomness. Also if you want an explanation of why does your code not work, that is because if the number is relatively small, say under 0.001 , you will get 0 by getting the int when you multiply.

每次generateRandom调用自身时,它都会从头开始使用第一个随机数重新开始,而不是为当前位置选择一个新的随机数。

This is approach

public void generateRandom() {
    for(int j=0; j<3; j++) {
      boolean f;
      do { 
        dots[j] = (int) (Math.random()*(col*row)+1);
        f = false;
        for(int i=j-1; i>=0; i--) {
            if(dots[i]==dots[j]) {
              f = true;
              break;
            }
        }
        if (!f)
          System.out.println(dots[j]);
      } while (f);
   }
}

It's repeating the generation of the number until no duplicates found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM