From 364d085c7c2b7384f9513c05d42d4eb8d3357f77 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Sat, 26 Nov 2022 22:48:15 +0100 Subject: [PATCH] huffman calculate frequencies --- Makefile | 2 +- huffman/huffman.c | 23 +++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index f84ef94..1c0b9a1 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ pre: @mkdir -p bin huffman/bin huffman/testfiles clean: - rm -rvf bin huffman/bin + rm -rvf bin huffman/testfiles huffman/bin huffman/bin/huffman: huffman/huffman.c $(CC) $(CFLAGS) -o $@ $< -lm diff --git a/huffman/huffman.c b/huffman/huffman.c index 4293ca9..1f6c230 100644 --- a/huffman/huffman.c +++ b/huffman/huffman.c @@ -16,6 +16,7 @@ struct Node { uint8_t byte; size_t occurences; unsigned frequencyPriority; + float frequencyRaw; }; // a combination of nodes. @@ -38,9 +39,9 @@ void initNodes(){ nodes[i].byte = i; nodes[i].occurences = 0; nodes[i].frequencyPriority = 0; + nodes[i].frequencyRaw = -1; heaps[i].isRoot = false; } - } // stolen from stackoverflow @@ -77,6 +78,7 @@ int main(int argc, char *argv[]) { FILE *fptrR = NULL; // file pointer for reading FILE *fptrW = NULL; // file pointer for writing + // process command line options while ((opt = getopt(argc, argv, "dvxhf:")) != -1) { if (debug) printf("optarg is: %s\n", optarg); @@ -103,7 +105,7 @@ int main(int argc, char *argv[]) { } } - // Now optind (declared extern int by ) is the index of the first + // Now optint (declared extern int by ) is the index of the first // non-option argument. If it is >= argc, there were no non-option arguments. if (verbose) @@ -213,6 +215,23 @@ int main(int argc, char *argv[]) { } // TODO calculate frequenciePririties + float addedUpFrequencies = 0; // only needed in debug, but it's efficient to calculate it with the loop. + for(int i = 0; i < 256; i++){ // calculate frequencies + nodes[i].frequencyRaw = 100*nodes[i].occurences / (float)filelen; + addedUpFrequencies += nodes[i].frequencyRaw; + } + + if(debug){ // print frequencies in debug mode + printf("Raw Frequencies of bytes:\n"); + for(int i = 0; i < 256; i++){ + printf("0x%02x: %lf\t", i, nodes[i].frequencyRaw); + if(i%5==0) + printf("\n"); + } + printf("\nAddedUpFrequencies: %f%%\n", addedUpFrequencies); + } + + // TODO sort by frequencieRaw, then sort references by frequency // TODO build tree using Heaps