how can we slove this static method ? help me out | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how can we slove this static method ? help me out

Write a static method named stretch that accepts an array of integers as a parameter and returns a new array as twice as the original, replacing every integer from the original array with a pair of integers each half of the original. If a number in the original array is odd then first number in the new array should be higher then the second so the sum equals the original number. For example if a list contains following values {18,9,6,28,13}, the call of the stretch function should create the new array as following {9,9,5,4,3,3,14,14,7,6}.

19th Jun 2020, 10:43 AM
neil advani
neil advani - avatar
4 Answers
+ 1
import java.util.*; public class TestStretch { public static void main(String[] args) { int[] list = {18, 7, 4, 14, 11}; int[] list2 = stretch(list); System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11] System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5] } public static int[] stretch(int[] array){ int length = array.length; int[] newArray = new int[array.length*2]; for(int i = 0; i< length; i=i+2){ int j = 0; if(array[i] % 2 == 0){ newArray[i] = (array[j]/2); newArray[i+1] = newArray[i]; j++; } else{ newArray[i] = (array[j]/2); newArray[i+1] = (newArray[i] + 1); j++; } } return newArray; } } but i m getting output (9,9,9,9,9,9,10,0,0,0) instead of (9,9,5,4,3,2,2,7,7,6,5
19th Jun 2020, 11:27 AM
neil advani
neil advani - avatar
+ 1
javascritpt
19th Jun 2020, 11:28 AM
neil advani
neil advani - avatar
0
which language ?
19th Jun 2020, 11:01 AM
Diya AbuZaid
Diya AbuZaid - avatar
0
With JavaScript, use Array.prototype.reduce() https://code.sololearn.com/WjgLoufudDRF/?ref=app
19th Jun 2020, 1:29 PM
Ore
Ore - avatar