gpt4 book ai didi

c# - 如何在C#中动态添加数组的索引值?

转载 作者:行者123 更新时间:2023-12-02 03:10:15 27 4
gpt4 key购买 nike

我有一个数组,必须将前两个最小值相加,因此结果必须添加到下一个最小值,依此类推,直到到达数组末尾才能得出最终总计。

但是,如何动态修改方法/函数,以便如果值发生变化并且数组中有 6 个车辆和 6 个规范值,则返回方法/函数总数不限于 4 个索引。

数组值未排序,因此为了添加第一个最小的值,必须对其进行排序。完成后,它会添加新数组的值。

这是我尝试过的:

public static int vehicles = 4;
public static int[] specs = new int[] { 40, 8, 16, 6 };

public static int time(int vehicles, int[] specs)
{
int newValue = 0;

for (int i = 1; i < vehicles; i++)
{
newValue = specs[i];
int j = i;

while (j > 0 && specs[j - 1] > newValue)
{
specs[j] = specs[j - 1];
j--;
}
specs[j] = newValue;
}

// How can I dynamically change this below:
int result1 = specs[0] + specs[1];
int result2 = result1 + specs[2];
int result3 = result2 + specs[3];
int total = result1 + result2 + result3;

return total; // Returns 114
}

这是它的工作原理:

4, [40, 8, 16, 6] = 14 --> [40, 14, 16] = 30 --> [40, 30] = 70 ==>> 14 + 30 + 70 = 114
6, [62, 14, 2, 6, 28, 41 ] = 8 --> [62, 14, 8, 28, 41 ] --> 22 [62, 22, 28, 41 ] --> 50
[62, 50, 41 ] --> 91 [62, 91 ] --> 153 ==> 8 + 22 + 50 + 91 + 153 = 324

最佳答案

首先,如果由于某些奇怪的原因您不限于数组,请使用 List<int>你的生活会更轻松。

List<int> integers = { 14, 6, 12, 8 };

integers.Sort();

integers.Reverse();

while( integers.Count > 1 )
{
int i = integers[integers.Count - 1];
int j = integers[integers.Count - 2];
integers[integers.Count - 2] = i + j;
integers.RemoveAt(integers.Count - 1);
}

var result = integers[0];

P.S.:这可以很容易地修改为在数组版本上操作,但你不能RemoveAt()来自数组,但可以单独维护一个lastValidIndex。

关于c# - 如何在C#中动态添加数组的索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com