Two dimensional matrix-like data type using lists and/or mutable lists
https://softwareengineering.stackexchange.com/questions/274760
Pergunta
I am trying to think of an implementation of a two dimensional matrix-like data type.
Normally I would take an array of arrays but I'm bound to a relatively low language level which only provides lists and mutable lists, because this is part of (but not an exercise itself, I could simply use an inefficient solution) a software project at university. In this, we are only allowed to use a specific language level.
So of cause I could take a list of mutable lists and, in search of an item in row n and column m, get the m-th mutable list and go throught it until position n. But isn't there a better solution than going through the whole list?
Solução
Since you need constant size, and access elements by their indexes, I'd say go with 1-dimensional array of WIDTH*HEIGHT
size. You can just translate indexes like matrix[x+y*WIDTH]
or build a wrapper class to do it like matrix.get(x, y)
- that way you don't have to track width, and you can add boundary checks.
Access by index will have a constant time (O(1)
) performance.