-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffman.c
496 lines (349 loc) · 8.97 KB
/
huffman.c
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//#define BINARY_MODE
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef struct Node
{
unsigned char data; // 문자
int freq; // 빈도
struct Node *left; // 왼쪽 서브트리 포인터
struct Node *right; // 오른쪽 서브트리 포인터
} tNode;
////////////////////////////////////////////////////////////////////////////////
typedef struct
{
int last; // 힙에 저장된 마지막 element의 index
int capacity; // heapArr의 크기
tNode **heapArr;
} HEAP;
// 힙 생성
// 배열을 위한 메모리 할당 (capacity)
// last = -1
HEAP *heapCreate( int capacity);
// 최소힙 유지
static void _reheapUp( HEAP *heap, int index);
// 힙에 원소 삽입
// _reheapUp 함수 호출
int heapInsert( HEAP *heap, tNode *data);
// 최소힙 유지
static void _reheapDown( HEAP *heap, int index);
// 최소값 제거
// _reheapDown 함수 호출
tNode *heapDelete( HEAP *heap);
// 힙 메모리 해제
void heapDestroy( HEAP *heap);
////////////////////////////////////////////////////////////////////////////////
int read_chars(FILE* fp, int* ch_freq)
{
int count = 0;
while (1)
{
int c = fgetc(fp);
if (c == EOF)
{
break;
}
ch_freq[c] += 1;
count++;
}
return count;
}
void free_huffman_code(char* codes[])
{
for (int i = 0; i < 256; i++)
free(codes[i]);
}
tNode* newNode(char data, int freq)
{
tNode* brandnew = malloc(sizeof(tNode));
brandnew->data = data;
brandnew->freq = freq;
brandnew->left = NULL;
brandnew->right = NULL;
return brandnew;
}
tNode* make_huffman_tree(int* ch_freq)
{
// 1. capacity 256짜리 빈 힙 생성
HEAP* hp = heapCreate(256);
// 2. 개별 알파벳에 대한 노드 생성
// 3. 힙에 삽입
for (int i = 0; i < 256; i++)
{
heapInsert(hp, newNode(i, ch_freq[i]));
}
while (hp->last > 0) // 7. 힙에 한 개의 노드가 남을 때까지 반복
{
// 4. 2개의 최소값을 갖는 트리 추출
tNode* min1 = heapDelete(hp);
tNode* min2 = heapDelete(hp);
// 5. 두 트리 결합 후 새 노드에 추가
tNode* brandnew = newNode(0, min1->freq + min2->freq);
brandnew->left = min1;
brandnew->right = min2;
// 6. 새 트리를 힙에 삽입
heapInsert(hp, brandnew);
}
tNode* out = hp->heapArr[0];
return out;
}
void traverse_tree(tNode* root, char* code, int depth, char* codes[]) // 여기 들어온 root는 완성된 허프만 트리!!
{
if (root->left ==NULL && root->right ==NULL)
{
codes[root->data] = code;
}
else
{
char* updateleft = strdup(code);
updateleft[depth] = '0'; // 왼쪽 노드로 가는 code
char *updateright = strdup(code);
updateright[depth] = '1';
traverse_tree(root->left, updateleft, depth + 1, codes);
traverse_tree(root->right, updateright, depth + 1, codes);
//free(updateleft);
//free(updateright);
}
}
void make_huffman_code(tNode* root, char* codes[])
{
char *code = "";
traverse_tree(root, code, 0, codes);
}
void destroyTree(tNode* root)
{
if (root->left != NULL)
{
free(root->left);
free(root->right);
destroyTree(root->left);
destroyTree(root->right);
}
}
int encoding(char* codes[], FILE* infp, FILE* outfp)
{
int count = 0;
while (1)
{
int c = fgetc(infp);
if (c == EOF)
{
break;
}
fputs(codes[c], outfp);
count += (int)(sizeof(codes[c]));
}
return count / 8;
}
int encoding_binary( char *codes[], FILE *infp, FILE *outfp);
void decoding(tNode* root, FILE* infp, FILE* outfp)
{
tNode* base = root;
while (fgetc(infp)!=EOF)
{
if (root->left == NULL && root->right == NULL)
{
fputc(root->data, outfp);
root = base;
}
else
{
char c = fgetc(infp);
if (c == '0')
root = root->left;
else if (c == '1')
root = root->right;
}
}
}
void decoding_binary( tNode *root, FILE *infp, FILE *outfp);
////////////////////////////////////////////////////////////////////////////////
void print_char_freq( int *ch_freq)
{
int i;
for (i = 0; i < 256; i++)
{
printf( "%d\t%d\n", i, ch_freq[i]); // 문자인덱스, 빈도
}
}
////////////////////////////////////////////////////////////////////////////////
tNode *run_huffman( int *ch_freq, char *codes[])
{
tNode *root;
root = make_huffman_tree( ch_freq);
make_huffman_code( root, codes);
return root;
}
////////////////////////////////////////////////////////////////////////////////
void print_huffman_code( char *codes[])
{
int i;
for (i = 0; i < 256; i++)
{
printf( "%d\t%s\n", i, codes[i]);
}
}
////////////////////////////////////////////////////////////////////////////////
int main( int argc, char **argv)
{
FILE *fp;
FILE *infp, *outfp;
int ch_freq[256] = {0,}; // 문자별 빈도
char *codes[256]; // 문자별 허프만 코드 (ragged 배열)
tNode *huffman_tree; // 허프만 트리
if (argc != 4)
{
fprintf( stderr, "%s input-file encoded-file decoded-file\n", argv[0]);
return 1;
}
////////////////////////////////////////
fp = fopen( argv[1], "rt");
if (fp == NULL)
{
fprintf( stderr, "Error: cannot open file [%s]\n", argv[1]);
return 1;
}
int num_bytes = read_chars( fp, ch_freq);
fclose( fp);
print_char_freq( ch_freq);
huffman_tree = run_huffman( ch_freq, codes);
print_huffman_code( codes);
////////////////////////////////////////
infp = fopen( argv[1], "rt");
#ifdef BINARY_MODE
outfp = fopen( argv[2], "wb");
#else
outfp = fopen( argv[2], "wt");
#endif
#ifdef BINARY_MODE
//int encoded_bytes = encoding_binary( codes, infp, outfp);
#else
int encoded_bytes = encoding( codes, infp, outfp);
#endif
free_huffman_code( codes);
fclose( infp);
fclose( outfp);
////////////////////////////////////////
#ifdef BINARY_MODE
infp = fopen( argv[2], "rb");
#else
infp = fopen( argv[2], "rt");
#endif
outfp = fopen( argv[3], "wt");
#ifdef BINARY_MODE
//decoding_binary( huffman_tree, infp, outfp);
#else
decoding( huffman_tree, infp, outfp);
#endif
destroyTree( huffman_tree);
fclose( infp);
fclose( outfp);
////////////////////////////////////////
printf( "# of bytes of the original text = %d\n", num_bytes);
printf( "# of bytes of the compressed text = %d\n", encoded_bytes);
printf( "compression ratio = %.2f\n", ((float)num_bytes - encoded_bytes) / num_bytes * 100);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
void heapPrint( HEAP *heap)
{
int i;
tNode **p = heap->heapArr;
int last = heap->last;
for( i = 0; i <= last; i++)
{
printf("[%d]%c(%6d)\n", i, p[i]->data, p[i]->freq);
}
printf( "\n");
}
////////////////////////////////////////////////////////////////////////////////
// last = -1
HEAP *heapCreate( int capacity)
{
HEAP *heap;
heap = (HEAP *)malloc( sizeof(HEAP));
if (!heap) return NULL;
heap->last = -1;
heap->capacity = capacity;
heap->heapArr = (tNode **)malloc( sizeof(tNode *) * capacity);
if (heap->heapArr == NULL)
{
fprintf( stderr, "Error : not enough memory!\n");
free( heap);
return NULL;
}
return heap;
}
////////////////////////////////////////////////////////////////////////////////
static void _reheapUp( HEAP *heap, int index)
{
tNode **arr = heap->heapArr;
int parent;
while(1)
{
if (index == 0) return; // root node
parent = (index - 1) / 2;
if (arr[index]->freq < arr[parent]->freq) // exchange (for minheap)
{
tNode *temp = arr[index];
arr[index] = arr[parent];
arr[parent] = temp;
index = parent;
}
else return;
}
}
////////////////////////////////////////////////////////////////////////////////
int heapInsert( HEAP *heap, tNode *data)
{
if (heap->last == heap->capacity - 1)
return 0;
(heap->last)++;
(heap->heapArr)[heap->last] = data;
_reheapUp( heap, heap->last);
return 1;
}
////////////////////////////////////////////////////////////////////////////////
static void _reheapDown( HEAP *heap, int index)
{
tNode **arr = heap->heapArr;
tNode *leftData;
tNode *rightData;
int noright = 0;
int largeindex; // index of left or right child with large key
while(1)
{
if ((index * 2 + 1) > heap->last) return; // leaf node (there is no left subtree)
leftData = arr[index * 2 + 1];
if (index * 2 + 2 <= heap->last) rightData = arr[index * 2 + 2];
else noright = 1;
if (noright || leftData->freq < rightData->freq) largeindex = index * 2 + 1; // left child
else largeindex = index * 2 + 2; // right child
if (arr[index]->freq > arr[largeindex]->freq) // exchange (for minheap)
{
tNode *temp = arr[index];
arr[index] = arr[largeindex];
arr[largeindex] = temp;
index = largeindex;
noright = 0;
}
else return;
}
}
////////////////////////////////////////////////////////////////////////////////
tNode *heapDelete( HEAP *heap)
{
if (heap->last == -1) return NULL; // empty heap
tNode *data = heap->heapArr[0];
heap->heapArr[0] = heap->heapArr[heap->last];
(heap->last)--;
_reheapDown( heap, 0);
return data;
}
////////////////////////////////////////////////////////////////////////////////
void heapDestroy( HEAP *heap)
{
free(heap->heapArr);
free(heap);
}