DATA STRUCTURES AND ALGORITHMS USING VISUAL BASIC.NET phần 6 pps

42 392 0
DATA STRUCTURES AND ALGORITHMS USING VISUAL BASIC.NET phần 6 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 CHAPTER 9 Building Dictionaries: The DictionaryBase Class and the SortedList Class A dictionary is a data structure that stores data as a key–value pair. The DictionaryBase class is used as an abstract class to implement different data structures that all store data as key–value pairs. These data structures can be hash tables, linked lists, or some other data structure type. In this chapter, we examine how to create basic dictionaries and how to use the inherited methods of the DictionaryBase class. We will use these techniques later when we explore more specialized data structures. One example of a dictionary-based data structure is the SortedList. This class stores key–value pairs in sorted order based on the key. It is an interesting data structure because you can also access the values stored in the structure by referring to the value’s index position in the data structure, which makes the structure behave somewhat like an array. We examine the behavior of the SortedList class at the end of the chapter. 200 P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 The DictionaryBase Class 201 THE DICTIONARYBASE CLASS You can think of a dictionary data structure as a computerized word dictionary. The word you are looking up is the key, and the definition of the word is the value. The DictionaryBase class is an abstract (MustInherit) class that is used as a basis for specialized dictionary implementations. The key–value pairs stored in a dictionary are actually stored as Dictio- naryEntry objects. The DictionaryEntry structure provides two fields, one for the key and one for the value. The only two properties (or methods) we’re interested in with this structure are the Key and Value properties. These meth- ods return the values stored when a key–value pair is entered into a dictionary. We explore DictionaryEntry objects later in the chapter. Internally, key–value pairs are stored in a hash table object called Inner- HashTable. We discuss hash tables in more detail in Chapter 12,sofor now just view it as an efficient data structure for storing key–value pairs. The DictionaryBase class actually implements an interface from the Sys- tem.Collections namespace, IDictionary. This interface actually forms the basis for many of the classes we’ll study later in this book, including the ListDictionary class and the Hashtable class. Fundamental DictionaryBase Class Methods and Properties When working with a dictionary object, there are several operations you want to perform. At a minimum, you need an Add method to add new data, an Item method to retrieve a value, a Remove method to remove a key–value pair, and a Clear method to clear the data structure of all data. Let’s begin the discussion of implementing a dictionary by looking at a simple example class. The following code shows the implementation of a class that stores names and IP addresses: Public Class IPAddresses Inherits DictionaryBase Public Sub New() MyBase.new() End Sub Public Sub Add(ByVal name As String, ByVal ip _ As String) P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 202 BUILDING DICTIONARIES MyBase.InnerHashtable.Add(name, ip) End Sub Public Function Item(ByVal name As String) As String Return CStr(MyBase.InnerHashtable.Item(name)) End Function Public Sub Remove(ByVal name As String) MyBase.InnerHashtable.Remove(name) End Sub End Class As you can see, these methods were very easy to build. The first method implemented is the constructor. This is a simple method that does noth- ing but call the default constructor for the base class. The Add method takes a name–IP address pair as arguments and passes them to the Add method of the InnerHashTable object, which is instantiated in the base class. The Item method is used to retrieve a value given a specific key. The key is passed to the corresponding Item method of the InnerHashTable object. The value stored with the associated key in the inner hash table is returned. Finally, the Remove method receives a key as an argument and passes the argument to the associated Remove method of the inner hash table. The method then removes both the key and its associated value from the hash table. There are two methods we can use without implementing them—Count and Clear. The Count method returns the number of DictionaryEntry objects stored in the inner hash table; Clear removes all the DictionaryEntry objects from the inner hash table. Let’s look at a program that utilizes these methods: Sub Main() Dim myIPs As New IPAddresses myIPs.Add("Mike", "192.155.12.1") myIPs.Add("David", "192.155.12.2") myIPs.Add("Bernica", "192.155.12.3") Console.WriteLine("There are"&myIPs.Count() & _ "IPaddresses.") P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 The DictionaryBase Class 203 Console.WriteLine("David's ip: " & _ myIPs.Item("David")) myIPs.Clear() Console.WriteLine("There are"&myIPs.Count() & _ "IPaddresses.") Console.Read() End Sub The output from this program looks like this: One modification we might want to make to the class is to overload the constructor so that we can load data into a dictionary from a file. Here’s the code for the new constructor, which you can just add into the IPAddresses class definition: Public Sub New(ByVal txtFile As String) MyBase.New() Dim line As String Dim words() As String Dim inFile As StreamReader inFile = File.OpenText(txtFile) While (inFile.Peek <> -1) line = inFile.ReadLine() words = line.Split(","c) Me.InnerHashtable.Add(words(0), words(1)) End While inFile.Close() End Sub P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 204 BUILDING DICTIONARIES Now here’s a new program to test the constructor: Sub Main() Dim myIPs As New IPAddresses(c: \ data \ ips.txt") Dim index As Integer For index=1To3 Console.WriteLine() Next Console.WriteLine("There are {0} IP addresses", _ myIPs.Count) Console.WriteLine("David's IP address: " & _ myIPs.Item("David")) Console.WriteLine("Bernica's IP address: " & _ myIPs.Item("Bernica")) Console.WriteLine("Mike's IP address: " & _ myIPs.Item("Mike")) Console.Read() End Sub The output this program is the following: Other DictionaryBase Methods There are two other methods that are members of the DictionaryBase class: CopyTo and GetEnumerator. We discuss these methods in this section. The CopyTo method copies the contents of a dictionary to a one- dimensional array. The array should be declared as a DictionaryEntry array, P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 The DictionaryBase Class 205 though you can declare it as Object and then use the CType function to convert the objects to DictionaryEntry. The following code fragment demonstrates how touse the CopyTo method: Dim myIPs As New IPAddresses("c: \ ips.txt") Dim ips((myIPs.Count-1) As DictionaryEntry myIPs.CopyTo(ips, 0) The formula used to size the array takes the number of elements in the dic- tionary and then subtracts one to account for a zero-based array. The CopyTo method takes two arguments: the array to copy to and the index position to start copying from. If you want to place the contents of a dictionary at the end of an existing array, for example, you would specify the upper bound of the array plus one as the second argument. Once we get the data from the dictionary into an array, we want to work with the contents of the array, or at least display the values. Here’s some code to do that: Dim index As Integer For index=0Toips.GetUpperBound(0) Console.WriteLine(ips(index)) Next The output from this code looks like this: Unfortunately, this is not what we want. The problem is that we’re storing the data in the array as DictionaryEntry objects, and that’s exactly what we see. If we use the ToString method Console.WriteLine(ips(index).ToString()) P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 206 BUILDING DICTIONARIES we get the same thing. To actually view the data in a DictionaryEntry ob- ject, we have to use either the Key property or the Value property, depend- ing on whether the object we’re querying holds key data or value data. So how do we know which is which? When the contents of the dictionary are copied to the array, the data get copied in key–value order. So the first object is a key, the second object is a value, the third object is a key, and so on. Now we can write a code fragment that allows us to actually see the data: Dim index As Integer For index=0Toips.GetUpperBound(0) Console.WriteLine(ips(index).Key) Console.WriteLine(ips(index).Value) Next The output looks like this: THE SORTEDLIST CLASS As we mentioned in the chapter’s introduction, a SortedList is a data structure that stores key–value pairs in sorted order based on the key. We can use this data structure when it is important for the keys to be sorted, such as in a standard word dictionary, where we expect the words in the dictionary to be sorted alphabetically. Later in the chapter we’ll also see how the class can be used to store a list of single, sorted values. P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 The SortedList Class 207 Using the SortedList Class We can use the SortedList class in much the same way we used the classes in the previous sections, since the SortedList class is but a specialization of the DictionaryBase class. To demonstrate this, the following code creates a SortedList object that contains three names and IP addresses: Dim myips As New SortedList myips.Add("Mike", "192.155.12.1") myips.Add("David", "192.155.12.2") myips.Add("Bernica", "192.155.12.3") The name is the key and the IP address is the stored value. We can retrieve the values by using the Item method with a key as the argument: Dim key As Object For Each key In myips.Keys Console.WriteLine("Name:"&key & Constants.vbTab & _ "IP: " & myips.Item(key)) Next This fragment produces the following output: Alternatively, we can also access this list by referencing the index numbers where these values (and keys) are stored internally in the arrays that actually store the data. Here’s how: Dim i As Integer Fori=0Tomyips.Count - 1 P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 208 BUILDING DICTIONARIES Console.WriteLine("Name:"&myips.GetKey(i) & _ Constants.vbTab & "IP: " & _ myips.GetByIndex(i)) Next This code fragment produces the exact same sorted list of names and IP addresses: A key–value pair can be removed from a SortedList by specifying either a key or an index number, as in the following code fragment, which demonstrates both removal methods: myips.Remove("David") myips.RemoveAt(1) If you want to use index-based access into a SortedList but don’t know the indexes where a particular key or value is stored, you can use the following methods to determine those values: Dim indexDavid As Integer = myips.GetIndexOfKey("David") Dim indexIPDavid As Integer = _ myips.GetIndexOfValue(myips.Item("David")) The SortedList class contains many other methods, and you are encouraged to explore them via VS.NET’s online documentation. SUMMARY The DictionaryBase class is an abstract class used to create custom dictionaries. A dictionary is a data structure that stores data in key–value pairs, using a P1: IWV 0521547652c09 CB820-McMillan-v1 April 21, 2005 17:41 Exercises 209 hash table (or sometimes a singly linked list) as the underlying data structure. The key–value pairs are stored as DictionaryEntry objects and you must use the Key and Value methods to retrieve the actual values in a DictionaryEntry object. The DictionaryBase class is often used when the programmer wants to create a strongly typed data structure. Normally, data added to a dictionary is stored as an Object type, but with a custom dictionary, the programmer can reduce the number of type conversions that must be performed, making the program more efficient and easier to read. The SortedList class is a particular type of Dictionary class, one that stores the key–value pairs in order sorted by the key. You can also retrieve the values stored in a SortedList by referencing the index number where the value is stored, much like you do with an array. EXERCISES 1. Using the implementation of the IPAddresses class developed in this chap- ter, devise a method that displays the IP addresses stored in the class in ascending order. Use the method in a program. 2. Write a program that stores names and phone numbers from a text file in a dictionary, with the name being the key. Write a method that does a reverse lookup, that is, finds a name given a phone number. Write a Windows application to test your implementation. 3. Using a dictionary, write a program that displays the number of occurrences of a word in a sentence. Display a list of all the words and the number of times they occur in the sentence. 4. Rewrite Exercise 3 to work with letters rather than words. 5. Rewrite Exercise 2 using the SortedList class. 6. The SortedList class is implemented using two internal arrays, one that stores the keys and one that stores the values. Create your own SortedList class implementation using this scheme. Your class should include all the methods discussed in this chapter. Use your class to solve the problem posed in Exercise 2. [...]... removed and go to that arraylist We then check to make sure the item is in the arraylist, and if it is, we remove it Here’s the code for a BucketHash class that includes a Hash function, an Add method, and a Remove method: Public Class BucketHash Private Const SIZE As Integer = 101 Private data( ) As ArrayList Public Sub New() Dim index As Integer ReDim data( SIZE) For index = 0 To SIZE - 1 2 16 HASHING AND. .. function Now let’s look at the distribution of the keys in the hash table using this new function: 214 HASHING AND THE HASHTABLE CLASS These keys are more evenly distributed though it’s hard to tell with such a small data set SEARCHING FOR DATA IN A HASH TABLE To search for data in a hash table, we need to compute the hash value of the key and then access that element in the array It is that simple Here’s...C HAPTER 10 Hashing and the Hashtable Class Hashing is a very common technique for storing data in such a way that the data can be inserted and retrieved very quickly Hashing uses a data structure called a hash table Although hash tables provide fast insertion, deletion, and retrieval, they perform poorly for operations that involve searching, such... two data items, we have a problem One solution to the collision problem is to implement the hash table using buckets A bucket is a simple data structure stored in a hash table element that can store multiple items In most implementations, this data structure is an array, but in our implementation we’ll make use of an arraylist, thereby precluding us from having to worry about running out of space and. .. String) Dim hash_value As Integer hash_value = Hash(item) If Not (data( hash_value).Contains(item)) Then data( hash_value).Add(item) End If End Sub Public Sub Remove(ByVal item As String) Dim hash_value As Integer hash_value = Hash(item) If (data( hash_value).Contains(item)) Then data( hash_value).Remove(item) End If End Sub End Class When using bucket hashing, you should keep the number of arraylist elements... create a new key–value pair using the Item method; the second line demonstrates that you can overwrite the current value associated with an existing key Retrieving the Keys and the Values Separately from a Hash Table The Hashtable class has two very useful methods for retrieving the keys and values separately from a hash table: Keys and Values These methods create 220 HASHING AND THE HASHTABLE CLASS an... computer begins following the instructions in a subprogram compiler,a program that translates a high-level program into machine code data, information in a form a computer can use database,a structured set of data Here’s how the program looks when it runs: 2 26 HASHING AND THE HASHTABLE CLASS If a word is entered that is not in the glossary, the Item method returns Nothing There is a test for Nothing... implementations of the data structure—object-based linked lists and array-based linked lists The chapter finishes up with several examples of how linked lists can be used for solving computer programming problems you may run across SHORTCOMINGS OF ARRAYS The array is the natural data structure to use when working with lists Arrays provide fast access to stored items and are easy to loop through And, of course,... Arrays provide fast access to stored items and are easy to loop through And, of course, the array is already part of the language and you don’t have to use extra memory and processing time using a user-defined data structure However, as we’ve seen, the array is not the perfect data structure Searching for an item in an unordered array can be slow because you might have to visit every element in the array... We’ll create a Node class and instantiate a Node object each time we add a node to the list The nodes in the list are connected via references to other nodes These references are set using methods created in a separate LinkedList class Let’s start by looking at the design of the Node class The Node Class A node is made up of two data members: Element, which stores the node’s data, and Link, which stores . different data structures that all store data as key–value pairs. These data structures can be hash tables, linked lists, or some other data structure type. In this chapter, we examine how to create basic. 18: 16 CHAPTER 10 Hashing and the Hashtable Class Hashing is a very common technique for storing data in such a way that the data can be inserted and retrieved very quickly. Hashing uses a data. time, unless of course the data item is somewhere close to the beginning of the array. P1: ICD 052154 765 2c10 CB820-McMillan-v1-c10 April 21, 2005 18: 16 Handling Collisions 215 HANDLING COLLISIONS When

Ngày đăng: 12/08/2014, 16:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan