这是一个不使用 LINQ 的解决方案,以防您想习惯数组和 for 循环:
// Determine the number of partitions.
int parts = currTermPairs.Length < 10 ? currTermPairs.Length : 10;
// Create the result array and determine the average length of the partitions.
var result = new string[parts][];
double avgLength = (double)currTermPairs.Length / parts;
double processedLength = 0.0;
int currentStart = 0;
for (int i = 0; i < parts; i++) {
processedLength += avgLength;
int currentEnd = (int)Math.Round(processedLength);
int partLength = currentEnd - currentStart;
result[i] = new string[partLength];
Array.Copy(currTermPairs, currentStart, result[i], 0, partLength);
currentStart = currentEnd;
}
return result;
项目的总数可能不能被 10 整除。问题是如何分配不同长度的部分。在这里,我尝试将它们均匀分布。注意铸造(double)currTermPairs.Length
。为了获得浮点除法而不是整数除法,这是必要的。
这里有一个小测试方法:
const int N = 35;
var arr = new string[N];
for (int i = 0; i < N; i++) {
arr[i] = i.ToString("00");
}
var result = new PatrtitioningArray().SplitInto10(arr);
for (int i = 0; i < result.Length; i++) {
Console.Write("{0}: ", i);
for (int k = 0; k < result[i].Length; k++) {
Console.Write("{0}, ", result[i][k]);
}
Console.WriteLine();
}
它的输出是(有 35 个元素):
0: 00, 01, 02, 03,
1: 04, 05, 06,
2: 07, 08, 09,
3: 10, 11, 12, 13,
4: 14, 15, 16, 17,
5: 18, 19, 20,
6: 21, 22, 23,
7: 24, 25, 26, 27,
8: 28, 29, 30, 31,
9: 32, 33, 34,