Advertisement
Guest User

Untitled

a guest
Jun 26th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 10.58 KB | None | 0 0
  1. package patmat
  2.  
  3. import common._
  4.  
  5. import scala.collection.immutable.Nil
  6.  
  7. /**
  8.   * Assignment 4: Huffman coding
  9.   *
  10.   */
  11. object Huffman {
  12.  
  13.   /**
  14.     * A huffman code is represented by a binary tree.
  15.     *
  16.     * Every `Leaf` node of the tree represents one character of the alphabet that the tree can encode.
  17.     * The weight of a `Leaf` is the frequency of appearance of the character.
  18.     *
  19.     * The branches of the huffman tree, the `Fork` nodes, represent a set containing all the characters
  20.     * present in the leaves below it. The weight of a `Fork` node is the sum of the weights of these
  21.     * leaves.
  22.     */
  23.   abstract class CodeTree
  24.  
  25.   case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
  26.  
  27.   case class Leaf(char: Char, weight: Int) extends CodeTree
  28.  
  29.  
  30.   // Part 1: Basics
  31.   def weight(tree: CodeTree): Int = tree match {
  32.     case Leaf(c, w) => w
  33.     case Fork(l, r, c, w) => weight(l) + weight(r)
  34.   }
  35.  
  36.   def chars(tree: CodeTree): List[Char] = tree match {
  37.     case Leaf(c, w) => List(c)
  38.     case Fork(l, r, c, w) => chars(l) ::: chars(r)
  39.   }
  40.  
  41.   def makeCodeTree(left: CodeTree, right: CodeTree) =
  42.     Fork(left, right, chars(left) ::: chars(right), weight(left) + weight(right))
  43.  
  44.  
  45.   // Part 2: Generating Huffman trees
  46.  
  47.   /**
  48.     * In this assignment, we are working with lists of characters. This function allows
  49.     * you to easily create a character list from a given string.
  50.     */
  51.   def string2Chars(str: String): List[Char] = str.toList
  52.  
  53.   /**
  54.     * This function computes for each unique character in the list `chars` the number of
  55.     * times it occurs. For example, the invocation
  56.     *
  57.     * times(List('a', 'b', 'a'))
  58.     *
  59.     * should return the following (the order of the resulting list is not important):
  60.     *
  61.     * List(('a', 2), ('b', 1))
  62.     *
  63.     * The type `List[(Char, Int)]` denotes a list of pairs, where each pair consists of a
  64.     * character and an integer. Pairs can be constructed easily using parentheses:
  65.     *
  66.     * val pair: (Char, Int) = ('c', 1)
  67.     *
  68.     * In order to access the two elements of a pair, you can use the accessors `_1` and `_2`:
  69.     *
  70.     * val theChar = pair._1
  71.     * val theInt  = pair._2
  72.     *
  73.     * Another way to deconstruct a pair is using pattern matching:
  74.     *
  75.     * pair match {
  76.     * case (theChar, theInt) =>
  77.     * println("character is: "+ theChar)
  78.     * println("integer is  : "+ theInt)
  79.     * }
  80.     */
  81.   def times(chars: List[Char]): List[(Char, Int)] =
  82.     chars.distinct.map((c) => (c, chars.count(x => x == c)))
  83.  
  84.   /**
  85.     * Returns a list of `Leaf` nodes for a given frequency table `freqs`.
  86.     *
  87.     * The returned list should be ordered by ascending weights (i.e. the
  88.     * head of the list should have the smallest weight), where the weight
  89.     * of a leaf is the frequency of the character.
  90.     */
  91.   def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] =
  92.     freqs.sortBy(-_._2).map((f) => Leaf(f._1, f._2))
  93.  
  94.   /**
  95.     * Checks whether the list `trees` contains only one single code tree.
  96.     */
  97.   def singleton(trees: List[CodeTree]): Boolean = trees.size == 1
  98.  
  99.   /**
  100.     * The parameter `trees` of this function is a list of code trees ordered
  101.     * by ascending weights.
  102.     *
  103.     * This function takes the first two elements of the list `trees` and combines
  104.     * them into a single `Fork` node. This node is then added back into the
  105.     * remaining elements of `trees` at a position such that the ordering by weights
  106.     * is preserved.
  107.     *
  108.     * If `trees` is a list of less than two elements, that list should be returned
  109.     * unchanged.
  110.     */
  111.   def combine(trees: List[CodeTree]): List[CodeTree] = {
  112.     if (singleton(trees)) trees
  113.     else {
  114.       val node = makeCodeTree(trees.head, trees(1))
  115.       val trimmedTree = trees.drop(2)
  116.       combine((node :: trimmedTree).sortBy(Huffman.weight))
  117.     }
  118.   }
  119.  
  120.   /**
  121.     * This function will be called in the following way:
  122.     *
  123.     * until(singleton, combine)(trees)
  124.     *
  125.     * where `trees` is of type `List[CodeTree]`, `singleton` and `combine` refer to
  126.     * the two functions defined above.
  127.     *
  128.     * In such an invocation, `until` should call the two functions until the list of
  129.     * code trees contains only one single tree, and then return that singleton list.
  130.     *
  131.     * Hint: before writing the implementation,
  132.     * - start by defining the parameter types such that the above example invocation
  133.     * is valid. The parameter types of `until` should match the argument types of
  134.     * the example invocation. Also define the return type of the `until` function.
  135.     * - try to find sensible parameter names for `xxx`, `yyy` and `zzz`.
  136.     */
  137.   def until(singleton: List[CodeTree] => Boolean,
  138.             combine: List[CodeTree] => List[CodeTree])
  139.            (trees: List[CodeTree]): List[CodeTree] =
  140.     if (singleton(trees)) trees else until(singleton, combine)(combine(trees))
  141.  
  142.   /**
  143.     * This function creates a code tree which is optimal to encode the text `chars`.
  144.     *
  145.     * The parameter `chars` is an arbitrary text. This function extracts the character
  146.     * frequencies from that text and creates a code tree based on them.
  147.     */
  148.   def createCodeTree(chars: List[Char]): CodeTree =
  149.     until(singleton, combine)(makeOrderedLeafList(times(chars))).head
  150.  
  151.  
  152.   // Part 3: Decoding
  153.   type Bit = Int
  154.  
  155.   /**
  156.     * This function decodes the bit sequence `bits` using the code tree `tree` and returns
  157.     * the resulting list of characters.
  158.     */
  159.   def decode(tree: CodeTree, bits: List[Bit]): List[Char] = {
  160.     def helper(partial: CodeTree, encoded: List[Bit], decoded: List[Char]): List[Char] = (partial, encoded) match {
  161.       case (Fork(l, r, c, w), Nil) => decoded
  162.       case (Leaf(c, w), es) => c :: helper(tree, es, decoded)
  163.       case (Fork(left, right, c, w), e :: es) =>
  164.         if (e == 0) helper(left, es, decoded)
  165.         else helper(right, es, decoded)
  166.     }
  167.  
  168.     helper(tree, bits, Nil)
  169.   }
  170.  
  171.   /**
  172.     * A Huffman coding tree for the French language.
  173.     * Generated from the data given at
  174.     * http://fr.wikipedia.org/wiki/Fr%C3%A9quence_d%27apparition_des_lettres_en_fran%C3%A7ais
  175.     */
  176.   val frenchCode: CodeTree = Fork(Fork(Fork(Leaf('s', 121895), Fork(Leaf('d', 56269), Fork(Fork(Fork(Leaf('x', 5928), Leaf('j', 8351), List('x', 'j'), 14279), Leaf('f', 16351), List('x', 'j', 'f'), 30630), Fork(Fork(Fork(Fork(Leaf('z', 2093), Fork(Leaf('k', 745), Leaf('w', 1747), List('k', 'w'), 2492), List('z', 'k', 'w'), 4585), Leaf('y', 4725), List('z', 'k', 'w', 'y'), 9310), Leaf('h', 11298), List('z', 'k', 'w', 'y', 'h'), 20608), Leaf('q', 20889), List('z', 'k', 'w', 'y', 'h', 'q'), 41497), List('x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 72127), List('d', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 128396), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 250291), Fork(Fork(Leaf('o', 82762), Leaf('l', 83668), List('o', 'l'), 166430), Fork(Fork(Leaf('m', 45521), Leaf('p', 46335), List('m', 'p'), 91856), Leaf('u', 96785), List('m', 'p', 'u'), 188641), List('o', 'l', 'm', 'p', 'u'), 355071), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q', 'o', 'l', 'm', 'p', 'u'), 605362), Fork(Fork(Fork(Leaf('r', 100500), Fork(Leaf('c', 50003), Fork(Leaf('v', 24975), Fork(Leaf('g', 13288), Leaf('b', 13822), List('g', 'b'), 27110), List('v', 'g', 'b'), 52085), List('c', 'v', 'g', 'b'), 102088), List('r', 'c', 'v', 'g', 'b'), 202588), Fork(Leaf('n', 108812), Leaf('t', 111103), List('n', 't'), 219915), List('r', 'c', 'v', 'g', 'b', 'n', 't'), 422503), Fork(Leaf('e', 225947), Fork(Leaf('i', 115465), Leaf('a', 117110), List('i', 'a'), 232575), List('e', 'i', 'a'), 458522), List('r', 'c', 'v', 'g', 'b', 'n', 't', 'e', 'i', 'a'), 881025), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q', 'o', 'l', 'm', 'p', 'u', 'r', 'c', 'v', 'g', 'b', 'n', 't', 'e', 'i', 'a'), 1486387)
  177.  
  178.   /**
  179.     * What does the secret message say? Can you decode it?
  180.     * For the decoding use the 'frenchCode' Huffman tree defined above.
  181.     **/
  182.   val secret: List[Bit] = List(0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1)
  183.  
  184.   /**
  185.     * Write a function that returns the decoded secret
  186.     */
  187.   def decodedSecret: List[Char] = decode(frenchCode, secret)
  188.  
  189.  
  190.   // Part 4a: Encoding using Huffman tree
  191.  
  192.   /**
  193.     * This function encodes `text` using the code tree `tree`
  194.     * into a sequence of bits.
  195.     */
  196.   def encode(tree: CodeTree)(text: List[Char]): List[Bit] = {
  197.     def encodeChar(partial: CodeTree)(char: Char)(encoded: List[Bit]): List[Bit] = partial match {
  198.       case Leaf(_, _) => encoded
  199.       case Fork(left, right, c, w) =>
  200.         if (chars(left).contains(char)) 0 :: encodeChar(left)(char)(encoded)
  201.         else 1 :: encodeChar(right)(char)(encoded)
  202.     }
  203.  
  204.     text.flatMap(c => encodeChar(tree)(c)(List[Bit]()))
  205.   }
  206.  
  207.   // Part 4b: Encoding using code table
  208.  
  209.   type CodeTable = List[(Char, List[Bit])]
  210.  
  211.   /**
  212.     * This function returns the bit sequence that represents the character `char` in
  213.     * the code table `table`.
  214.     */
  215.   def codeBits(table: CodeTable)(char: Char): List[Bit] = table.find(t => t._1 == char).get._2
  216.  
  217.   /**
  218.     * Given a code tree, create a code table which contains, for every character in the
  219.     * code tree, the sequence of bits representing that character.
  220.     *
  221.     * Hint: think of a recursive solution: every sub-tree of the code tree `tree` is itself
  222.     * a valid code tree that can be represented as a code table. Using the code tables of the
  223.     * sub-trees, think of how to build the code table for the entire tree.
  224.     */
  225.   def convert(tree: CodeTree): CodeTable = {
  226.     def helper(auxTree: CodeTree, bits: List[Bit]): CodeTable = auxTree match {
  227.       case Leaf(c, w) => List((c, bits))
  228.       case Fork(left, right, cs, w) =>
  229.         helper(left, bits ::: List(0)) ::: helper(right, bits ::: List(1))
  230.     }
  231.  
  232.     helper(tree, Nil)
  233.   }
  234.  
  235.   /**
  236.     * This function takes two code tables and merges them into one. Depending on how you
  237.     * use it in the `convert` method above, this merge method might also do some transformations
  238.     * on the two parameter code tables.
  239.     */
  240.   def mergeCodeTables(a: CodeTable, b: CodeTable): CodeTable = ???
  241.  
  242.   /**
  243.     * This function encodes `text` according to the code tree `tree`.
  244.     *
  245.     * To speed up the encoding process, it first converts the code tree to a code table
  246.     * and then uses it to perform the actual encoding.
  247.     */
  248.   def quickEncode(tree: CodeTree)(text: List[Char]): List[Bit] = ???
  249. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement