I'm building a simple app that represents some matrix, where nodes are added quite often. Currently I have following code for adding a new node:
let mut new_edges = Array2::default((position + 1, position + 1));
for i in 0..position {
for j in 0..position {
new_edges[[i, j]] = self.edges[[i, j]]
}
}
self.edges = new_edges;
So it basically just copies everything on each node insert.
Much more efficient way were just add new items in the end of single-dimension vector and treat it as 2D matrix. For example, it could be vector of length 9
which represents following matrix:
0|1|8|
_| | |
3 2|7|
___ |
4 5 6|
_____
So you see. We hold indices of underlying vector in snake order. When we want to resize it we don't move anything but just add new 2n-1
nodes to the end. Adding 4th column and row would lead to adding 7 nodes in following manner:
0 |1 |8 |9 |
__| | | |
3 2 |7 |10|
_____| | |
4 5 6 |11|
________| |
15 14 13 12|
___________|
The problem with this approach that I can't express it mathematically, i.e. in this case matrix[[2,2]]
is stored in vec on index 6
, matrix[[2,0]]
is stored on the index 8
and matrix[[0,1]]
is stored on index 3
.
Am I doing the right thing and if the answer is yes, how could 1d to 2d translation be performed?