int printCodes(nodeStructure* rootNode) { static char buff[0xFF]; if ((rootNode->l == NULL) != (rootNode->r == NULL)) { // (possible logical XOR?) printf("MUDDLE ELEMENT! - %p\n", rootNode); return 1; } if (rootNode->l == NULL && rootNode->r == NULL) { // leaf reached if (strlen(buff) == 0) { buff[strlen(buff)] = '0'; buff[strlen(buff)+1] = '\0'; } printf("%s - %c\n", buff, rootNode->c); buff[(strlen(buff) > 0)? strlen(buff) - 1: 0]='\0'; return 0; } buff[strlen(buff)] = '0'; buff[strlen(buff)+1] = '\0'; printCodes(rootNode->l); buff[strlen(buff)] = '1'; buff[strlen(buff)+1] = '\0'; printCodes(rootNode->r); buff[(strlen(buff) > 0)? strlen(buff) - 1: 0]='\0'; return 0; }
void HuffmanCodes(char data[], int freq[], int size) { struct MinHeapNode* root = buildHuffmanTree(data, freq, size); int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top); }
// The main function that builds a Huffman Tree and print codes by traversing // the built Huffman Tree void HuffmanCodes(char data[], int freq[], int size) { // Construct Huffman Tree struct node* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using the Huffman tree built above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top); }
void printCodes (MinHeapNode* root, int arr[], int top) { //Assign 0 to left edge if (root->left) { arr[top]=0; printCodes(root->left, arr, top+1); } //Assign 1 to right edge if (root->right) { arr[top]=1; printCodes(root->right, arr, top+1); } if (isLeaf(root)) { fprintf(fp, "%c", root->data); printArr(arr, top); } }
void printCodes(struct MinHeapNode* root, int arr[], int top) { if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } if (isLeaf(root)) { printf("%c: ", root->data); printArr(arr, top); } }
void printCodes(Tree *dic, char *string) { Tree current = *dic; printf("Code : %d String : %s \n", current -> code, string); char *stringCopy = malloc((strlen(string) + 1) * sizeof(char)); strcpy(stringCopy, string); stringCopy[strlen(string) + 1] = '\0'; for(int a = 0; current -> children[a]; a++) { char letter = current -> childChar[a]; char *newString = newStringForLetterString(string, letter); printCodes(¤t -> children[a],newString); } }
// Prints huffman codes from the root of Huffman Tree. It uses arr[] to // store codes void printCodes(struct node* root, int arr[], int top) { // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then it contains one of the input // characters, print the character and its code from arr[] if (isLeaf(root)) { printf("%c: ", root->data); printArr(arr, top); } }
void HuffmanCodes(char data[], int freq[], int size) { MinHeapNode* root = buildHuffmanTree(data, freq, size); int arr[128], top=0; printCodes(root, arr, top); }
int main(int argc, char ** argv) { // Проверка состояния переданных аргументов if (argc == 1) { std::cout << "Too few arguments."; _getch(); exit(10); } if (argc > 2) { std::cout << "Too many arguments."; _getch(); exit(10); } /* Открываем и читаем файл*/ std::fstream file; // Переменная файлового потока std::filebuf* buf; // Указатель на буфер файлового потока buf = file.rdbuf(); // Устанавливаем указатель на буфер файлового потока buf->open(argv[1], std::ios::in); // Открываем файл на чтение /* Читаем файл и формируем вектор символов, упорядоченных по убыванию вероятностей их вхождений */ std::vector<struct node *> * countsSyms; // Вектор для хранения счетчиков вхождения символов в файл countsSyms = fcalcCountSyms(buf); if (countsSyms->size() == 0) // Файл пустой { std::cout << "The file " << argv[1] << " is empty."; _getch(); exit(10); } /* Формируем коды Шеннона */ std::vector<struct node *> * codeShannon; // Переменная для хранения символов и соответствующих кодов Шеннона codeShannon = 0; codeShannon = buildCodeShannon(countsSyms); /* Проверяем, выполняется ли неравество Крафта для полученных кодов Шеннона */ if (!verifyInequalKraft(codeShannon)) { std::cout << "This code not prefix."; _getch(); exit(10); } /* Выводим таблицу с кодами Шеннона и статистикой */ std::cout << "Table of code Shannon:" << std::endl; printCodes(codeShannon); std::cout << std::endl; /* Подсчитываем среднюю длину кодового слова для кодов Шеннона */ double averageLength; // Переменная для хранения средней длины кодового слова averageLength = calcAverageLengthWord(codeShannon); /* Выводим полученные данные на консоль */ std::cout.setf(std::ios::fixed); std::cout.precision(4); std::cout << "The average length Snannon code word: " << averageLength << std::endl << std::endl; /* Освобождаем память из-под вектора с кодами Шеннона */ codeShannon = freeVectorNode(codeShannon); /* Фомируем коды Фано */ std::vector<struct node *> * codeFano; // Переменная для хранения кодов Фано codeFano = 0; codeFano = buildCodeFano(countsSyms); /* Проверяем, выполняется ли неравество Крафта для полученных кодов Фано */ if (!verifyInequalKraft(codeFano)) { std::cout << "This code not prefix."; _getch(); exit(10); } /* Выводим таблицу с кодами Фано и статистикой */ std::cout << "Table of code Fano:" << std::endl; printCodes(codeFano); std::cout << std::endl; /* Подсчитываем среднюю длину кодового слова для кодов Фано */ averageLength = calcAverageLengthWord(codeFano); /* Выводим полученные данные на консоль */ std::cout << "The average length Fano code word: " << averageLength << std::endl; /* Освобождаем память из-под вектора с кодами Шеннона */ codeFano = freeVectorNode(codeFano); _getch(); return 0; }
int main(int argc, char *argv []) { FILE* outfile = NULL; char infilename[256], outfilename[256]; // Section of parsing command line arguments // Added by Yupeng int k, flag = 0; for (k = 1; k < argc; k++) { if (argv[k][0] != '-') { strcpy(infilename, argv[1]); freopen(infilename, "r", stdin); flag = 1; } else { if (argv[k][1] == 'o') { k++; // printf("outputfile : argv[%d] : %s\n",k,argv[k]); if (k == argc) { printf("Error : Inlegal command. There must be a param after -o option.\n"); } else { strcpy(outfilename, argv[k]); outfile = fopen(outfilename, "wb"); } } } } if (!flag) printf("Warning : haven't decide a source file, system will take the standard input as source.\n"); if (outfile == NULL) outfile = fopen("a.o", "wb"); // End of Arguments parsing printf("Parsing ...\n"); ASTree ast = parse(); printf("\n\nDump the program from the generated AST:\n"); dumpASTNode(ast->root, 0); // Section of code generate and output to file // Added by Yupeng Zhang printf("\n\nPCode generated from the generated AST:\n"); PcodeGenerater generator = newPcodeGenerater(); generate(generator, ast->root); int result; printCodes(generator->code, generator->cx); result = fwrite(&generator->cx, sizeof(long), 1, outfile); result = fwrite(generator->code, sizeof(instruction), generator->cx, outfile); fclose(outfile); //freopen(outfilename, "r", outfile); //system("PAUSE"); //printf("=====================\n"); //FILE* infile = fopen(outfilename, "r"); //if (outfile){ // int len = fread(&len, sizeof(long), 1, outfile); // instruction* code = (instruction*) malloc(sizeof(instruction) *(len + 1)); // fread(code, sizeof(instruction), len, outfile); // printCodes(code, len); // fclose(outfile); // free(code); //} // End of Section destroyAST(&ast); destroyPcodeGenerater(&generator); printf("\n\nFinished destroying AST.\n"); return(0); }