从连续的int数组元素创建对值

时间:2014-04-12 12:39:47

标签: c# arrays

我需要将数组中的第一个和第二个,然后是第三个和第四个,然后是第五个和第六个元素相加。 例如,如果我得到输入int [] {1,2,3,3,4,-1}我需要将它计算为new int [] {3,3,3}

using System;

class Program
{
static void Main()
{
    int[] Arr = new int[] {1, 2, 0, 3, 4, -1};
    int sum = 0;
    foreach(int index in Arr)
    {
        //sum = (Arr[index at 0 position] + Arr[item at 0 position + 1]); 
        //Then do nothing with Arr[index at 1 position]
        //Then sum Arr[index at 2 position] + Arr[item at 3 position];
        //Then do nothing with Arr[index at 4 position]

        //if I test this condition
        // if(Arr[index]%2==0) //here I want to test the actual index of the element, not the value behind the index
        //{skip the next Arr[index]}
        //else{ sum Arr[index]+Arr[index + 1] }



    }
}   

}

2 个答案:

答案 0 :(得分:2)

如果长度为奇数,则总结每一对并保留最后一个:

int[] Arr = new int[] { 1, 2, 0, 3, 4 };
int ExactResultLength = (int)(((double)Arr.Length / 2) + 0.5);
int[] res = new int[ExactResultLength];

int j = 0;
for (int i = 0; i < Arr.Length; i+= 2)
{
    if(i + 1 < Arr.Length)
        res[j] = Arr[i] + Arr[i+1];
    else
        res[j] = Arr[i];

    j++;
}

答案 1 :(得分:2)

假设你不关心没有一对的元素:

int[] Arr = new int[] {1, 2, 0, 3, 4, -1};
int[] Arr2 = new int[Arr.Length / 2];

for (int i = 0; i < Arr2.Length; i++)
    Arr2[i] = Arr[i * 2] + Arr[i * 2 + 1];

但是,如果你这样做,它应该出现在输出数组中,最后添加以下行:

Arr2[Arr2.Length - 1] = Arr[Arr.Length - 1];

并将Arr2的长度更改为Arr.Lenght / 2 + 1