因此,在此数组中,每个数字都是结果,该结果的索引是分配给给出结果的人的数字。 我需要找出哪个得分手为阵列中的所有行提供了最高的结果。所以说结果[0-3,3]是所有行的得分手3我如何找出哪个得分手总共给出了所有行的最高结果? 输出的一个例子是
所以输出的例子是“得分4给出最高的平均得分9”
int[,] results ={//Each number is a scorer's score
{ 4, 7, 9, 3, 8, 6},//competitor 1
{ 4, 8, 6, 4, 8, 5},//competitor 2
{ 2, 1, 10, 10, 10, 10}
};
答案 0 :(得分:0)
从你的问题来看,你想知道哪个专栏(得分手)的平均得分最高,而不是行(这将是竞争者和不是得分手。)
这是我将如何做到的:
var bestScorer =
results
.OfType<int>()
.Select((x, n) => new { x, n })
.GroupBy(xn => xn.n % results.GetLength(1))
.Select(gxns => new
{
average = gxns.Average(xn => xn.x),
scorer = gxns.Key + 1,
})
.OrderByDescending(x => x.average)
.Select(x =>
String.Format(
"Scorer {0} gave the highest average score of {1}",
x.scorer,
x.average))
.First();
这给出了结果:
Scorer 5 gave the highest average score of 8.66666666666667
如果您将字符串格式更改为"Scorer {0} gave the highest average score of {1:0}"
,那么您将获得:
Scorer 5 gave the highest average score of 9
如果您确实需要行/竞争对手,请将%
更改为/
,这仍然有效。
使用循环执行此操作将如下所示:
var best = new { scorer = -1, average = double.MinValue };
for (var j = 0; j < results.GetLength(1); j++)
{
var total = 0;
for (var i = 0; i < results.GetLength(0); i++)
{
total += results[i, j];
}
var current = new { scorer = j + 1, average = (double)total / results.GetLength(0) };
if (current.average > best.average)
{
best = current;
}
};
var output =
String.Format(
"Scorer {0} gave the highest average score of {1}",
best.scorer,
best.average);
我得到与上面相同的输出。
答案 1 :(得分:-1)
使用列表&lt;&gt;与linq
static void Main(string[] args)
{
List<List<int>> results = new List<List<int>>() {//Each number is a scorer's score
new List<int>(){ 4, 7, 9, 3, 8, 6},//competitor 1
new List<int>(){ 4, 8, 6, 4, 8, 5},//competitor 2
new List<int>(){ 2, 1, 10, 10, 10, 10}
};
var max = results.Select((x, i) => new
{
total = x.Sum(),
index = i
}).OrderByDescending(x => x.total).Take(1);
}
答案 2 :(得分:-1)
我认为有些竞争对手可能会获得相同的分数。 bestScorersIds
是具有最高总分的竞争者的索引列表。
int[,] results ={//Each number is a scorer's score
{ 4, 7, 9, 3, 8, 6},//competitor 1
{ 4, 8, 6, 4, 8, 5},//competitor 2
{ 2, 1, 10, 10, 10, 10}
};
var max = Enumerable.Range(0, results.GetLength(0))
.Max(i => Enumerable.Range(0, results.GetLength(1)).Sum(j => results[i,j]));
var bestScorersIds = Enumerable.Range(0, results.GetLength(0))
.Where(i => Enumerable.Range(0, results.GetLength(1)).Sum(j => results[i, j]) == max)
.ToList();
带循环的替代解决方案:
int[,] results ={//Each number is a scorer's score
{ 4, 7, 9, 3, 8, 6},//competitor 1
{ 4, 8, 6, 4, 8, 5},//competitor 2
{ 2, 1, 10, 10, 10, 10}
};
List<int> bestScorersIds = new List<int>();
int bestScore = 0;
for (int i = 0; i < results.GetLength(0); i++)
{
int tempScore = 0;
for (int j = 0; j < results.GetLength(1); j++)
tempScore += results[i, j];
if (tempScore < bestScore) continue;
if(tempScore > bestScore) bestScorersIds.Clear();
bestScorersIds.Add(i);
}