Guest User

Untitled

a guest
Jan 4th, 2018
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.45 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. /**
  8. *This class implements Huffman's Algorithm. It reads in any .txt file given in the command argument
  9. * and reads the characters that are in and determines: how many characters there are, how many times they occur, and
  10. * generates binary code for them according to Huffman's Algorithm.
  11. * @author Charlie Davis (CLD0023@auburn.edu), Jordan Hutcheson (jmh0049@auburn.edu)
  12. * @version 2011-04-25
  13. */
  14.  
  15. public class Huff
  16. {
  17. private File file;
  18. private BufferedReader reader;
  19. private HashMap charHash = new HashMap();
  20. private PriorityQueue queue;
  21. private String string = "";
  22. private char[] tokens;
  23. private ArrayList<TreeNode> array = new ArrayList<TreeNode>();
  24. private int bitBefore = 0;
  25. private int bitAfter = 0;
  26.  
  27. /**
  28. *Constructor that takes in a String representation of the File that is to be read.
  29. *@param fileIn String containing a file name including .txt
  30. */
  31. public Huff(String fileIn)
  32. {
  33. this(new File(fileIn));
  34. }
  35. /**
  36. *Secondary constructor that stores the file and calls the read() method.
  37. *@param fileIn to be read by Huff.
  38. */
  39.  
  40. public Huff(File fileIn)
  41. {
  42. this.file = fileIn;
  43. read();
  44. }
  45. /**
  46. *This is the read() method which essentially performs the task of reading the file into the class.
  47. *This method also sets up the small variable important to the final output.
  48. */
  49. public void read()
  50. {
  51. try {
  52. reader = new BufferedReader(new FileReader(file));
  53. while (reader.ready())
  54. {
  55. string += reader.readLine();
  56. }
  57. //convert the string into a char[]
  58. tokens = string.toCharArray();
  59. //bits before the text is "compressed"
  60. bitBefore = 8 * tokens.length;
  61. reader.close();
  62. }
  63. catch (IOException e)
  64. {
  65. e.printStackTrace();
  66. return;
  67. }
  68. //instantiate the toAdd boolean to true so that it will add the first character.
  69. boolean toAdd = true;
  70.  
  71. //loop through the token array and store the characters as TreeNodes into an ArrayList.
  72. for (int i = 0; i < tokens.length; i++) {
  73.  
  74. for (int a = 0; a < array.size(); a++) {
  75. //if the character is already inside of the arrayList find it and increment its weight.
  76. if (tokens[i] == (Character) (array.get(a).getValue())) {
  77. array.get(a).setWeight(array.get(a).getWeight() + 1);
  78. toAdd = false;
  79. break;
  80. }
  81. }
  82.  
  83. if (toAdd) {
  84. array.add(new TreeNode(tokens[i], 1));
  85. }
  86.  
  87. toAdd = true;
  88. }
  89.  
  90. queue = new PriorityQueue(array);
  91.  
  92. TreeNode c1;
  93. TreeNode c2;
  94. TreeNode c3;
  95.  
  96. while (queue.size() > 1) {
  97. c1 = (TreeNode) queue.remove();
  98. c2 = (TreeNode) queue.remove();
  99. c3 = new TreeNode(null, c1.getWeight() + c2.getWeight(), c1, c2);
  100. queue.add(c3);
  101. }
  102.  
  103. TreeNode minTreeNodeTree = (TreeNode) queue.remove();
  104.  
  105. //traverse the tree and set all of the binary.
  106. for (int i = 0; i < tokens.length; i++) {
  107. searchTree(minTreeNodeTree, tokens[i], "");
  108. }
  109.  
  110. String s = "";
  111. for (int i = 0; i < tokens.length; i++) {
  112. s += charHash.get(tokens[i]);
  113. }
  114.  
  115. bitAfter = s.length();
  116.  
  117. }
  118. /**
  119. *A Recursive Depth-First approach to traversing the binary tree. Takes in the intial string "" and adds a '0' or a '1' depending on if it goes
  120. *to a left child or a right child.
  121. *@param node TreeNode to be traversed.
  122. *@param target char to be found, if it exists.
  123. *@param pre String binary to be produced and placed in the HashMap along with the character key.
  124. */
  125. @SuppressWarnings("unchecked")
  126. public void searchTree(TreeNode node, char target, String pre) {
  127.  
  128. if (node == null) {
  129. return;
  130. }
  131.  
  132. else if (node.getValue() != null && (Character) node.getValue() == target) {
  133. //store the character as a key along with the binary string (pre)
  134. charHash.put((Character) node.getValue(), pre);
  135. return;
  136. }
  137.  
  138. else {
  139. searchTree(node.lNode(), target, pre + '0');
  140. searchTree(node.rNode(), target, pre + '1');
  141. }
  142. }
  143.  
  144. /**
  145. *Creates a string for output containing the characters, frequency of the character, and the binary generated.
  146. *@return String representation of each character.
  147. */
  148. public String toString()
  149. {
  150. String s = "Huff:\n";
  151. for (int i = 0; i < array.size(); i++)
  152. {
  153. s += array.get(i) + " Huffman Code: " + charHash.get(array.get(i).getValue()) + "\n";
  154. }
  155. s += "Bits before: " + bitBefore + "\nBits after: " + bitAfter + "\nTotal characters in the file: " + tokens.length;
  156. return s;
  157. }
  158.  
  159. /**
  160. *This main runs the first file in the Command Arguments if it is a valid file.
  161. *@param args user-defined File to be read.
  162. */
  163.  
  164. public static void main(String[] args) {
  165. File file;
  166. try {
  167. file = new File(args[0]);
  168. if (file.exists()) {
  169. Huff p = new Huff(args[0]);
  170. System.out.print(p);
  171. }
  172. else {
  173. System.out.println("File or Filename invalid.");
  174. }
  175. }
  176. catch (ArrayIndexOutOfBoundsException e) {
  177. System.out.println("There are no command arguments..");
  178. }
  179.  
  180.  
  181. }
  182.  
  183. }
  184.  
  185. import java.io.File;
  186. import java.io.BufferedReader;
  187. import java.io.FileReader;
  188. import java.io.IOException;
  189. import java.util.ArrayList;
  190. import java.util.HashMap;
  191. import java.util.Comparator;
  192. /**
  193. *This class implements Huffman's Algorithm but with a Max Heap instead of a Min Heap, making it severly worse.
  194. * It reads in any .txt file given in the command argument
  195. * and reads the characters that are in and determines: how many characters there are, how many times they occur, and
  196. * generates binary code for them according to Huffman's Algorithm.
  197. * @author Charlie Davis (CLD0023@auburn.edu), Jordan Hutcheson (jmh0049@auburn.edu)
  198. * @version 2011-04-25
  199. */
  200.  
  201. public class Puff
  202. {
  203.  
  204. private File file;
  205. private BufferedReader reader;
  206. private HashMap charHash = new HashMap();
  207. private PriorityQueue queue;
  208. private String string = "";
  209. private char[] tokens;
  210. private ArrayList<TreeNode> array = new ArrayList<TreeNode>();
  211. private int bitBefore = 0;
  212. private int bitAfter = 0;
  213. /**
  214. *An inner class in Puff that is simply a Comparator to be given into the PriorityQueue.
  215. */
  216. @SuppressWarnings("unchecked")
  217. public static class PuffCompare implements Comparator {
  218. /**
  219. *Method that returns the negative comparison of the two objects.
  220. *@param o1 Object one to be compared.
  221. *@param o2 Object two to be compared.
  222. *@return int based on comparison.
  223. */
  224. public int compare(Object o1, Object o2)
  225. {
  226. return -(((Comparable) o1).compareTo(o2));
  227. }
  228.  
  229. }
  230. /**
  231. *Constructor that takes in a String fileName and passes it into the secondary constructor.
  232. *@param fileIn String containing a file name including .txt
  233. */
  234. public Puff(String fileIn)
  235. {
  236. this(new File(fileIn));
  237. }
  238. /**
  239. *Secondary constructor that stores the file and calls the read() method.
  240. *@param fileIn to be read by Puff.
  241. */
  242. public Puff(File fileIn)
  243. {
  244. this.file = fileIn;
  245. read();
  246. }
  247. /**
  248. *This is the read() method which essentially performs the task of reading the file into the class.
  249. *This method also sets up the small variable important to the final output.
  250. */
  251. public void read()
  252. {
  253. try {
  254. reader = new BufferedReader(new FileReader(file));
  255. while (reader.ready())
  256. {
  257. string += reader.readLine();
  258. }
  259. tokens = string.toCharArray();
  260. bitBefore = 8 * tokens.length;
  261. reader.close();
  262. }
  263. catch (IOException e)
  264. {
  265. e.printStackTrace();
  266. return;
  267. }
  268.  
  269. boolean toAdd = true;
  270.  
  271. for (int i = 0; i < tokens.length; i++) {
  272.  
  273. for (int a = 0; a < array.size(); a++) {
  274.  
  275. if (tokens[i] == (Character) (array.get(a).getValue())) {
  276. array.get(a).setWeight(array.get(a).getWeight() + 1);
  277. toAdd = false;
  278. break;
  279. }
  280. }
  281.  
  282. if (toAdd) {
  283. array.add(new TreeNode(tokens[i], 1));
  284. }
  285.  
  286. toAdd = true;
  287. }
  288.  
  289. Comparator compare = new PuffCompare();
  290. queue = new PriorityQueue(compare);
  291.  
  292. for (int i = 0; i < array.size(); i++) {
  293. queue.add(array.get(i));
  294. }
  295.  
  296.  
  297. TreeNode c1;
  298. TreeNode c2;
  299. TreeNode c3;
  300.  
  301. while (queue.size() > 1) {
  302. c1 = (TreeNode) queue.remove();
  303. c2 = (TreeNode) queue.remove();
  304. c3 = new TreeNode(null, c1.getWeight() + c2.getWeight(), c1, c2);
  305. queue.add(c3);
  306.  
  307. }
  308.  
  309. TreeNode minTreeNodeTree = (TreeNode) queue.remove();
  310. for (int i = 0; i < tokens.length; i++) {
  311. searchTree(minTreeNodeTree, tokens[i], "");
  312. }
  313.  
  314. String s = "";
  315. for (int i = 0; i < tokens.length; i++) {
  316. s += charHash.get(tokens[i]);
  317. }
  318.  
  319. bitAfter = s.length();
  320.  
  321. }
  322. /**
  323. *A Recursive Depth-First approach to traversing the binary tree. Takes in the intial string "" and adds a '0' or a '1' depending on if it goes
  324. *to a left child or a right child.
  325. *@param node TreeNode
  326. *@param target char
  327. *@param pre String
  328. */
  329. @SuppressWarnings("unchecked")
  330. public void searchTree(TreeNode node, char target, String pre) {
  331.  
  332. if (node == null) {
  333. return;
  334. }
  335.  
  336. else if (node.getValue() != null && (Character) node.getValue() == target) {
  337. charHash.put((Character) node.getValue(), pre);
  338. return;
  339. }
  340.  
  341. else {
  342. searchTree(node.lNode(), target, pre + '0');
  343. searchTree(node.rNode(), target, pre + '1');
  344. }
  345. }
  346. /**
  347. *Creates a string for output containing the characters, frequency of the character, and the binary generated.
  348. *@return String representation of each character.
  349. */
  350. public String toString()
  351. {
  352. String s = "Puff:\n";
  353. for (int i = 0; i < array.size(); i++)
  354. {
  355. s += array.get(i) + " Huffman Code: " + charHash.get(array.get(i).getValue()) + "\n";
  356. }
  357. s += "Bits before: " + bitBefore + "\nBits after: " + bitAfter + "\nTotal characters in the file: " + tokens.length;
  358. return s;
  359. }
  360.  
  361. /**
  362. *This main method runs the first file in the Command Argument if it is a valid file.
  363. *@param args user-defined File to be read.
  364. */
  365. public static void main(String[] args) {
  366. File file;
  367. try {
  368. file = new File(args[0]);
  369. if (file.exists()) {
  370. Puff p = new Puff(args[0]);
  371. System.out.print(p);
  372. }
  373. else {
  374. System.out.println("File or Filename invalid.");
  375. }
  376. }
  377. catch (ArrayIndexOutOfBoundsException e) {
  378. System.out.println("There are no command arguments..");
  379. }
  380. }
  381.  
  382. }
  383.  
  384. import java.io.File;
  385. import java.io.BufferedReader;
  386. import java.io.FileReader;
  387. import java.io.IOException;
  388. import java.util.ArrayList;
  389. import java.util.HashMap;
  390. import java.util.HashSet;
  391. /**
  392. *Blow is the class responsible for compressing files using a fixed length code instead of Huffman's algorithm.
  393. *The class finds what 2 to the nth is large enough to represent all the unique characters represented in the file.
  394. *Then it creates binary that has up to n bits to represent the characters.
  395. *
  396. *@author Jordan Hutcheson (jmh0049@auburn.edu), Charlie Davis (CLD0023@auburn.edu)
  397. *@version 2011-04-25
  398. */
  399. public class Blow
  400. {
  401.  
  402. private File file;
  403. private BufferedReader reader;
  404. private HashMap<Character, String> charHash = new HashMap<Character, String>();
  405. private String string = "";
  406. private char[] tokens;
  407. private ArrayList<TreeNode> nodeArray = new ArrayList<TreeNode>();
  408. private int bitBefore = 0;
  409. private int bitAfter = 0;
  410. private static int spacesNeeded = 0;
  411.  
  412. /**
  413. *This is the class's constructor that creates the blow class and sets up the values based off of the file.
  414. *
  415. *@param fileIn The file to be used to set up the class.
  416. */
  417. public Blow(String fileIn)
  418. {
  419. this(new File(fileIn));
  420. }
  421. /**
  422. *This is the secondary constructor that is called in the previous constructor to create the Blow class. Calls the
  423. *read() method.
  424. *
  425. *@param fileIn The file to set up the class.
  426. */
  427. public Blow(File fileIn)
  428. {
  429. this.file = fileIn;
  430. read();
  431. }
  432. /**
  433. *This is the read() method which essentially performs the task of reading the file into the class.
  434. *This method also sets up the small variable important to the final output.
  435. */
  436. public void read()
  437. {
  438. try {
  439. reader = new BufferedReader(new FileReader(file));
  440. while (reader.ready())
  441. {
  442. string += reader.readLine();
  443. }
  444. tokens = string.toCharArray();
  445. bitBefore = 8 * tokens.length;
  446. reader.close();
  447. }
  448. catch (IOException e)
  449. {
  450. e.printStackTrace();
  451. return;
  452. }
  453.  
  454. boolean toAdd = true;
  455.  
  456. for (int i = 0; i < tokens.length; i++) {
  457.  
  458. for (int a = 0; a < nodeArray.size(); a++) {
  459.  
  460. if (tokens[i] == (Character) (nodeArray.get(a).getValue())) {
  461. nodeArray.get(a).setWeight(nodeArray.get(a).getWeight() + 1);
  462. toAdd = false;
  463. break;
  464. }
  465. }
  466.  
  467. if (toAdd) {
  468. nodeArray.add(new TreeNode(tokens[i], 1));
  469. }
  470.  
  471. toAdd = true;
  472. }
  473.  
  474. charHash = createBinary(nodeArray);
  475. bitAfter = spacesNeeded * tokens.length;
  476.  
  477. }
  478. /**
  479. *This is a recursive method that iterates in order to find out if the passed in array can be, by the rules of
  480. *binary addition, be incremented and if so performs it. It actually uses reverse recursion.
  481. *
  482. *@param arrayIn The array to be checked if it can be incremented.
  483. *@param j Where in array it should be checked if it can increment by one.
  484. *@return arrayIn Returns the arraIn at these default conditions.
  485. */
  486.  
  487. private int[] recursive(int[] arrayIn, int j) {
  488. if (j < 0 && arrayIn[0] == 1) {
  489. return arrayIn;
  490. }
  491. else if (arrayIn[j] == 0) {
  492. arrayIn[j] = 1;
  493. return arrayIn;
  494. }
  495. else {
  496. arrayIn[j] = 0;
  497. return recursive(arrayIn, j - 1);
  498. }
  499. }
  500. /**
  501. *checkAllDone takes in an array and checks to see if every position is all equal to one. This simply
  502. *checks to see if the recursive method has executed to it maximum amount.
  503. *
  504. *@param arrayIn The array that is going to be checked if all positions are equal to 1.
  505. *@return allDone Boolean which tells whether all the positions of the array are 1 or not.
  506. */
  507. public boolean checkAllDone(int[] arrayIn) {
  508. boolean allDone = true;
  509. int n = 0;
  510. while (allDone && n < arrayIn.length) {
  511. if (arrayIn[n] != 1) {
  512. allDone = false;
  513. }
  514. else {
  515. n++;
  516. }
  517. }
  518. return allDone;
  519. }
  520. /**
  521. *This method is responsible for creating the hasmap that is the main brute force of the whole class.
  522. *This class determines how many binary numbers of the fixed length are necessary to represent all the unique chars.
  523. *Then, the class iterates and creates the binary while also assigning the new binary to the unique characters in the
  524. *charHash.
  525. *
  526. *@param a ArrayList of tree nodes that represent the unique characters.
  527. *@return map The returned hashMap that contains all the newly assigned variables and binary numbers.
  528. */
  529. public HashMap<Character, String> createBinary(ArrayList<TreeNode> a) {
  530. int n = 0;
  531. int uniqueChars = a.size();
  532. HashSet<String> binaryHolder = new HashSet<String>();
  533. HashMap<Character, String> map = new HashMap<Character, String>();
  534.  
  535. while (Math.pow(2, n) < uniqueChars) {
  536. n++;
  537. }
  538. spacesNeeded = n;
  539. int[] binary = new int[n];
  540.  
  541. while (!checkAllDone(binary) && !(binaryHolder.size() == uniqueChars)) {
  542. binaryHolder.add(convert(binary));
  543. binary = recursive(binary, binary.length - 1);
  544. }
  545. int i = 0;
  546. for (String s : binaryHolder) {
  547. map.put((Character) a.get(i).getValue(), s);
  548. i++;
  549. }
  550. return map;
  551. }
  552. /**
  553. *convert() simply takes in an array of integers and converts them into a string. This method is mainly only important for the toString()
  554. *method and does not carry much purpose elsewhere in the class.
  555. *
  556. *@param a The integer array to be transformed into a String.
  557. *@return temp The returned String version of the int array.
  558. */
  559. public String convert(int[] a)
  560. {
  561. String temp = "";
  562. for (int i = 0; i < a.length; i++) {
  563. temp += a[i];
  564. }
  565. return temp;
  566. }
  567. /**
  568. *The toString method of the class which takes the class and puts its information into a string form for reading.
  569. *It shows all the special characters and their values and the amount by which the file has been shortened.
  570. *
  571. *@return string The string representation of the class.
  572. */
  573. public String toString()
  574. {
  575. String aString = "Blow:\n";
  576. for (int i = 0; i < nodeArray.size(); i++)
  577. {
  578. aString += nodeArray.get(i) + " Code: " + charHash.get(nodeArray.get(i).getValue()) + "\n";
  579. }
  580. aString += "Bits before: " + bitBefore + "\nBits after: " + bitAfter + "\nTotal characters in the file: " + tokens.length;
  581. return aString;
  582. }
  583. /**
  584. *This is the main method of the class Blow. It takes in args but only uses the first argument passed.
  585. *
  586. *@param args The arguments are generally going to be files passed in as the name of files.
  587. */
  588.  
  589. public static void main(String[] args) {
  590. File file;
  591. try {
  592. file = new File(args[0]);
  593. if (file.exists()) {
  594. Blow p = new Blow(args[0]);
  595. System.out.print(p);
  596. }
  597. else {
  598. System.out.println("YO FILE SUX");
  599. }
  600. }
  601. catch (ArrayIndexOutOfBoundsException e) {
  602. System.out.println("There are no command arguments..");
  603. }
  604. }
  605.  
  606. }
Add Comment
Please, Sign In to add comment