Write a static method called \"reverse3\" that takes an ArrayList of Integer val
ID: 3643875 • Letter: W
Question
Write a static method called "reverse3" that takes an ArrayList of Integer values as a parameter and that reverses each successive sequence of three values in the list. For example, suppose that a variable called "list" stores the following sequence of values:[3, 8, 19, 42, 7, 26, 19, -8, 193, 204, 6, -4]
and we make the following call:
reverse3(list);
Afterwards the list should store the following sequence of values:
[19, 8, 3, 26, 7, 42, 193, -8, 19, -4, 6, 204]
The first sequence of three values (3, 8, 19) has been reversed to be (19, 8, 3). The second sequence of three values (42, 7, 26) has been reversed to be (26, 7, 42). And so on.
If the list has extra values that are not part of a sequence of three, those values are to remain unchanged. For example, if the list had instead stored:
[3, 8, 19, 42, 7, 26, 19, -8, 193, 99, 2]
The result would have been:
[19, 8, 3, 26, 7, 42, 193, -8, 19, 99, 2]
Note that the values (99, 2) are unchanged in position because they were not part of a sequence of three values.
import java.util.*;
public class Reverse3 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(8);
list.add(19);
list.add(42);
list.add(7);
list.add(26);
list.add(19);
list.add(-8);
list.add(193);
list.add(99);
list.add(2);
System.out.println(list.toString()); // [3, 8, 19, 42, 7, 26, 19, -8, 193, 99, 2]
reverse3(list);
System.out.println(list.toString()); // [19, 8, 3, 26, 7, 42, 193, -8, 19, 99, 2]
}
// *** Your method code goes here ***
} // End of Reverse3 class
Explanation / Answer
Please rate...
import java.util.*;
public class Reverse3
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(8);
list.add(19);
list.add(42);
list.add(7);
list.add(26);
list.add(19);
list.add(-8);
list.add(193);
list.add(99);
list.add(2);
System.out.println(list.toString()); // [3, 8, 19, 42, 7, 26, 19, -8, 193, 99, 2]
reverse3(list);
System.out.println(list.toString()); // [19, 8, 3, 26, 7, 42, 193, -8, 19, 99, 2]
}
public static void reverse3(ArrayList<Integer> list)
{
int l=list.size();
int a=l/3;
int i,t;
for(i=0;i<a*3;i=i+3)
{
t=list.get(i);
list.set(i,list.get(i+2));
list.set(i+2,t);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.