我有一个输入,我想使用以下逻辑基于输入分布来修改现有列表值。
int distributeVal = 7;
List<int> validationList = new List<int>();
distributeVal可以是任何整数,并且应该在validationList中平均分配。 少数情况:
distributeVal validationList validationList(Updated)
7 {5,5,5} {5,2}
7 {5,6,5} {5,2}
7 {6,5,5} {6,1}
8 {2,2,2,3} {2,2,2,2}
8 {1} {1} (remaining 7 ignored)
8 {5,2,7} {5,2,1}
2 {5,5,5} {2}
3 {1,1,5} {1,1,1}
8 {1,45,16} {1,7}
0 {1,50,50} {}
validationList的分配应基于FCFS允许的列表值。 我尝试执行此操作,但由于存在很多循环和条件,因此需要根据列表值划分distributedVal,然后对其进行修改。我怎样才能最好地做到这一点?谢谢。
答案 0 :(得分:2)
您可以尝试使用 Linq 来查询validationList
:
using System.Linq;
...
int distributeVal = 7;
List<int> validationList = new List<int>() { 2, 2, 2, 3 };
...
// validationList = if you want to "update" validationList
var result = validationList
.TakeWhile(_ => distributeVal > 0) // Keep on while we have a value to distribute
.Select(item => { // Distribution
int newItem = item > distributeVal // two cases:
? distributeVal // we can distribute partialy
: item; // or take the entire item
distributeVal -= newItem; // newItem has been distributed
return newItem;
})
.ToList();
Console.Write(string.Join(", ", result));
结果:
2, 2, 2, 1
答案 1 :(得分:2)
这是一个非Linq答案,它使用简单函数来计算这些值:
private List<int> GetValidationList(int distributeVal, List<int> validationList)
{
List<int> outputList = new List<int>();
int runningCount = 0;
for (int i = 0; i < validationList.Count; i++)
{
int nextValue;
if (runningCount + validationList[i] > distributeVal)
nextValue = distributeVal - runningCount;
else
nextValue = validationList[i];
outputList.Add(nextValue);
runningCount += nextValue;
if (runningCount >= distributeVal)
break;
}
return outputList;
}
本质上,遍历每个值并将其添加到输出中(如果该值低于所需总数)。如果不是,则计算差异并将其添加到输出中。
使用以下值运行:
List<int> result;
result = GetValidationList(7, new List<int> { 5, 5, 5 });
result = GetValidationList(7, new List<int> { 5, 6, 5 });
result = GetValidationList(7, new List<int> { 6, 5, 5 });
result = GetValidationList(8, new List<int> { 2, 2, 2, 3 });
result = GetValidationList(8, new List<int> { 1 });
result = GetValidationList(8, new List<int> { 5, 2, 7 });
result = GetValidationList(2, new List<int> { 5, 5, 5 });
result = GetValidationList(3, new List<int> { 1, 1, 5 });
result = GetValidationList(8, new List<int> { 1, 45, 16 });
result = GetValidationList(0, new List<int> { 1, 50, 50 });
提供此输出(在List<int>
中):
5,2
5,2
6,1
2,2,2,2
1
5,2,1
2
1,1,1
1,7
0
答案 2 :(得分:0)
Linq支持的最短方法:
private List<int> Validations(int value, List<int> validations)
{
List<int> outputList = new List<int>();
int runningCount = 0;
foreach (var nextValue in validations.Select(t => runningCount + t > value ? value - runningCount : t))
{
outputList.Add(nextValue);
runningCount += nextValue;
if (runningCount >= value) break;
}
return outputList;
}
用法:
var result = Validations(7, new List<int> { 1, 5, 1 });