How to have unique random number?

后端 未结 7 797
情深已故
情深已故 2020-12-16 08:38

This is how i am generating a unique no in between 1 to 6 and getting appropriate images from the drawable folder.

Random rand = new Random();
// n = the n         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 09:24

    Create a static list of possibilities you've already gotten.

    static ArrayList listIdontWantAnymore = new ArrayList();
    
    int NextRandomNumber() {
        Random random = new Random();
        int myRandomInt;
    
        do {
            myRandomInt = random.NextInt(6) + 1;
        } while(listIdontWantAnymore.Contains(myRandomInt));
    
        listIdontWantAnymore.Add(myRandomInt);
    
        // now your 'myRandomInt' is what you want it to be.
        return myRandomInt;
    }
    

提交回复
热议问题