Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

java - Generate random number without duplicate in certain range

I'm currently creating an app and it will generate random numbers. So each time it will generate three numbers num1, num2 and num3. These number should not be duplicate. For example if num1 = 1 than num2 and num3 cannot be equal to 1. I've tried this code where it will display three different number ranging from 0-2. And its working. However I would want to generate random number ranging from 1-3, 2-4, 3-5 and so on. So how can I achieve this by using the code below. Please help me since I'm new to this. Thank you.

for(int i=0; i<images.length; i++)
{
        num[i] = (int)(Math.random()*3);

        if (i == 0)
        {
        if(num[i]== 0)
            images[i].setImageResource(R.drawable.zero);
        else if(num[i]==1)
            images[i].setImageResource(R.drawable.one);
        else
            images[i].setImageResource(R.drawable.two);
        }

        else
        {
            while (num[i] ==  num[i-1] || num[i] == num[0] )
                num[i] = (int)(Math.random()*3);


        if(num[i]==0)
            images[i].setImageResource(R.drawable.zero);
        else if(num[i]==1)
            images[i].setImageResource(R.drawable.one);
        else
            images[i].setImageResource(R.drawable.two);

        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a list if all numbers in the range, then shuffle the list:

List<Integer> numbers = new ArrayList<>();
// eg for range 3-5
for (int i = 3; i <= 5; i++)
    numbers.add(i);
Collections.shuffle(numbers);

Now use them in their new (random) order.

Unless your range is very large (millions) this will work fine.


Java8 version:

List<Integer> numbers = IntStream.rangeClosed(3, 5).boxed().collect(Collectors.toList());
Collections.shuffle(numbers);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...