0

I am learning Dart. I have simple JS code that split array to number of parts like:

2: [1,2,4,6,8], [14,17,18,19]
3: [1,2,4], [6,8,14], [17,18,19]
4: [1,2], [4,6], [8,14], [17,18,19]

Could anybody help me with converting follow code to Dart?

function split(arr, numParts) {
  const partSize = arr.length / numParts | 0;

  return Array
    .from({ length: numParts }, (n, i) => i * partSize)
    .map((n, i, a) => arr.slice(n, a[i + 1]));
}

console.log(split([1,2,4,6,8,14,17,18,19,20], 3)); // [1,2,4] [6,8,14] [17,18,19,20]

I was able to convert only few first lines:

split(List<int> arr, int numParts) {
  var partSize = arr.length / numParts;

}

But need help with rest part.

julemand101
  • 28,470
  • 5
  • 52
  • 48
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145

1 Answers1

1

Something like this? I am not really sure this is how you want to share the numbers between the groups:

void main() {
  for (var i = 1; i <= 10; i++) {
    print('${i.toString().padLeft(2)} | ${split([1, 3, 4, 5, 6, 12, 1, 5, 6, 1], i)}');
  }
  //  1 | [[1, 3, 4, 5, 6, 12, 1, 5, 6, 1]]
  //  2 | [[1, 3, 4, 5, 6], [12, 1, 5, 6, 1]]
  //  3 | [[1, 3, 4], [5, 6, 12], [1, 5, 6, 1]]
  //  4 | [[1, 3], [4, 5], [6, 12], [1, 5, 6, 1]]
  //  5 | [[1, 3], [4, 5], [6, 12], [1, 5], [6, 1]]
  //  6 | [[1], [3], [4], [5], [6], [12, 1, 5, 6, 1]]
  //  7 | [[1], [3], [4], [5], [6], [12], [1, 5, 6, 1]]
  //  8 | [[1], [3], [4], [5], [6], [12], [1], [5, 6, 1]]
  //  9 | [[1], [3], [4], [5], [6], [12], [1], [5], [6, 1]]
  // 10 | [[1], [3], [4], [5], [6], [12], [1], [5], [6], [1]]
}

List<List<T>> split<T>(List<T> list, int parts) {
  final partSize = list.length ~/ parts;

  return [
    for (var i = 0; i < parts; i++)
      if (i + 1 < parts)
        list.sublist(i * partSize, (i + 1) * partSize)
      else
        list.sublist(i * partSize)
  ];
}

Also, this solution is going to behave a little funny if you have more parts than values:

11 | [[], [], [], [], [], [], [], [], [], [], [1, 3, 4, 5, 6, 12, 1, 5, 6, 1]]
12 | [[], [], [], [], [], [], [], [], [], [], [], [1, 3, 4, 5, 6, 12, 1, 5, 6, 1]]
13 | [[], [], [], [], [], [], [], [], [], [], [], [], [1, 3, 4, 5, 6, 12, 1, 5, 6, 1]]
julemand101
  • 28,470
  • 5
  • 52
  • 48