public static void main(String[] args) { //int[] array = {1,2,3,4,5}; //System.out.print(collapse(array)); } @SuppressWarnings("unused") public static int[] collapse(int[] array) { int L=array.length; int outSize; if(L%2==0) outSize = L/2; else outSize = L/2+1; int[] array2 = new int[outSize]; //{2 3 4 5 6 7} ->{5 9 13} //{2 3 4 5 6} -> {5 9 6} int i2=0; for(int i=0;i<L-1;i=i+2) { array2[i/2] = array[i] + array[i+1]; //i2++; } if(L%2==1) { array2[outSize-1] = array[L-1]; } return array2; } return array2; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter