More data structures
Lists and dictionaries are not always the best tool. This lesson shows five collections of .NET that keep order for you or save memory — a priority queue, a sorted set, a sorted dictionary, a linked list and a bit array — and when each one is the right choice.
What you will learn#
PriorityQueue: always the most urgent item first,SortedSet: no duplicates and always sorted,SortedDictionary: keys in order,LinkedList: cheap changes at both ends and next to a node,BitArray: a million yes/no values in 125 KB, with logic operations,- the Ring words that start with
@(@Get,@And,@Or).
The tutorial Collections and LINQ used List and Dictionary, and the tutorial Collections for many threads the collections for many threads.
The program#
# more data structures - PriorityQueue, SortedSet, SortedDictionary, LinkedList and BitArray
load "dotnet.ring"
using {
"System"
"System.Collections"
"System.Collections.Generic"
}
func main
cInt = "System.Int32"
cText = "System.String"
# 1. PriorityQueue<element, priority>: Dequeue always gives the element with the SMALLEST priority, whatever the order of Enqueue.
oTasks = new PriorityQueue([ :typeArguments = [cText,cInt] ])
oTasks.Enqueue("write the report",3)
oTasks.Enqueue("fix the server",1)
oTasks.Enqueue("answer the mail",5)
oTasks.Enqueue("call the customer",2)
? "1. " + oTasks.Count + " tasks, most urgent first:"
while oTasks.Count > 0
? " " + oTasks.Dequeue()
end
# 2. SortedSet: no duplicates, always sorted. Add answers false for a value that is already there. Min and Max are ready.
oSet = new SortedSet([ :typeArguments = [cInt] ])
for n in [42,7,19,7,3,42,100]
oSet.Add(n)
next
? nl + "2. sorted set of 7 numbers with duplicates: " + oSet.Count + " kept, from " + oSet.Min + " to " + oSet.Max
? " in order: " + list2str2(oSet.toList())
? " Contains(19): " + oSet.Contains(19) + ", Contains(20): " + oSet.Contains(20)
# 3. SortedDictionary: keys stay in order, so a loop over it is alphabetical
oDict = new SortedDictionary([ :typeArguments = [cText,cInt] ])
for cName in ["pear","apple","fig","banana"]
oDict.Add(cName,len(cName))
next
cKeys = ""
aKeys = oDict.Keys.toList()
for cKey in aKeys
cKeys += cKey + " "
next
? nl + "3. sorted dictionary, keys in order: " + cKeys
# 4. LinkedList: items are linked to their neighbors. Adding or removing at either end, or next to a known node, is quick.
oList = new LinkedList([ :typeArguments = [cText] ])
oList.AddLast("b")
oList.AddLast("c")
oList.AddFirst("a")
oNodeB = oList.First.@Next
oList.AddAfter(oNodeB,"b2")
? nl + "4. linked list: " + list2str2(oList.toList()) + " (first = " + oList.First.Value + ", last = " + oList.Last.Value + ")"
oList.Remove("b")
? " after Remove(b): " + list2str2(oList.toList())
# 5. BitArray: one bit for each item, so a million yes/no values take 125 KB. Set, Get and the logic methods And, Or, Xor, Not.
# (Get, And and Or are Ring words, so their names start with @. And and Or change the array they are called on.)
oBits = new BitArray(10)
oBits.Set(1,True)
oBits.Set(3,True)
oBits.Set(4,True)
oOther = new BitArray(10)
oOther.Set(3,True)
oOther.Set(9,True)
? nl + "5. bits: " + bitText(oBits)
? " other: " + bitText(oOther)
? " AND: " + bitText(copyBits(oBits).@And(oOther))
? " OR: " + bitText(copyBits(oBits).@Or(oOther))
func copyBits oBits
return new BitArray(oBits)
func bitText oBits
cText = ""
for i = 0 to oBits.Length - 1
if oBits.@Get(i) cText += "1" else cText += "0" ok
next
return cText
func list2str2 aList
cText = ""
for item in aList
cText += "" + item + " "
next
return cText1. 4 tasks, most urgent first:
fix the server
call the customer
write the report
answer the mail
2. sorted set of 7 numbers with duplicates: 5 kept, from 3 to 100
in order: 3 7 19 42 100
Contains(19): 1, Contains(20): 0
3. sorted dictionary, keys in order: apple banana fig pear
4. linked list: a b b2 c (first = a, last = c)
after Remove(b): a b2 c
5. bits: 0101100000
other: 0001000001
AND: 0001000000
OR: 0101100001This program uses a few generic functions (dnNewGeneric, callMethod, getProp) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Closed generic types#
All of them but BitArray are generic: dnNewGeneric(type, [type arguments], [constructor values]) makes a closed type such as PriorityQueue<string, int>. Most have no Ring class, so those objects are used in the plain style: callMethod("Add", [value]), getProp("Count"), and toList() to copy a collection into a Ring list (Core concepts).
PriorityQueue#
Enqueue(element, priority) adds; Dequeue() returns the element with the smallest priority number, whatever the order of adding. It is the right tool for a to-do list by urgency, for events by time, and for algorithms such as the shortest path. It does not keep the whole list sorted (it only knows the next item), so it is faster than sorting again and again.
SortedSet#
A set holds each value once: adding 42 twice keeps one 42. A SortedSet also keeps the values in order, so Min, Max and a loop come for free, and Contains is fast even for a million items.
SortedDictionary#
Same as a Dictionary, with the keys in order. The loop over Keys gives apple banana fig pear. Use it when the order matters for display; use the plain Dictionary when only the speed of the lookup matters.
LinkedList#
Each item is a node that knows its neighbors (Next, Previous). AddFirst, AddLast and AddAfter(node, value) do not move other items, and Remove of a known node is quick. The price: no access by number. Take it when you add or remove in the middle of a long list all the time, for example an undo list or a play list.
BitArray#
One bit for each item. A million yes/no values (a sieve of primes, which seats are free, which files were seen) take 125 KB instead of megabytes. Set(index, value) and @Get(index) write and read one bit (Get is a Ring word, so the name starts with @, see below); @And, @Or, Xor and @Not work on all the bits at once and change the array they are called on, so the program copies it first (new BitArray(bits)). In the output, AND has only the bit that both arrays have and OR has the bits of either.
Ring accepts most of its own words as method names after a dot (Set, From, To, Step, In, On, Off), but not Get, And and Or (a statement get x reads input, and and, or are the operators of conditions). A .NET method with one of those names has a name that starts with @ in the generated class: oBits.@Get(3), oBits.@And(oOther).
What you learned#
- five collections and what each one is for,
- the plain style (
callMethod,getProp,toList) for closed generic types, BitArrayoperations change their own array,- the few Ring words that start with
@.
Exercises#
- Make a task list with
PriorityQueuewhere two tasks have the same priority: in which order do they come out? (Do not rely on it.) - Use a
SortedSetof words to print the words of a text without duplicates in alphabetical order. - Find all primes below 1000 with a
BitArray(the sieve of Eratosthenes). - Build an undo list of the last 5 actions with a
LinkedList.