繁体   English   中英

初学者Java:在7号数组中存储7个唯一的随机整数

[英]Beginner Java: Storing 7 unique random integers in a size 7 array

我的任务是使用随机数生成器函数获取0到9之间的7个唯一整数,将它们存储在数组中,并显示输出。

我在下面尝试了此代码,但无法给我7个唯一整数。 我仍然收到重复的值。

任何帮助表示赞赏,谢谢。

import java.util.Scanner;

public class JavaProgramCh8Ex2 {

  //Global Scanner object to read input from the user:
  static Scanner keyboard = new Scanner(System.in);

  //Global variable to hold the size of the array:
  final static int SIZE = 7;

  //Main
  public static void main(String[] args) {

    //Populate the array with 7 numbers:
    int [] sevenNumbers = new int [SIZE];
    populateSevenNumbersArray(sevenNumbers);

    //Display the numbers to the user:
    displaySevenNumbers(sevenNumbers);

}


    //Populate the numbers array with 7 random numbers:
    public static void populateSevenNumbersArray (int [] numArray){
      int maxElement;
      for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
        for (int i = 0; i <= (maxElement - 1); i++) {
          numArray[i] = getRandomNumber(0, 9);
          if(numArray[i] == numArray[i + 1]){
            numArray[i + 1] = getRandomNumber(0, 9);
          }
        }
      }
    }


    //Display the numbers to the user:
    public static void displaySevenNumbers (int [] numArray){
      for (int i = 0; i < numArray.length; i++) {
        System.out.print(numArray[i] + " ");
      }
    }


    //Get random numbers to populate the 7 numbers array:
    public static int getRandomNumber(int low, int high){
      return (int)(Math.random() * ((high + 1) - low)) + low;
    }

}

在这段代码中

 numArray[i] = getRandomNumber(0, 9);
 if(numArray[i] == numArray[i + 1]){      // yes you retry here
    numArray[i + 1] = getRandomNumber(0, 9);  // but what about here
 }

也许循环会更好

 int num = getRandomNumber(0, 9);
 while( isInArray(num){          // write a method to check
   num = getRandomNumber(0, 9);  
 }
 numArray[i] = num;

但是,当解决方案

List<Integer> solution = new ArrayList<>(); 
for (int i = 0; i < 10; i++) { solution.add(i); }     
Collections.shuffle(solution);

然后取7的子集

Integer[] numArray = Arrays.copyOfRange(solution.toArray(new Integer[0]), 0, 6);

并完成

    for (int x : numArray) {
        System.out.println(x);
    }

产量

9
3
4
6
7
1
8

会更好地工作

可能是一个过大的杀手,但我想尝试使用流解决此问题。

public final static Random RANDOM = new Random();

/**
 * Random unique integers from a given range [low, high)
 * @param size - number of integers to take, must be less than or equal to high - low
 * @param low - lower bound, inclusive
 * @param high - upper bound, exclusive
 * @return a list of unique, randomly chosen integers from the given range
 * @throws IllegalArgumentException if size is greater than high - low.
 */
public static List<Integer> uniqueSample(int size, int low, int high) {
    if (size > high - low) throw new IllegalArgumentException();
    return Stream.generate(choice(low, high))
            .distinct() // Discard duplicate 
            .limit(size) // Limit the size of the result.
            .collect(Collectors.toList());
}

/**
 * Return a random integer in range [low, high)
 * @param low - lower bound, inclusive
 * @param high - upper bound, exclusive
 * @return a random integer between low and high (exclusive)
 */
private static Supplier<Integer> choice(int low, int high) {
    return ()->low + RANDOM.nextInt(high - low);
}

public static void main(String [] args) {
    uniqueSample(7, 0, 10).forEach(System.out::println);
}

想法是一样的:您不断生成0到9之间的随机整数,直到得到从未见过的整数,然后将其添加到结果中。 当我们有7个这样的整数时停止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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