Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

## SortedCollection - Andrew Cray

Some Smalltalk Help

Well you have ventured to the individual case site for some help and good for you. I had no idea this could be such a useful resource, and after looking over some of the topics it certainly couldn’t have hurt to read these things.

The Problem
The problem I will be talking about dealt with an issue on our final project. For a list of items, we had to implement four different sale policies: First in First Out (FIFO), Last in First Out (LIFO), cheapest item bought first (CIF), and most expensive item bought first (EIF). It’s easy to recognize to recognize that FIFO could be a queue and LIFO could be a stack, but what about CIF and EIF. Before my team ventured any farther into thinking about this problem, we realized we were creating a bigger problem. Implementing the sale policy would require four different data structures, which could potentially take up a lot of space. We would have to keep track of and update each one accordingly and this seemed like creating a big mess. Lucky for us our instructor Mr. Waters had introduced us to a nice data structure: the Sorted Collection.

The Sorted Collection
The Sorted Collection is a useful data structure because it will keep the objects sorted in whatever way you wish to implement. The way to do this is changing the Sorted Collections sort block. For FIFO and LIFO we added a count to each item and incremented the count by one for each item added. So FIFO would sort lowest count first. LIFO would sort highest count. CIF and EIF would sort the buy price the same respectively.

In Initialize – This is the code to initialize a SortedCollection with a sort block
items := SortedCollection sortBlock:[:a :b | (a buyPrice asNumber) (b buyPrice asNumber).].

SortPolicy Method – 1=CIF,2=EIF, 3=FIFO, 4=LIFO
sortPolicy: anInteger

anInteger = 1 ifTrue: [ items sortBlock:[:a :b | (a buyPrice asNumber) (b buyPrice asNumber).].].
anInteger = 2 ifTrue: [ items sortBlock:[:a :b | (a buyPrice asNumber) > (b buyPrice asNumber).].].
anInteger = 3 ifTrue: [ items sortBlock:[:a :b | (a count asNumber) (b count asNumber).].].
anInteger = 4 ifTrue: [ items sortBlock:[:a :b | (a count asNumber) > (b count asNumber).].].