reshape<T> method

List reshape<T>(
  1. List<int> shape
)

Reshape list to a another shape

T is the type of elements in list

Returns List

Throws ArgumentError if number of elements for shape mismatch with current number of elements in list

Implementation

List reshape<T>(List<int> shape) {
  var dims = shape.length;
  var numElements = 1;
  for (var i = 0; i < dims; i++) {
    numElements *= shape[i];
  }

  if (numElements != computeNumElements) {
    throw ArgumentError(
        'Total elements mismatch expected: $numElements elements for shape: $shape but found $computeNumElements');
  }

  if (dims <= 5) {
    switch (dims) {
      case 2:
        return _reshape2<T>(shape);
      case 3:
        return _reshape3<T>(shape);
      case 4:
        return _reshape4<T>(shape);
      case 5:
        return _reshape5<T>(shape);
    }
  }

  var reshapedList = flatten<dynamic>();
  for (var i = dims - 1; i > 0; i--) {
    var temp = [];
    for (var start = 0;
        start + shape[i] <= reshapedList.length;
        start += shape[i]) {
      temp.add(reshapedList.sublist(start, start + shape[i]));
    }
    reshapedList = temp;
  }
  return reshapedList;
}