Reputation:
So I'm trying to make a sports game schedule generator. This randomly selects from an array that consists of field names. How do I make it so that It won't select the same field twice?
Random rand = new Random();
int index, loc;
index = rand.nextInt();
loc = rand.nextInt(y);
System.out.print(fields[loc]);
Upvotes: 0
Views: 129
Reputation: 294
You should store the indexes of sports in another integer from where we can check that this sport has not been chosen earlier. first store the indexes of sports in a string.
public void sportPicker(){
int[] sche=new int[4];
String[] sports={"1-Cricket","2-Hockey","3-Tennis","4-Badminton"}
int temp;
Random rand=new Random();
for(int a=1;a<=sports.length();a++){
temp=rand.nextInt(4);
if(temp!=sche[0]||temp!=sche[1]||temp!=sche[2]||temp!=sche[3]){
sche[a]=temp;
}
else a--;
}
}
This would make sure that index is not there in the array sche, if it exists it would make the fuction again generate a number and check.
Upvotes: 0
Reputation: 1105
Create a seperate array of the same size as your fields
array of boolean type, then when a location is selected:
loc = rand.nextInt(y);
alreadySelected[loc] = true;
if(!alreadySelected[loc]) {
System.out.print(fields[loc]);
}
This will make it so that if you've already been at that location, it won't print it out again.
Upvotes: 1
Reputation: 1265
public static void main(String[] args) {
ArrayList<> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
System.out.println(list.get(0));
}
Add each number in the range sequentially in a list structure using add() method of List Interface.Then use shuffle of Collections class to shuffle the list
Collections.shuffle()
generate random number from a given list using default source of randomness.
Upvotes: 0