英文:
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 < 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];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论