indexOf method

dynamic indexOf(
  1. dynamic element, {
  2. bool findAll = false,
})

Returns the indices of occurrences of the specified element in the matrix. If findAll is set to true, returns a List<List<int>> of all indices where the element was found. If findAll is false or not provided, returns a List<int> of the first occurrence. Returns null if the element is not found.

element: The element to search for in the matrix. findAll: Whether to find all occurrences of the element.

Example:

var m = Matrix([[1, 2, 1], [3, 1, 4], [1, 5, 6]]);
var singleIndex = m.indicesOf(1);
print(singleIndex);
// Output: [0, 0]
var allIndices = m.indicesOf(1, findAll: true);
print(allIndices);
// Output: [[0, 0], [0, 2], [1, 1], [2, 0]]

Implementation

dynamic indexOf(dynamic element, {bool findAll = false}) {
  List<List<int>> allIndices = [];

  for (int i = 0; i < rowCount; i++) {
    for (int j = 0; j < _data[i].length; j++) {
      if (_data[i][j] == element) {
        if (!findAll) {
          return [i, j];
        }
        allIndices.add([i, j]);
      }
    }
  }

  if (findAll) {
    return allIndices.isNotEmpty ? allIndices : null;
  }

  return null;
}