How to generate 6 different random numbers in java

后端 未结 10 1303
猫巷女王i
猫巷女王i 2020-12-10 21:04

I want to generate 6 different random numbers by using Math.random and store them into an array. How can I make sure that they are different? I know I need to use for-loop t

10条回答
  •  攒了一身酷
    2020-12-10 21:33

    You can use a Set.

    Set s = new HashSet<>();
    while(s.size() != 6){
       s.add(1 + (int) (Math.random() * 49));
    }
    
    Integer[] arr = s.toArray(new Integer[s.size()]);
    

    This is enough to do this in your case because the number of distinct random numbers is relatively small compared to the size of the range you generate them.

    Otherwise I would go with @JBNizet approach.

提交回复
热议问题