Ana amfani da algorithm ɗin binciken abubuwa da yawa don nemo duk abubuwan da suka faru na takamaiman kashi a cikin jeri. Ba kamar algorithms binciken abu guda ɗaya ba, wannan hanyar tana lura da abubuwan da suka faru da yawa na abin da ake nufi kuma suna dawo da jerin matsayinsu.
Yadda Ake Aiki
- Fara daga farkon jerin.
- Yi maimaita ta kowane kashi a cikin lissafin.
- Kwatanta kashi na yanzu tare da ƙimar manufa.
- Idan kashi na yanzu yayi daidai da ƙimar manufa, yi rikodin matsayinsa.
- Ci gaba zuwa kashi na gaba kuma maimaita matakai 3-4.
- Bayan maimaita ta cikin jerin duka, mayar da jerin wuraren da aka yi rikodi.
Misali
Bari mu yi la'akari da jerin lambobin kuma muna son nemo duk abubuwan da suka faru na lamba 23.
Jerin: {12, 23, 45, 23, 56, 23, 89, 90}
- Fara daga farkon: 12. Ba lambar da ake so ba.
- Matsar zuwa kashi na gaba: 23. An samo daidai, matsayi na rikodin kamar 1.
- Matsar zuwa kashi na gaba: 45. Ba lambar da ake so ba.
- Matsar zuwa kashi na gaba: 23. An samo daidai, matsayi na rikodin kamar 3.
- Matsar zuwa kashi na gaba: 56. Ba lambar da ake so ba.
- Matsar zuwa kashi na gaba: 23. An samo daidai, matsayi na rikodin kamar 5.
- Matsar zuwa kashi na gaba: 89. Ba lambar da ake so ba.
- Matsar zuwa kashi na gaba: 90. Ba lambar da ake so ba.
- Bayan maimaitawa, mayar da jerin matsayi: [1, 3, 5].
Misali Code a C++
#include <iostream>
#include <vector>
std::vector<int> multipleItemSearch(const std::vector<int>& arr, int target) {
std::vector<int> positions;
for(int i = 0; i < arr.size(); ++i) {
if(arr[i] == target) {
positions.push_back(i);
}
}
return positions;
}
int main() {
std::vector<int> numbers = {12, 23, 45, 23, 56, 23, 89, 90};
int target = 23;
std::vector<int> result = multipleItemSearch(numbers, target);
std::cout << "Occurrences of " << target << " found at positions: ";
for(int pos: result) {
std::cout << pos << ";
}
std::cout << std::endl;
return 0;
}
A cikin misalin da aka bayar, multipleItemSearch
ana amfani da aikin don nemo duk abubuwan da suka faru na lamba 23 a cikin jerin lambobin. Sakamakon zai zama vector mai ɗauke da matsayi na duk abubuwan da suka faru(matsayi sun fara daga 0).