0

I need to show the numbers 1-10 in a random order. An example outpue while executing first time would be: 5,4,8,7,9,1,2,3. An example while executing second time would be: 7,6,5,1,2,3,4,9,8

Will the following code print all date between ranges in random?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Bathri Nathan
  • 1,101
  • 2
  • 13
  • 17

2 Answers2

1

You can use the Collections.shuffle() method. (more info on this SO question)

In your example:

List<int> numbers = new ArrayList<int>();
int min = 65;
int max = 85;
for (int i = min; i <= max; i++) {
  numbers.add(i);
}
Collections.shuffle(numbers);
Community
  • 1
  • 1
FlyingPumba
  • 1,015
  • 2
  • 15
  • 37
0

Using shuffle works too. This is how you would manually do it.

Random r = new Random();

List<Integer> list = new ArrayList<Integer>();

for (int i=min ;  i<= max ; i++){

list.add(i); // adding your data

}

List<Integer> list2 = new ArrayList<Integer>().addAll(list); 
//you don't need to use 
//list2 if you are ok with losing list. 
//As here list2 is being emptied ..

while(list2.size() > 0){

 int randomIndex = r.nextInt(0, list2.size);
 System.out.println(list.get(randomIndex));

 list2.remove(randomIndex);
 }
  • i have found the solution myself dude .. by the same shuffel meathod... i tried in random but... dulication of numbers occurs there... soo this is simple and better... thxxxx u @Yosif Mansour... – Bathri Nathan Nov 07 '16 at 04:06