Mirroring method using arraylist
I am writing a Mirror method that duplicates the post back and adds to the original ArrayList if the size is even.
public ArrayList<Integer> mirror(ArrayList<Integer> mr) {
if (mr.size() % 2 == 0) {
for (int i = mr.size() - 1; i > 0; i--) {
mr.add(mr.get(i));
}
}
return mr;
}
It doesn't give 1 though.
eg.
[1,2,3,4]->[1,2,3,4,4,3,2]
If i> 0 is changed to i> = 0, then
[1,2,3,4]-> [1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1]
source to share
What do you call a mirror?
When I change i > 0
to i >= 0
, I get the expected results.
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList(Arrays.asList(1, 2, 3, 4));
System.out.println(mirror(list));
}
public static ArrayList<Integer> mirror(ArrayList<Integer> mr) {
if (mr.size() % 2 == 0) {
for (int i = mr.size() - 1; i >= 0; i--) {
mr.add(mr.get(i));
}
}
return mr;
}
Results:
[1, 2, 3, 4, 4, 3, 2, 1]
Update
Actually, why check if it's even a dimensional list? Just a mirror of any size.
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
System.out.println(mirror(list));
}
public static ArrayList<Integer> mirror(ArrayList<Integer> mr) {
for (int i = mr.size() - 1; i >= 0; i--) {
mr.add(mr.get(i));
}
return mr;
}
Results:
[1, 2, 3, 3, 2, 1]
source to share
You just need to do this:
- Check if list size is valid
- Make a copy of the original list
- Reverse copy
- Add a back copy to the original list
Code:
import java.util.ArrayList;
import java.util.Collections;
public class Snippet {
public static ArrayList<Integer> mirror(ArrayList<Integer> mr) {
if (mr.size() % 2 == 0) {
ArrayList<Integer> copy = new ArrayList<>();
copy.addAll(mr); // Copy original list
Collections.reverse(copy); // Reverse copy
mr.addAll(copy); // Append reversed copy to original list
}
return mr;
}
public static void main(String [] args) {
ArrayList<Integer> lst = new ArrayList<Integer>();
lst.add(1);
lst.add(2);
lst.add(3);
lst.add(4);
lst = mirror(lst);
for(Integer n : lst) {
System.out.print(n + " ");
}
}
}
Output:
1 2 3 4 4 3 2 1
source to share
Just an alternative solution using existing JDK methods:
public static <E, T extends List<E>> T mirror(T mr) {
int size = mr.size();
mr.addAll(mr.subList(0, size));
Collections.reverse(mr.subList(size, size*2));
return mr;
}
Note that the method is now much more general: it can work with any modified type of list (not only ArrayList
), but also with any type of list items (not only Integer
).
source to share