สมมุติว่าเรามีอาร์เรย์ มีองค์ประกอบที่แตกต่างกัน n เราต้องตรวจสอบความถี่ขององค์ประกอบหนึ่งในอาร์เรย์ สมมติว่า 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