簡體   English   中英

對大小為 N 的數組進行隨機搜索

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM