+ 4

Explain me this problem

Consider this C Program or Java Program. It reads integers from the standard input (until it gets a negative number) and puts them into an array. After that it calls processArray on the array, and then prints the contents of the array on standard output. Currently, processArray does not modify the array. You have to change this program so that any sequence of two or more consecutive odd numbers in the array is replaced by a single integer that is the maximum of all the numbers in that sequence. The processArrayfunction/method should modify the array in-place (preferably without creating a new array), and it should return the new length of the modified array. For example, if these numbers were provided on the standard input: 1 3 33 62 122 63 65 39 662 9 -1 Then the program should print: 33 62 122 65 662 9 http://www2.rsphinx.com/site_media/misc/arrayproc.c http://www2.rsphinx.com/site_media/misc/ArrayProc.java

9th Sep 2018, 5:19 PM
Sayan Kundu
4 odpowiedzi
+ 2
Ok, I have understood the problem and the example. From the start of the list, 1, 3 and 33 are odd numbers, Maximum number is 33. Output: 33 Then 62, 122 are even so, those are left as it is. Output: 62, 122 In between 63,65,39 maximum is 65. Output: 65 As 662 is even, output: 662 9 is odd number with no consecutive, output: 9
30th Oct 2018, 4:49 AM
Sayan Kundu
+ 1
We don't normally write programs. We will fix your broken code only.
9th Sep 2018, 10:08 PM
John Wells
John Wells - avatar
+ 1
Here is the logic you can use: public static void main(String[] args) { int[] arr = {1,33,3,62,122,63,65,39,662,9}; int oddCounter = 0; int val = 0; int i = 0; int length = arr.length; while(true) { if(i == length) { break; } if(arr[i]%2 != 0) { oddCounter++; if(oddCounter == 2) { if(arr[i] > val ) { val = arr[i]; } oddCounter = 0; arr[--i] = val; length = length-1; arr = processArray(arr, i+1); val = 0; } else { val = arr[i]; i++; } } else{ i++; val = 0; oddCounter = 0; } } for(int j = 0 ; j<length ; j++) { System.out.println(arr[j]); } } public static int[] processArray(int[] arr, int i) { for(int k = i; k<arr.length-1 ; k++) { arr[k] = arr[k+1]; } return arr; } I have harcoded the input, you can use the combination of scanner class and while(true) {if(scan.nextInt<0) {break;} else{//insert into array}} to get the array dynamically. LMK your thoughts
15th Jan 2021, 11:10 AM
Rohan Ganiga
Rohan Ganiga - avatar
0
John Wells I wish to solve programs by myself. But, here I am not able to understand the question. If you understand it, can you please elaborate it?
10th Sep 2018, 6:47 AM
Sayan Kundu