简体   繁体   English

如何生成每个数字都位于数字范围内的随机数?

[英]How can I generate random numbers where each digit lies within a number range?

I am trying to figure out how to generate and store 10 random numbers in array where the numbers are two digit and each digit is in the range of 0-7. 我试图弄清楚如何在数组中生成和存储10个随机数,其中数字是两位数,每个数字都在0-7范围内。 For example, 10, 23, 35, 77 are all ok, but not 1,78,89,99. 例如,10、23、35、77都可以,但是1,78,89,99都可以。 And also, I want to make sure that all the numbers are unique. 而且,我想确保所有数字都是唯一的。 Here is what I have come up to so far... 到目前为止,这是我要提出的...

import java.util.Random;
public class RandomNum{
      public static void main(String[] args){
            Random rand=new Random();
            int[] randomFirstDigit=new int[10];
             int[] randomSecondDigit=new int[10];

             for(int i=0;i<10;i++){
                 randomFirstDigit[i]=rand.nextInt(7-1+1)+1;
             }
             for(int i=0;i<10;i++){
                 randomSecondDigit[i]=rand.nextInt(7-1+1)+0;
             }
             int[] randomArr=new int[10];
             for(int i=0;i<10;i++){
             randomArr[i]=(randomFirstDigit[i]*10)+randomSecondDigit[i];
             }
             for(int i=0;i<=randomArr.length;i++){
                 System.out.println(randomArr[i]);
             }
      }
}

The main issue with the above code is, sometimes, the array value is not unique. 上述代码的主要问题是,有时数组值不是唯一的。 In other words, two identical numbers are stored in the array like 23,23. 换句话说,两个相同的数字像23,23一样存储在数组中。

Could any one please help me figure out the problem. 谁能帮我解决这个问题。

Thanks in advance for your help. 在此先感谢您的帮助。

So the list of the possible numbers is [10, 11, 12, ..., 17, 20, ..., 76, 77] and it has a size of 7 * 8 . 因此,可能数字的列表为[10, 11, 12, ..., 17, 20, ..., 76, 77] ,大小为7 * 8 What we need is 10 distinct random numbers that represent indices on that list, and then we can map the them to the actual numbers using i -> (i / 8 + 1) * 10 + (i % 8) . 我们需要的是代表该列表上索引的10个不同的随机数,然后我们可以使用i -> (i / 8 + 1) * 10 + (i % 8)将它们映射到实际数字。

Here is a quite simple solution using ThreadLocalRandom.ints : 这是一个使用ThreadLocalRandom.ints的非常简单的解决方案:

int[] array = ThreadLocalRandom.current()
        .ints(0, 7 * 8)
        .distinct()
        .limit(10)
        .map(i -> (i / 8 + 1) * 10 + (i % 8))
        .toArray();

The simpler and less computationally expensive solution is to generate each digit one at a time, then append it to a String. 一种更简单,更省钱的解决方案是一次生成一个数字,然后将其附加到字符串中。 You can convert it to an integer afterwards. 之后可以将其转换为整数。

To generate exactly 10 unique numbers, we can add each number we generate to a HashSet , where every element must be unique. 要生成正好10个唯一的数字,我们可以将生成的每个数字添加到HashSet中 ,其中每个元素都必须是唯一的。 We can continue this until the HashSet has 10 elements. 我们可以继续进行直到HashSet具有10个元素。

import java.util.Random;
import java.util.Set;
import java.util.HashSet;

public class TwoDigitGenerator {

    public static void main(String[] args) {

        // Generate 10 unique random numbers with desired properties.
        Set<Integer> usedNumbers = new HashSet<>();
        while (usedNumbers.size() < 10)
            usedNumbers.add(randomNumber());

        // Convert the set of numbers to an Integer array.
        Integer[] numbers = usedNumbers.toArray(new Integer[usedNumbers.size()]);

        for (Integer number : numbers)
            System.out.println(number);
    }

    public static int randomNumber() {
        Random random = new Random();
        String number = "";
        number += 1 + random.nextInt(7); // Generate first digit between 1 and 7 inclusively
        number += random.nextInt(8); // Generate second digit between 0 and 7 inclusively
        return Integer.parseInt(number);
    }

}

please you should loop the array again and check whether its already existing or not. 请您再次循环该数组,并检查其是否已经存在。 this is not the best solution because some of codes are redundant but to give you some hint on how you proccess it. 这不是最佳解决方案,因为某些代码是多余的,但可以为您提供一些提示,说明如何进行处理。

import java.util.Random;
public class RandomNum{
      public static void main(String[] args){
            Random rand=new Random();
            int[] randomFirstDigit=new int[10];
             int[] randomSecondDigit=new int[10];

             for(int i=0;i<10;i++){
                int gen = rand.nextInt(7-1+1)+1;
                Boolean flag = false;
                 for(int j=0; j < 10; j++)
                  if(randomFirstDigit[j] == gen) 
                   flag = true
                if(!flag) randomFirstDigit[i] = gen;
             }

             for(int i=0;i<10;i++){
                int gen = rand.nextInt(7-1+1)+0;
                Boolean flag = false;
                 for(int j=0; j < 10; j++)
                  if(randomSecondDigit[j] == gen) 
                   flag = true;
                if(!flag) randomSecondDigit[i] = gen;
             }

             int[] randomArr=new int[10];
             for(int i=0;i<10;i++){
               randomArr[i]=(randomFirstDigit[i]*10)+randomSecondDigit[i];
             }
             for(int i=0;i<=randomArr.length;i++){
                 System.out.println(randomArr[i]);
             }
      }
}

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

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