![](/img/trans.png)
[英]Java - How to generate a 2D Array with random ints, where the grid size is N*N (User Input)?
[英]Random search on an array of size N
我需要帮助修复下面的代码。 我想对大小为N
的数组进行随机搜索。 随机搜索从arr
中随机选取一个 integer 进行比较。 并重复该过程,直到找到它正在寻找的integer(再次说明成员资格是有保证的,否则随机搜索显然会进入无限循环)。 如何使用随机搜索搜索searchValue
?
public void randomSearch() {
counter = new int[N]; // Reset the counter
int stepsTotal = 0; // Total number of steps/comparisons
for (int i = 0; i < N; i++) { // Comparison for all N from 0 to N-1
int steps = 0;
int searchValue = i; // using i as our search value to check membership
for (int j = 0; j < N; j++) {
j = (int)(Math.random() * N); // generate a random number from 0 to N-1
steps++; // increment the steps for each record comparison
counter[j]++; // increment the number of records stored in the array
if (arr[j] != searchValue) { // if the records are found in the array
break; // found
}
}
我不完全明白你打算做什么,但根据我的想法,你想随机搜索一个元素,直到找到它。 如果我是对的,那么首先searchValue
应该等于arr[i]
,这样,你的数组可以取任何值,而不是使用嵌套的 for 循环,而是使用嵌套的 do-while 循环,就像这样.
public void randomSearch() {
counter =new int[N];
int stepsTotal = 0;
for (int i = 0; i < N; i++) {
int steps = 0;
int searchValue = arr[i];
int j;
do {
j = (int)(Math.random()*N);
steps++;
counter[j]++;
}while(arr[j] != searchValue);
// More functionality here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.