简体   繁体   English

对大小为 N 的数组进行随机搜索

[英]Random search on an array of size N

I need help fixing my code below.我需要帮助修复下面的代码。 I want to do a random search on an array of size N .我想对大小为N的数组进行随机搜索。 Random search randomly picks up an integer from arr to compare.随机搜索从arr中随机选取一个 integer 进行比较。 And the process repeats until the integer it is looking for is found (again it is remarked that the membership is guaranteed, otherwise random search obviously can enter an infinite loop).并重复该过程,直到找到它正在寻找的integer(再次说明成员资格是有保证的,否则随机搜索显然会进入无限循环)。 How do I search for the searchValue using random search?如何使用随机搜索搜索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
      }
    }

I don't exactly get what you intend to do, but based on my idea, you want to search for an element randomly, until it is found.我不完全明白你打算做什么,但根据我的想法,你想随机搜索一个元素,直到找到它。 If I am right, then first of all searchValue should be equal arr[i] , in this way, your array can take any value, and instead of using a nested-for loop, use nested-do-while loop, like-this.如果我是对的,那么首先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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM