这不是使用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,
已知: _____预计:______ –
我不明白吗? 如果你问我给出了什么和期望什么, 你可以在方法中看到一个字符串数组,并且期望它被等分为10个不同部分 – Ramie
@Ramie:我们不知道什么您的要求。某些给定输入的预期输出是什么? – Patrick