Homework: Looking for better strategy, or approach rather than complete code.
I'v got two arrayLists of integers under two conditions:
- the first list is bigger than the second
- the second list is larger than the first
My goal was to interleave elements of list2, into list1 under both conditions. I've created a method that does this, but I feel like I could be doing something better.
Here is the expected result for condition 1. Note that after the elements of list2 are exhausted, we leave the elements of list1 in place:
list1: [10, 20, 30, 40, 50, 60, 70]
list2: [4, 5, 6, 7]
Combined: [10, 4, 20, 5, 30, 6, 40, 7, 50, 60, 70]
Here is the expected result for condition 2. Since list2 has more elements, we append these elements to list1 after list1 is exhausted:
list1: [10, 20, 30, 40]
list2: [4, 5, 6, 7, 8, 9, 10, 11]
Combined: [10, 4, 20, 5, 30, 6, 40, 7, 8, 9, 10, 11]
My code uses an if-else statement to process both conditions. I then use an iterator to go through elements of list2 and insert them in list1.
public static void main(String[] Args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
//numbers.add(50);
//numbers.add(60);
//numbers.add(70);
ArrayList<Integer> numbers2 = new ArrayList<Integer>();
numbers2.add(4);
numbers2.add(5);
numbers2.add(6);
numbers2.add(7);
numbers2.add(8);
numbers2.add(9);
numbers2.add(10);
numbers2.add(11);
System.out.println("list1: " + numbers);
System.out.println("list2: " + numbers2);
interleave(numbers, numbers2);
System.out.println();
System.out.println("Combined: " + numbers);
}
public static void interleave(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
//obtain an iterator for the collection
Iterator<Integer> itr2 = list2.iterator();
//loop counter
int count = 1;
//handle based on initial size of lists
if(list1.size() >= list2.size())
{
//loop through the first array and add elements from list 2 after each element
while(itr2.hasNext())
{
//insert elements from list2
list1.add(count, itr2.next());
//make sure elements are getting added at 1, 3, 5, 7, 9, etc
count = count + 2;
}
}
else if(list1.size() < list2.size())
{
//loop through the first array and add elements from list 2 after each element
while(itr2.hasNext())
{
if(count <= list1.size())
{
//insert elements from list2
list1.add(count, itr2.next());
//make sure elements are getting added at 1, 3, 5, 7, 9, etc
count = count + 2;
}
else
{
//fill in the remainder of the elements from list2 to list1
list1.add(itr2.next());
}
}
}
}