Home > Net >  Updating an item of a matrix in Dart has different results dependant on the method of initialisation
Updating an item of a matrix in Dart has different results dependant on the method of initialisation

Time:10-16

The following code demonstrates a problem that I have come across in a larger application.


    void probtest() {
        List<List<int>> mat1 = List.filled(3, List.filled(3, -1));
        List<List<int>> mat2 = [
          [-1, -1, -1],
          [-1, -1, -1],
          [-1, -1, -1]
        ];
    
        print(mat1);
        print(mat2);
        mat1[0][0] = 1;
        mat2[0][0] = 1;
        print(mat1);
        print(mat2);
    }

The output of this (formatted for clarity) is:

[
 [-1,-1,-1],
 [-1,-1,-1],
 [-1,-1,-1]
]

[
 [-1,-1,-1],
 [-1,-1,-1],
 [-1,-1,-1]
]

[
 [1,-1,-1],
 [1,-1,-1],
 [1,-1,-1]
]

[
 [1,-1,-1],
 [-1,-1,-1],
 [-1,-1,-1]
]

As you can see creating a matrix using List.filled and then attempting to update the value at [0][0] seems to update the entire 0th column. If the matrix is created using literals then updating [0][0] just updates the [0][0] item - this is the result I want and expected.

2 questions:

  1. Why is it different?
  2. Is there a way to initialise the list without manually writing out the literals so that I am able to update the individual items as for mat2. I need to do it for a much larger matrix.

CodePudding user response:

The code

List<List<int>> mat1 = List.filled(3, List.filled(3, -1));

creats one List.filled(3, -1), then creates another list with that same list as all three elements.

When you update the one list, it shows everywhere that list is referenced.

What you should do instead is:

List<List<int>> mat1 = List.generate(3, (_) => List.filled(3, -1));

This creates a new list for each element of the outer list, instead of reusing the same list.

  • Related