Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. private int getSymbol(FileInputStream inFile, HuffmanTree T) throws IOException {
  2.         // COMPLETE THIS FUNCTION
  3.         // ----------------------
  4.         // Private field 'buffer' is a string of "0"s and "1s". If this string is empty you need
  5.         // to read a byte from the input file and convert it into a binary string to be stored in
  6.         // 'buffer' (see function byteToBinary()).
  7.         //
  8.         // You can then get the first bit from the buffer (and remove it) and use it to navigate
  9.         // the Huffman tree, moving to the left or right branch. This process will be repeated
  10.         // until you get to a leaf of the tree and return the corresponding symbol. Note that
  11.         // you may exhaust the buffer in the process and may have to read further bytes from the
  12.         // input file.
  13.         //
  14.         // You can add additional methods if necessary.
  15.         //
  16.  
  17.         char symbol = traverseTree(inFile, T);
  18.        
  19.         return int(symbol);     // change this line appropriately (or delete it altogether) when you
  20.                     // complete this method.
  21.     }
  22.  
  23.  
  24.  
  25.     private char traverseTree(FileInputStream inFile, HuffmanTree tree) throws IOException {
  26.         boolean finishedTraversal = false;
  27.         HuffmanTree currentTree = tree;
  28.                
  29.         while(!finishedTraversal) {
  30.             prepareBuffer(inFile);
  31.             currentTree = nextSubTree(currentTree);
  32.             finishedTraversal = currentTree.isLeaf();
  33.         }
  34.        
  35.         return currentTree.root().getSymbol();
  36.     }
  37.  
  38.  
  39.     private void prepareBuffer(FileInputStream inFile) throws IOException {    
  40.         if(buffer == "") {
  41.             buffer = byteToBinary(inFile.read());
  42.         }
  43.     }
  44.  
  45.  
  46.     private HuffmanTree nextSubTree(HuffmanTree current) {
  47.         HuffmanTree nextTree;
  48.        
  49.         if(buffer.charAt(0) == 0) {
  50.             nextTree = current.left();
  51.             buffer = buffer.substring(1);
  52.         }else {
  53.             nextTree = current.right();
  54.             buffer = buffer.substring(1);
  55.         }
  56.        
  57.         return nextTree;
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement