Huffman

Status
Niet open voor verdere reacties.

jangge

Gebruiker
Lid geworden
16 jan 2013
Berichten
15
Hoi,

Ik zit met een error met mijn Huffman alghoritme

bij me program.cs zegt dat die 2 argumenten verwacht maar die geef ik toch ook een char voor de key en een int voor de value, iemand enig idee?

Error: IDictionary counts = new Dictionary<char, int>(); ->

type 'System.Collections.Generic.IDictionary<TKey,TValue>' requires 2 type arguments E:\Huffman Final\Huffmana\Huffmana\Program.cs

Code:
//////////////////////////////////program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Huffmana
{
    class Program
    {
        static void Main(string[] args)
        {
            IDictionary counts = new Dictionary<char, int>();
            //types of keys = char
            //types of values = int
            //van dictonary 


            //character op eerste plaatst
            //frequency in een int op tweede plaats
            //plaatst string in dictonary 

            // ac bca ba z 
            counts.Add(' ', 3);
            counts.Add('b', 2);
            counts.Add('a', 3);
            counts.Add('c', 2);
            counts.Add('z', 1);
            counts.Add('\n', 1);
            HuffmanTree tree = new HuffmanTree(counts);
            IDictionary<char, string> encodings = tree.CreateEncodings();

            foreach (KeyValuePair<char, string> kvp in encodings)
            {
                Console.WriteLine((kvp.Key == '\n' ? "EOF" : kvp.Key.ToString()) + ":\t" + kvp.Value);
            }

            Console.ReadLine();
        }
    }
}
//////////////////////////////////PriorityQueue.cs
namespace Huffmana
{
    class PriorityQueue<T>
    {
        private readonly SortedDictionary<int, Queue<T>> _SortedDictionary = new SortedDictionary<int, Queue<T>>();

        public int Count { get; set; }
        public void Enqueue (T item, int priority)
        {
            ++Count;
            if (!_SortedDictionary.ContainsKey(priority)) _SortedDictionary
                [priority] = new Queue<T>();
            _SortedDictionary[priority].Enqueue(item);
        }
        public T Dequeue()
            {
            --Count;
            var item = _SortedDictionary.First();
            if (item.Value.Count == 1) _SortedDictionary.Remove(item.Key);
            return item.Value.Dequeue();
            }
        }
    }

//////////////////////////////////HuffmanNode.cs

namespace Huffmana
{
    class HuffmanNode
    {
        //create node
        public HuffmanNode Parent   { get; set; }
        public HuffmanNode Left     { get; set; }
        public HuffmanNode Right    { get; set; }
        public char Value           { get; set; }
        public int Count            { get; set; } 
    }
}

//////////////////////////////////HuffmanNode.cs
namespace Huffmana
{
    class HuffmanTree
    {
         
        private readonly HuffmanNode _root;

        public HuffmanTree(IEnumerable<KeyValuePair<char, int>> counts)
        {
            var priorityQueue = new PriorityQueue<HuffmanNode>();

            foreach(KeyValuePair<char, int> kvp in counts)
            {
                priorityQueue.Enqueue(new HuffmanNode {Value = kvp.Key, Count = kvp.Value}, kvp.Value);
            }

            while(priorityQueue.Count > 1)
            {
                HuffmanNode n1 = priorityQueue.Dequeue();
                HuffmanNode n2 = priorityQueue.Dequeue();
                var n3 = new HuffmanNode {Left = n1, Right = n2, Count = n1.Count + n2.Count};
                n1.Parent = n3;
                n2.Parent = n3;
                priorityQueue.Enqueue(n3, n3.Count);
            }

            _root = priorityQueue.Dequeue();
        }

        public IDictionary<char, string> CreateEncodings()
        {
            var encodings = new Dictionary<char, string>();
            Encode(_root, "", encodings);
            return encodings;
        }

        private void Encode(HuffmanNode node, string path, IDictionary<char, string> encodings)
        {
            if (node.Left != null)
            {
                Encode(node.Left, path + "0", encodings);
                Encode(node.Right, path + "1", encodings);
            } else
            {
                encodings.Add(node.Value, path);    
            }
        }
    }
}
 
Als ik alle voorbeelden volg, lijkt het me dat:
IDictionary counts = new Dictionary<char, int>();

zou kunnen/moeten zijn:

IDictionary<char, int> counts = new Dictionary<char, int>();

Ik ben geen c-sharp programmeur, maar misschien is bovenstaande de oplossing.

Tijs.
 
Je kunt gewoon bij de constructor:
Code:
public HuffmanTree(IEnumerable<KeyValuePair<char, int>> counts)

een IDictionary geven
Code:
public HuffmanTree(IDictionary  counts)
 
Heey Blooshed,

Ik heb een vraag zou je me kunnen helpen om met deze code een applicatie te maken met een simpel form waar een user een .txt bestand kan invoeren en deze kan zippen d.m.v huffman algoritme ik heb deze code al klaar als console applicatie
waarin ook de frequentie etc word bepaald.

Maar ik krijg het niet voor elkaar in een form.

Ik wil je ervoor betalen:)

heb je msn etc?

Ik hoor het wel jannge
 
Ik bedoel zoiets.

http://i48.tinypic.com/332xxyd.png

Mocht je interesse hebben dan hoor ik het wel

de code voor mijn console application:

Code:
/////////////////////////program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HuffmanTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Encode";
            HuffmanTree huffmanTree = new HuffmanTree();

            // Build the Huffman tree
            huffmanTree.Build(input);

            // Encode
            BitArray encoded = huffmanTree.Encode(input);

            Console.Write("Encoded: ");
            foreach (bool bit in encoded)
            {
                Console.Write((bit ? 1 : 0) + "");
            }
            Console.WriteLine();

            // Decode
            string decoded = huffmanTree.Decode(encoded);

            Console.WriteLine("Decoded: " + decoded);
  

            Console.ReadLine();
        }
    }
}

/////////////////////////node.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HuffmanTest
{
    class Node
    {
        public char Symbool { get; set; }
        public int Frequency { get; set; }
        public Node Right { get; set; }
        public Node Left { get; set; }

        public List<bool> Check(char symbol, List<bool> data)
        {
            // Leaf
            if (Right == null && Left == null)
            {
                if (symbol.Equals(this.Symbool))
                {
                    return data;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                List<bool> left = null;
                List<bool> right = null;

                if (Left != null)
                {
                    List<bool> leftPath = new List<bool>();
                    leftPath.AddRange(data);
                    leftPath.Add(false);

                    left = Left.Check(symbol, leftPath);
                }

                if (Right != null)
                {
                    List<bool> rightPath = new List<bool>();
                    rightPath.AddRange(data);
                    rightPath.Add(true);
                    right = Right.Check(symbol, rightPath);
                }

                if (left != null)
                {
                    return left;
                }
                else
                {
                    return right;
                }
            }
        }
    }
}



////////////////////////HuffmanTree.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HuffmanTest
{
    class HuffmanTree
    {
        private List<Node> nodes = new List<Node>();
        public Node Root { get; set; }
        public Dictionary<char, int> Frequencies = new Dictionary<char, int>();

        public void Build(string source)
        {
            for (int i = 0; i < source.Length; i++)
            {
                if (!Frequencies.ContainsKey(source[i]))
                {
                    Frequencies.Add(source[i], 0);
                }

                Frequencies[source[i]]++;
            }

            foreach (KeyValuePair<char, int> symbol in Frequencies)
            {
                nodes.Add(new Node() { Symbool = symbol.Key, Frequency = symbol.Value });
            }

            while (nodes.Count > 1)
            {
                List<Node> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList<Node>();

                if (orderedNodes.Count >= 2)
                {
                    // Take first two items
                    List<Node> taken = orderedNodes.Take(2).ToList<Node>();

                    // Create a parent node by combining the frequencies
                    Node parent = new Node()
                    {
                        Symbool = '*',
                        Frequency = taken[0].Frequency + taken[1].Frequency,
                        Left = taken[0],
                        Right = taken[1]
                    };

                    nodes.Remove(taken[0]);
                    nodes.Remove(taken[1]);
                    nodes.Add(parent);
                }

                this.Root = nodes.FirstOrDefault();

            }

        }
        public BitArray Encode(string source)
    
        {
            List<bool> encodedSource = new List<bool>();

            for (int i = 0; i < source.Length; i++)
            {
                List<bool> encodedSymbol = this.Root.Check(source[i], new List<bool>());
                encodedSource.AddRange(encodedSymbol);
            }

            BitArray bits = new BitArray(encodedSource.ToArray());

            return bits;
        }

        public string Decode(BitArray bits)
        {
            Node current = this.Root;
            string decoded = "";

            foreach (bool bit in bits)
            {
                if (bit)
                {
                    if (current.Right != null)
                    {
                        current = current.Right;
                    }
                }
                else
                {
                    if (current.Left != null)
                    {
                        current = current.Left;
                    }
                }

                if (IsLeaf(current))
                {
                    decoded += current.Symbool;
                    current = this.Root;
                }
            }

            return decoded;
        }

        public bool IsLeaf(Node node)
        {
            return (node.Left == null && node.Right == null);
        }

    }
}
 
Ik zal straks eens kijken, als je de code al werkend hebt zal dit geen probleem zijn. Betalen is niet nodig :P
 
Op de foto ben ik 2 buttons vergeten open file, en voor opslag locatie:p
 
Ik heb even gekeken maar zonder de orginele data (non encoded) werkt de 'Decode' method niet? :P
En bij .Build -> .Encode werkt het alleen als je de string die je wilt encoden gebruikt?


Ik dacht dat je gewoon niet precies wist hoe je dingen in forms moest doen.
 
Hoe bedoel je dat precies.

Je hebt een encoded string bvb: water
deze decode je en krijg je de binaire code ervan: 1010100101 (b.v.b.)
deze binaire code zet die weer om in tekst: water
Zonder die string kan die niks nee, wat bedoel je precies:P
 
Weet je dan misschien hoe je op een form met 2 Textboxen encode/decode krijgt waar ik dan "water" in kan voeren en in de decode textbox de binaire code krijg, en andersom. Deze twee methodes heb ik nu in een console application waarbij een vooraf een string is gegeven maar ik wil de gebruiker graag deze string laten invoeren.

in ieder geval toch bedankt voor de moeite;)
 
Dit is wat ik even had gemaakt om te testen
288mb1v.png


http://dl.dropbox.com/u/63676419/encoding_vs12.zip
Ik denk dat het voorbeeld form win8 was dus hoop ik dat je vs2012 hebt :P
 
Vervelend, ik heb 2010, kan ik geen compatibility pack downloaden of zo, of kan jij hem downgraden?:P
Anders download ik wel even de 2012 versie.
 
Laatst bewerkt door een moderator:
Heb even geprobeerd, je kunt gewoon de bestanden naar de solution explorer slepen vanuit de map. Werk goed genoeg bij deze kleine projecten.
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan