组合1个数组的元素以使用for循环创建新数组

时间:2016-05-20 20:48:31

标签: java arrays sorting for-loop

下午好,

我分配了一个编程问题,我需要使用具有不同数量元素的单个数组,并配置一个新数组。

新数组将由前两个元素的总和组成,接着是接下来的两个元素总和,依此类推。

如果原始数组具有奇数个元素,则最后一个值将保持不变,前面的总和值。

public static int[] collapse(int[] old) {
    int[] nNew = new int[old.length];        
    if(old.length%2 == 0){
        nNew = new int[old.length/2];    
        for(int i =0; i<nNew.length; i+=2) {                        
            int temp = old[i] + old[i+1];
            nNew[i] = temp;            
        }                   
    }
     //i tried to for loop to increment by 1 here, but it didn't work out.
     //I believe this is where my problem is.

    if(old.length%2 != 0) {
        nNew = new int[(old.length/2) +1];        
        for(int i =0; i<nNew.length-1; i++) {
            //I can't get an Odd number of array elements to increment by 2
            int temp = old[i] + old[i+1];
            nNew[i] = temp;
            nNew[nNew.length-1] = old[old.length-1];
        }                
    }    
    return nNew; 
}

示例调用包括:

collapse({7, 2, 8, 9, 4, 13, 7, 1, 9, 10}) 
expected: {9, 17, 17, 8, 19}
my result: {9, 0, 17, 0, 17}

collapse({1, 2, 3, 4, 5}) 
expected: {3, 7, 5} 
my result: {3, 5, 5}

3 个答案:

答案 0 :(得分:0)

对于奇数长度数组的问题,你可以从1开始你的for循环,然后不是查看当前值和下一个值,而是查看i-1和i,然后递增2。能够用index.OutofBounds错误来阻止你的错误。

示例:

if(old.length%2 != 0) {
    nNew = new int[(old.length/2) +1];        
    for(int i =1; i<nNew.length-1; i += 2) {
        //I can't get an Odd number of array elements to increment by 2
        int temp = old[i-1] + old[i];
        nNew[i] = temp;
        nNew[nNew.length-1] = old[old.length-1];
    }                
}    

答案 1 :(得分:0)

不需要单独的循环。只需在同一循环中检查:

public static int[] collapse(int[] old) {
    int[] nNew = new int[(old.length + 1) / 2];
    for (int i = 0; i < old.length; i += 2) {
        nNew[i / 2] = old[i];
        if (i + 1 < old.length) {
            nNew[i / 2] += old[i + 1];
        }
    }
    return nNew;
}

答案 2 :(得分:0)

我认为解决这个问题的最好方法是使用一个for循环和if语句来帮助,如果数组长度是旧数字,表示最后一个数字不会出现,所以你只需要自己添加它。

public static int[] collapse(int[] array) {
    int[] newArray = new int[(array.length + 1)/2];
    int lastnum = array[array.length-1];
    for (int i = 1; i < array.length; i += 2) {
        newArray[i/2] = array[i] + array[i-1];
    }
    if (newArray[newArray.length-1] == 0)newArray[newArray.length-1] = lastnum;
    return newArray;
}