#include<stdio.h>
#include<stdlib.h>
void count_ints(const char* file_name) {
FILE* file = fopen(file_name, "r");
int arr[1000000];
int n = sizeof(arr) / sizeof(arr[0]);
int c = 0;
while(!feof(file)) {
fscanf(file, "%d", &arr[c]);
c++;
}
// Hash table
int hash[1000] = {0};
int lv = 0, lvi = 0;
for (int j=0; j<n; j++) {
hash[arr[j]]++;
}
for (int i=0; i < 1000; i++) {
if (lv <= hash[i]) {
lv = hash[i];
lvi = i;
}
}
printf("%d occurs %d times\n", lvi, lv);
fclose(file);
}
int main() {
count_ints("/home/russellb/Development/c_devel/play/fcountr/1M.txt");
return 0;
Approach
1. Read the input file
2. Create hashtable
3. Find the maximum from the hash tableInitial approach was to use binary search. Later I learnt hash tables can be used for this problem and adopted it.
Result 142 occurs 1130 times
**Execution time**
real 0m00.11s
user 0m00.10s
sys 0m00.00s
Machine details:
CPU: Intel i5-3230M (4 cores)
OS: GNU/Linux
RAM: 8GM DDR3
}
Approach
Read in the file
Create hashmap of counts
Find the most occuringg value
CPU: i5-3235M
RAM: 8GB DDR3
OS: GNU/Linux
Execution times
\> time ./countr_ic
142 occurs 1130 times
real 0m00.10s
user 0m00.10s
sys 0m00.00s
Max finding is not optimized and working on it.