折叠数组

huangapple go评论74阅读模式
英文:

Collapsing an array

问题

public static int[] collapse(int[] arrayToCollapse) {

    // Properties
    int[] newArray = new int[(arrayToCollapse.length / 2) + (arrayToCollapse.length % 2)];

    // Set each element for the new array.
    for (int i = 0; i < arrayToCollapse.length / 2; i++) {

        // Set the current index of the new array to the sum of the next two elements from the input array.
        newArray[i] = arrayToCollapse[i * 2] + arrayToCollapse[i * 2 + 1];

    }

    // Set the last element of the new array if the input array length is odd.
    if (arrayToCollapse.length % 2 == 1) {
        newArray[newArray.length - 1] = arrayToCollapse[arrayToCollapse.length - 1];
    }

    // Return the new array
    return newArray;
}
英文:

I need to have this method take in an array and add every 2 numbers together(doesn't add the same number twice) and make a new array to return, if there is an an odd number of elements the odd number will be added at the end. It currently doesn't add the correct numbers.

code:

public static int[] collapse(int[] arrayToCollapse) {

    // Properties
    int[] newArray = new int[(arrayToCollapse.length / 2) + (arrayToCollapse.length % 2)];

    // Set each elements for the new array.
    for(int i = 0; i &lt; arrayToCollapse.length / 2 ; i++) {

        // Set the current index of the new array to the next two elements of the passed in array.
        newArray[i] += arrayToCollapse[i * 2] + arrayToCollapse[i * 2];

    }

    // Set the last element of the new array if the array passed in was odd.
    if(arrayToCollapse.length % 2 == 1) {

        newArray[newArray.length - 1] = arrayToCollapse[arrayToCollapse.length - 1];

    }

    // Return the array
    return newArray;

}

答案1

得分: 2

新数组[i] = 数组要折叠的部分[i * 2] + 数组要折叠的部分[(i * 2) + 1];
英文:

This:

newArray[i] += arrayToCollapse[i * 2] + arrayToCollapse[i * 2];

Should be:

newArray[i] = arrayToCollapse[i * 2] + arrayToCollapse[(i * 2) + 1];

huangapple
  • 本文由 发表于 2020年9月24日 05:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64036598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定