简体   繁体   中英

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. For example, 10, 23, 35, 77 are all ok, but not 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.

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 . 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) .

Here is a quite simple solution using 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. We can continue this until the HashSet has 10 elements.

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]);
             }
      }
}

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