Algorithm na Bincike bazuwar (Random Search) a cikin C++- Bayani, Misali da Lambobi

Algorithm ɗin Bincike na Random hanya ce ta bincike bisa ga zaɓin saitin mafita daga sararin binciken da bincika ko za su iya magance matsalar. Ana amfani da wannan hanyar sau da yawa lokacin da babu takamaiman bayani ko dabara don jagorantar binciken.

Yadda Ake Aiki

  1. Ƙaddamarwa: Fara da saitin mafita na farko da aka ƙirƙira ba da gangan ba.
  2. Ƙimar: Yi la'akari da ingancin kowane bayani dangane da aikin haƙiƙa ko ma'aunin ƙima.
  3. Zaɓi: Zaɓi ɓangaren mafi kyawun mafita daga saitin dangane da yuwuwar ko zaɓi na bazuwar.
  4. Gwaji: Gwada idan zaɓaɓɓun mafita suna da ikon magance matsalar.
  5. Maimaita: Maimaita ta hanyar matakai 2 zuwa 4 har sai an sami sakamako mai gamsarwa ko kuma an kai takamaiman adadin maimaitawa.

Misali: Inganta Fibonacci Aiki

Yi la'akari da matsalar inganta aikin Fibonacci F(x) = F(x-1) + F(x-2) tare da F(0) = 0, F(1) = 1. Muna son nemo darajar x don wanda F(x) yana da girma. Hanyar Neman Bazuwar na iya zaɓar ƙimar x ba da gangan, ƙididdige Fibonacci ƙima a kowane x, kuma zaɓi ƙimar x daidai da mafi girman Fibonacci ƙimar da aka samu.

Misalin Code a C++

#include <iostream>  
#include <cstdlib>  
#include <ctime>  
  
int fibonacci(int n) {  
    if(n <= 0) return 0;  
    if(n == 1) return 1;  
    return fibonacci(n- 1) + fibonacci(n- 2);  
}  
  
int randomSearchFibonacci(int maxIterations) {  
    int bestX = 0;  
    int bestValue = 0;  
  
    srand(time(0));  
  
    for(int i = 0; i < maxIterations; ++i) {  
        int x = rand() % maxIterations;  
        int value = fibonacci(x);  
        if(value > bestValue) {  
            bestValue = value;  
            bestX = x;  
        }  
    }  
  
    return bestX;  
}  
  
int main() {  
    int maxIterations = 20;  
    int result = randomSearchFibonacci(maxIterations);  
  
    std::cout << "Optimal x for maximum Fibonacci value: " << result << std::endl;  
  
    return 0;  
}  

A cikin wannan misalin, muna amfani da hanyar Neman Random don inganta Fibonacci aikin. Muna zaɓar ƙimar x ba da gangan ba, mu lissafta Fibonacci ƙimar a kowace x, sannan mu zaɓi ƙimar x daidai da mafi girman Fibonacci ƙimar da muka lissafta.