コード例 #1
0
    static Tree Huffman(string msg)
    {
        /* Построяване на таблица на честотите на срещане */
        Dictionary <char, int> freqs = msg.GroupBy(ch => ch)
                                       .ToDictionary(g => g.Key, g => g.Count());

        var forest = new HeapForest();

        /* За всеки символ с ненулева честота на срещане се създава тривиално дърво */
        foreach (var ch in freqs.Keys.OrderBy(ch => ch))
        {
            forest.Add(new Tree {
                Char = ch, Weight = freqs[ch]
            });
        }

        while (forest.Count > 1)
        {
            Tree minTree1 = forest.GetMin(); /* Намиране на двата най-редки върха */
            Tree minTree2 = forest.GetMin();

            /* Създаване на нов възел - обединение на двата най-редки */
            var tree = new Tree {
                Left   = minTree1, Right = minTree2,
                Weight = minTree1.Weight + minTree2.Weight
            };
            forest.Add(tree);
        }
        return(forest.GetMin());
    }
コード例 #2
0
    static Tree Huffman(string msg)
    {
        /* Построяване на таблица на честотите на срещане */
        Dictionary<char, int> freqs = msg.GroupBy(ch => ch)
            .ToDictionary(g => g.Key, g => g.Count());

        var forest = new HeapForest();
        /* За всеки символ с ненулева честота на срещане се създава тривиално дърво */
        foreach(var ch in freqs.Keys.OrderBy(ch => ch))
        {
            forest.Add(new Tree { Char = ch, Weight = freqs[ch] });
        }

        while (forest.Count > 1)
        {
            Tree minTree1 = forest.GetMin(); /* Намиране на двата най-редки върха */
            Tree minTree2 = forest.GetMin();

            /* Създаване на нов възел - обединение на двата най-редки */
            var tree = new Tree { Left = minTree1, Right = minTree2,
                                  Weight = minTree1.Weight + minTree2.Weight };
            forest.Add(tree);
        }
        return forest.GetMin();
    }