Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

arrays - Java - generate Random range of specific numbers without duplication of those numbers - how to?

Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution.

For a range of numbers, say 1-12, I want to generate a random sequence within that range, and include 1 and 12.

I don't want duplicate numbers though.

So I would want something like this - 3,1,8,6,5,4 ..and so on, every number from 1-12.

Then I want to put these random numbers into an Array and use that array to 'randomly' select and display some items (like inventory pulled from database) on a jsp page.

The problem with what I've tried thus far, is that there are a lot of duplicate numbers being generated...or, not ALL of the numbers are chosen.

Is there a simple solution to this problem?


Edit

Test#1 using Collections and shuffle() method -

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

String[] randomNumbers = (String[])list.toArray();

for(int i = 0; i < 10; i++)
{
  out.print(randomNumbers[i]+"<br>");
}

The result was a sequence with duplicate values -
chose = 3
chose = 8
chose = 7
chose = 5
chose = 1
chose = 4
chose = 6
chose = 4
chose = 7
chose = 12

Test #2 - using Random math class

int max = 12;
int min = 1;

int randomNumber = 0;

String str_randomNumber = "";

for(int i=0; i<10; i++) {
    //int choice = 1 + Math.abs(rand.nextInt(11));
    int choice = min + (int)(Math.random() * ((max - min) + 1));

    out.print("chose = "+choice+"<br>");
}

The result was just like using Collections.shuffle().

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Why does Collections.shuffle() fail for my array?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...