随机搜索大小为 N 的数组
Random search on an array of size N
我需要帮助修复下面的代码。
我想对大小为 N
的数组进行随机搜索。
随机搜索从arr
中随机取一个整数进行比较。并且重复这个过程,直到找到它要找的整数(再次说明必须保证隶属度,否则随机搜索显然会进入死循环)。如何使用随机搜索来搜索 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]
,这样,你的数组可以取任何值,而不是使用 nested-for 循环,使用 nested-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
}
}
我需要帮助修复下面的代码。
我想对大小为 N
的数组进行随机搜索。
随机搜索从arr
中随机取一个整数进行比较。并且重复这个过程,直到找到它要找的整数(再次说明必须保证隶属度,否则随机搜索显然会进入死循环)。如何使用随机搜索来搜索 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]
,这样,你的数组可以取任何值,而不是使用 nested-for 循环,使用 nested-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
}
}