Reputation: 187
How to chose only one picture which can't repeat?
I tried this:
I use random and i want to delete selected picture
String[] picture = { "blue", "white", "red", "yellow" };
int number_picture1;
// Random function to find a random picture
Random ran = new Random();
number_picture1 = ran.nextInt(picture.length);
System.out.println(picture[number_picture1]);
// There is still posibility to chose the same picture
int number_picture2;
number_picture2 = ran.nextInt(picture.length);
System.out.println(picture[number_picture2]);
Upvotes: 1
Views: 198
Reputation: 116266
Use a List
or Set
instead of an array, then remove the selected picture from it after each selection:
import java.util.List;
import java.util.Arrays;
List<String> pictures = Arrays.asList("blue","white","red","yellow");
int number_picture1;
number_picture1=ran.nextInt(pictures.size());
System.out.println (pictures.remove(number_picture1));
int number_picture2;
number_picture2=ran.nextInt(pictures.size());
...
Upvotes: 2
Reputation: 178451
Simplest way is to use a List
1 to store your elements, and use Collections.shuffle()
on it - and then take elements iteratively.
The shuffle produces a random permutation of the list, so chosing items iteratively gives you the same probability to chose any ordering, which seems to be exactly what you are after.
Code snap:
String[] picture = { "blue", "white", "red", "yellow" };
//get a list out of your array:
List<String> picturesList = Arrays.asList(picture);
//shuffle the list:
Collections.shuffle(picturesList);
//first picture is the first element in list:
String pictureOne = picturesList.get(0);
System.out.println(pictureOne);
//2nd picture is the 2nd element in list:
String pictureTwo = picturesList.get(1);
System.out.println(pictureTwo);
...
(1) Simplest way to get the list from an array is using Arrays.asList()
Upvotes: 6
Reputation: 71
Using a Collection is a much better option in retrieving and deleting. With Arrays, keep a track of the indices which has already been selected. Also, if the number of selections is greater than the the length of the array, just throw an exception accordingly.
Upvotes: 3
Reputation: 38163
Although you haven't given the declaration of ran
, I guess it's the standard JDK random number generator.
That one has no guarantee whatsoever that not the same number is selected twice. In a true random algorithm that would be a rather strange guarantee.
One way to solve this is to put the numbers corresponding to your choices in a linked list (here {0,1,2,3}). Then pick a random integer between 0 and the size of your list (3 here). Say you get '2', then remove the second element from the list making it thus {0,1,3}. Next time pick a number between 0 and 2. If you now get a '2' again, you again remove the second element which is now '3'. Etc.
Upvotes: 1