如何将一个数分成偶数个组?
How do I divide a number into an even number of groups?
如果我得到一个数字,以及我需要将该数字分成多少组的数字,我如何将它分成尽可能接近偶数的块?
8 into 3 chunks -> 3, 3, 2
12 into 2 chunks -> 6, 6
9 into 2 chunks -> 4, 5
9 into 4 chunks -> 2, 2, 2, 3
11 into 5 chunks -> 2, 2, 2, 2, 3
这似乎或多或少有效:
int[] GetGroups(int number, int chunks) =>
Enumerable
.Range(0, chunks)
.Select(x => number / chunks + (number % chunks > x ? 1 : 0))
.ToArray();
var inputs = new[]
{
new { n = 8, c = 3, },
new { n = 12, c = 2, },
new { n = 9, c = 2, },
new { n = 9, c = 4, },
new { n = 11, c = 5, },
};
foreach (var input in inputs)
{
Console.WriteLine($"{input.n} into {input.c} chunks -> {String.Join(", ", GetGroups(input.n, input.c))}");
}
这给了我:
8 into 3 chunks -> 3, 3, 2
12 into 2 chunks -> 6, 6
9 into 2 chunks -> 5, 4
9 into 4 chunks -> 3, 2, 2, 2
11 into 5 chunks -> 3, 2, 2, 2, 2
int[,] input = new int[,] { { 8, 3 }, { 12, 2 }, { 9, 2 }, { 9, 4 }, { 11, 5 } };
int uBound0 = input.GetUpperBound(0);
int num = 0;
int split = 0;
for (int i = 0; i <= uBound0; i++)
{
num = input[i, 0];
split = input[i, 1];
int dev = num / split;
int mod = num % split;
string output = string.Empty;
//int slice = num - mod;
if (dev <= mod)
dev++;
for (int k = 1; k < split; k++)
{
output += dev + ",";
}
output += (num - (dev * (split - 1)));
Console.WriteLine(num + " into " + split + " chunks -> " + output);
}
output:
8 into 3 chunks -> 3,3,2
12 into 2 chunks -> 6,6
9 into 2 chunks -> 4,5
9 into 4 chunks -> 2,2,2,3
11 into 5 chunks -> 2,2,2,2,3
如果我得到一个数字,以及我需要将该数字分成多少组的数字,我如何将它分成尽可能接近偶数的块?
8 into 3 chunks -> 3, 3, 2
12 into 2 chunks -> 6, 6
9 into 2 chunks -> 4, 5
9 into 4 chunks -> 2, 2, 2, 3
11 into 5 chunks -> 2, 2, 2, 2, 3
这似乎或多或少有效:
int[] GetGroups(int number, int chunks) =>
Enumerable
.Range(0, chunks)
.Select(x => number / chunks + (number % chunks > x ? 1 : 0))
.ToArray();
var inputs = new[]
{
new { n = 8, c = 3, },
new { n = 12, c = 2, },
new { n = 9, c = 2, },
new { n = 9, c = 4, },
new { n = 11, c = 5, },
};
foreach (var input in inputs)
{
Console.WriteLine($"{input.n} into {input.c} chunks -> {String.Join(", ", GetGroups(input.n, input.c))}");
}
这给了我:
8 into 3 chunks -> 3, 3, 2
12 into 2 chunks -> 6, 6
9 into 2 chunks -> 5, 4
9 into 4 chunks -> 3, 2, 2, 2
11 into 5 chunks -> 3, 2, 2, 2, 2
int[,] input = new int[,] { { 8, 3 }, { 12, 2 }, { 9, 2 }, { 9, 4 }, { 11, 5 } };
int uBound0 = input.GetUpperBound(0);
int num = 0;
int split = 0;
for (int i = 0; i <= uBound0; i++)
{
num = input[i, 0];
split = input[i, 1];
int dev = num / split;
int mod = num % split;
string output = string.Empty;
//int slice = num - mod;
if (dev <= mod)
dev++;
for (int k = 1; k < split; k++)
{
output += dev + ",";
}
output += (num - (dev * (split - 1)));
Console.WriteLine(num + " into " + split + " chunks -> " + output);
}
output:
8 into 3 chunks -> 3,3,2
12 into 2 chunks -> 6,6
9 into 2 chunks -> 4,5
9 into 4 chunks -> 2,2,2,3
11 into 5 chunks -> 2,2,2,2,3