Reputation: 27
Write a method
public static ArrayList merge(ArrayList a, ArrayList b)
that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elemts from the longer array list. For example, if a is
1 4 9 16
and b is
9 7 4 9 11
then merge returns the array list
1 9 4 7 9 4 16 9 11
Okay this is my code so far.
All I need to do is merged two inputs given by user in same fashion as here
I asked same question earlier but that was for Array and i got satisfied result.
I tried solutions from that link but I have no result If someone can please give me quick hint on how to merge two ArrayList, I will appreciate the help.
import java.util.ArrayList;
import java.util.Scanner;
public class HomeWork6_27_B{
public static void main(String arg[]) {
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
System.out.print("Enter Array of numbers in First Set, type 0 when finished:");
System.out.println();
int in = scan.nextInt();
a.add(in);
in = scan.nextInt();
while (in !=0){
a.add(in);
in = scan.nextInt();
}
System.out.println("End of First Set");
System.out.print("Enter Array of numbers in Second Set, type 0 when finished:");
System.out.println();
int in2 = scan2.nextInt();
b.add(in2);
in2 = scan2.nextInt();
while (in2 !=0){
b.add(in2);
in2 = scan2.nextInt();
}
System.out.println("End of Second Set");
}
}
Upvotes: 0
Views: 992
Reputation: 560
I haven't used java for a while but I'm pretty sure this should work. Basically we loop to the end of the longer list, and add an element from each input list if we haven't reached the end of that input list.
ArrayList<Integer> merged = new ArrayList<Integer>();
// Merge the lists
for (int i = 0; i < Math.max(a.size(), b.size()); i++) {
if (i < a.size()) merged.add(a.get(i));
if (i < b.size()) merged.add(b.get(i));
}
for (int i = 0; i < merged.size(); i++) {
System.out.print(merged.get(i).toString() + " ");
}
Upvotes: 1