Creating random numbers with no duplicates

后端 未结 18 1809
忘了有多久
忘了有多久 2020-11-21 12:00

In this case, the MAX is only 5, so I could check the duplicates one by one, but how could I do this in a simpler way? For example, what if the MAX has a value of 20? Thanks

18条回答
  •  故里飘歌
    2020-11-21 12:04

    Following code create a sequence random number between [1,m] that was not generated before.

    public class NewClass {
    
        public List keys = new ArrayList();
    
        public int rand(int m) {
            int n = (int) (Math.random() * m + 1);
            if (!keys.contains(n)) {
                keys.add(n);
                return n;
            } else {
                return rand(m);
            }
        }
    
        public static void main(String[] args) {
            int m = 4;
            NewClass ne = new NewClass();
            for (int i = 0; i < 4; i++) {
                System.out.println(ne.rand(m));
            }
            System.out.println("list: " + ne.keys);
        }
    }
    

提交回复
热议问题