Write a java program that calls a method called reverse4 that accepts an ArrayLi
ID: 3816684 • Letter: W
Question
Write a java program that calls a method called reverse4 that accepts an ArrayList of integer values as a parameter and reverses each successive sequence of four values in the list. If the list has extra values that are not part of a sequence of four, those values are unchanged. For example if a list stores values [10, 13, 2, 8, 7, 90, -1, 2, 4, 5], after the call the list should store the values [8, 2, 13, 10, 2, -1, 90, 7, 4, 5]. The first sequence of four (10, 13, 2, 8) has been reversed to (8, 2, 13, 10). The second sequence (7, 90, -1, 2) has been reversed to (2, -1, 90, 7) and so on. Notice that 4 and5 are unchanged because they were not part of a sequence of four values. Print the array before the call and after the call.
import java.util.*;
public class Reverse4 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(13);
list.add(2);
list.add(8);
list.add(7);
list.add(90);
list.add(-1);
list.add(2);
list.add(4);
list.add(5);
System.out.println(list.toString());
reverse4(list);
System.out.println(list.toString());
}
*Insert method code here*
}
Explanation / Answer
Reverse4.java
import java.util.*;
public class Reverse4 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(13);
list.add(2);
list.add(8);
list.add(7);
list.add(90);
list.add(-1);
list.add(2);
list.add(4);
list.add(5);
System.out.println(list.toString());
reverse4(list);
System.out.println(list.toString());
}
//*Insert method code here*
public static void reverse4(ArrayList<Integer> list ) {
int size = list.size();
int n = 4;
int count=0;
int temp =0;
while(n < size){
for(int i=count,j=0; i<count+2; i++,j++){
temp = list.get(i);
list.set(i, list.get(n+count-j-1));
list.set(n+count-j-1, temp);
}
size = size - n;
count = count+n ;
}
}
}
Output:
[10, 13, 2, 8, 7, 90, -1, 2, 4, 5]
[8, 2, 13, 10, 2, -1, 90, 7, 4, 5]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.