我希望构建一个包含不同元素的列表,这些元素总计定义的总和。例如,给定以下列表,总和为61.如何构建一个新列表,使其具有相同的61,但具有不同的元素,而不是具有重复的值4,7和9?
List<int> ElementList = new List<int> { 4, 4, 4, 4, 6, 7, 7, 7, 9, 9}
static void BuildDistinctList(List<int> InputList)
{
InputList.Sort();
Dictionary<int, int> DistinctValues = new Dictionary<int, int>();
for (int i = 0; i < InputList.Count; i++)
{
if(!DistinctValues.ContainsValue(InputList[i]))
{
DistinctValues.Add(i, InputList[i]);
}
else
{
//My thinking at this point would be to no longer mess with
//the value stored inside of the dictionary as it is fixed from this point
//forward, and to borrow from the remaining list values.
FindNewDistinctValue(MIN, MAX, DistinctValues, InputList, i, InputList.Count - i);
}
}
}
如果我通过这条路线遵循适当的方向,有人可以分享一些见解。或者提供一些解决方法。
编辑:我创建了下面的函数,并将其添加到提供的原始代码中的else语句中。它似乎有点工作,但我似乎从列表末尾的价值中借了太多,而且总和很少。这描绘了我想要做的更好的画面。如果您需要我澄清任何问题,请随时提出。
static void FindNewDistinctValue(int Min, int Max, Dictionary<int, int> DistinctValues, List<int> InputList, int CurrentIndex, int BorrowIndex)
{
for (int i = Min + 1; i < Max; i++)
{
if (!DistinctValues.ContainsValue(i))
{
int ValueToSubtractFromBorrowIndex = InputList[CurrentIndex] - i;
DistinctValues.Add(CurrentIndex, i);
InputList[BorrowIndex] = InputList[BorrowIndex] - ValueToSubtractFromBorrowIndex;
break;
}
}
}