-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrequency_table.c
More file actions
88 lines (61 loc) · 1.79 KB
/
frequency_table.c
File metadata and controls
88 lines (61 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "frequency_table.h"
#include "util.h"
FreqTable FreqTableCreate(int size){
assert(size > 0);
FreqTable fqtable = (FreqTable) malloc(sizeof(struct _FreqTable));
assert(fqtable != NULL);
fqtable->size = size;
fqtable->char_count = 0;
fqtable->table = (int*) malloc(size * sizeof(int));
assert(fqtable->table != NULL);
for (int i = 0; i < size; i++){
fqtable->table[i] = 0;
}
return fqtable;
}
FreqTable FreqTableDestroy(FreqTable fqtable){
assert(IsFreqTableValid(fqtable));
free(fqtable->table);
fqtable->table = NULL;
free(fqtable);
fqtable = NULL;
return fqtable;
}
void FreqTableInsert(FreqTable fqtable, int c){
assert(IsFreqTableValid(fqtable));
assert(c >= 0 && c < fqtable->size);
assert(fqtable->table[c] >= 0);
if (fqtable->table[c] == 0){
fqtable->char_count += 1;
}
fqtable->table[c] += 1;
return;
}
int FreqTableGetCount(FreqTable fqtable, int c){
assert(IsFreqTableValid(fqtable));
assert(c >= 0 && c < fqtable->size);
assert(fqtable->table[c] >= 0);
return fqtable->table[c];
}
void FreqTableShow(FreqTable fqtable){
assert(IsFreqTableValid(fqtable));
printf("Frequency Table Print:\n");
for (int i = 0; i < fqtable->size; i++){
if (fqtable->table[i] > 0){
printf("idx = %d, char = %c, count = %d\n", i, i, fqtable->table[i]);
}
}
printf("\n");
return;
}
int FreqTableGetCharCount(FreqTable fqtable){
assert(IsFreqTableValid(fqtable));
return fqtable->char_count;
}
bool IsFreqTableValid(FreqTable fqtable){
return fqtable != NULL && fqtable->size > 0 && fqtable->char_count >= 0 && fqtable->table != NULL;
}