简体   繁体   中英

How do I generate random numbers for that array that don't repeat? (java)

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]);

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM