Question

I am new to Smalltalk and am taking a class init currently. One of the problems we were assigned requires creating a new Class "HeavyMatrix", which is called like this —

aMatrix := HeavyMatrix new.

Notice that there is no initial size assignment. The size is supposed to be undetermined upon creation. Then, the class adds values to the matrix with the following method —

aMatrix setRow:1 column:2 value:7.

All the values in the matrix which have not been declared in this way default to 0. The new Class HeavyMatrix is not supposed to subclass anything other than Object (i.e. not Matrix or Array). Can any Smalltalkers help me out? There are some other methods the class must contain but I think I can figure everything else once I am able to initialize the class. Thanks!

Was it helpful?

Solution

What can I suggest you… First of all you can just used ordered collections and inside setRow:column:value: if current column size is smaller that required than add what is missing an OrderedCollection instances. The same with desired row size (add 0s). The implementation will be something like this:

initialize
    rows := OrderedCollection new

setRow: aRow column: aColumn value: aValue
    | row |
    rows size < aRow ifTrue: [
        (aRow - rows size) timesRepeat: [rows add: OrderedCollection new]].
    row := rows at: aRow.
    row size < aColumn ifTrue: [
        (aColumn - row size) timesRepeat: [row add: 0]].
    row at: aColumn put: aValue

getRow: aRow column: aColumn
    aRow <= rows size ifTrue: [
        |row|
        row := rows at: aRow.
        aColumn <= rows size ifTrue: [^ row at: aColumn]].
    ^ 0 

But more efficient way to do that is to implement a sparse matrix I think. You have a lot of structures described at wiki. Please note, that this matrices are only efficient when you have a low amount of elements compering to the size of the matrix itself. But if you'll check even the easiest implementation, like storing a coords-value data in dictionary, than it will suite you a lot:

initialize
    dict := Dictionary new

setRow: aRow column: aColumn value: aValue
    dict at: aRow@aColumn put: aValue

getRow: aRow column: aColumn
    dict at: aRow@aColumn ifAbsent: [0] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top