สมมติว่าเรามีอาร์เรย์ มี n สมาชิกที่แตกต่างกัน เราต้องตรวจสอบความถี่ (Frequency) ของสมาชิกหนึ่งในอาร์เรย์ สมมติ A = [5, 12, 26, 5, 3, 4, 15, 5, 8, 4] ถ้าเราพยายามหาความถี่ของ 5 จะได้ 3
เพื่อแก้ปัญหานี้ เราจะสแกนอาร์เรย์จากซ้าย ถ้าสมาชิกเท่ากับตัวเลขที่กำหนด ให้เพิ่มตัวนับ ไม่เช่นนั้น ไปสมาชิกถัดไป จนกว่าอาร์เรย์จะหมด
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int countElementInArr(int arr[], int n, int e) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == e)
count++;
}
return count;
}
int main() {
int arr[] = {5, 12, 26, 5, 3, 4, 15, 5, 8, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int e = 5;
cout << "Frequency of " << e << " in the array is: " << countElementInArr(arr, n, e);
}
ผลลัพธ์
Frequency of 5 in the array is: 3