December 22, 2024

Answer to Collections Q11

 

This requires the default sort mechanism to be overridden. The class message sortBlock: will return an instance of the class with the required mechanism in place. Rather than predecessor and successor (as in the course text) I have used mountain1 and mountain2 for the block arguments. Try and use names (variables) that help you understand the kind of objects you are accessing. Instances of Mountain are being added and sorted by accessing and comparing their height instance variable. To achieve this, the height getter message is sent to each Mountain object.

mountainsOfTheWorld := SortedCollection sortBlock:
    [:mountain1 :mountain2|
        mountain1 height >= mountain2 height
    ].
arrayOfMountains do:
    [: eachSet | eachSet do:
       [: mountain | mountainsOfTheWorld
                              add: mountain
       ]
    ]

Or the final line can be replaced with:

1 to: 3 do:
    [:index | Dialog warn:
                (mountainsOfTheWorld at: index)
    ]

Note that if you wanted to display the names of each of the first three mountains, as in Q10, you need to send the name getter message to each of the stored Mountain objects.

mountainsOfTheWorld keysAndValuesDo:
    [: index :mountain | (index<= 3)
       ifTrue: [Dialog warn: mountain name]
    ]

Or

1 to: 3 do: [:index | Dialog warn:
   (mountainsOfTheWorld at: index)name ]

 

Back to « Collection Questions 2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page