java - 如何避免在 Java 中由 math.random 数字创建的数组中创建重复项?
问题描述
我有一个方法可以创建一个长度由 Main 中的参数决定的数组。这些数字是由数学随机创建的。如何通过在每次将其放入数组之前检查创建的随机数来避免重复?
是否可以检查未完成的数组?
class Test{
public int[] numberArray;
public int length;
public Test(int lengthArray){
this.numberArray=new int[lengthArray];
this.length=lengthArray;
}
public boolean checkArray(int checknumber){
inArray=false;
//what code can I write here to find duplicate
return inArray;
}
public void fillArray(){
int highest = 1000;
int lowest = 100;
int randomNumber = 0;
int counter=0;
for(int i=0;i<length;i++){
randomNumber=lowest + (int)(Math.random() * ((highest - lowest) + 1));
numberArray[counter]=randomNumber;
counter++;
}
}
public class testing {
public static void main(String[] args) {
Test test1 = new Test(9);
test1.fillArray();
for(int value: test1.numberArray){
System.out.print(value+" ");
}
}
}
解决方案
您可以首先创建所需的所有数字并将其存储在 Set 数据结构中,直到大小等于您想要的数字数量。稍后,将 Set 中的所有数字转移到一个相同大小的数组中
推荐阅读
- sql - 在单个 SELECT 中获取某个组的第一项
- reactjs - 如何为 2 个受保护的路由构建 Context Api 多状态?
- ms-word - 多次连续按下 AHK 组合键可在 Word 或 PowerPoint 中进行特殊粘贴
- python - ModuleNotFoundError:使用 sys.path.append() 时没有名为 Project 的模块
- sql - 具有并行未嵌套的 Upsert 在 UPDATE 部分引发“列不存在”
- calculated-field - Amazon Quicksight 计算字段 - maxIf 或 maxOver?
- php - auth()->attempt($request->only('email','password')) - 不工作
- scheme - 高阶函数和 Set 如何在 Scheme 上工作?
- c - 声明与 PieVectTable 不兼容
- javascript - 如何在没有 jQuery 或 ID 的情况下在 HTML 字符串中查找某些元素