I have two lists lets say:
def list1 = [a,b,c,d,e...]
def list2 = [1,2,3,4,5... ]
I want them to mix in a certain pattern so that final list looks like:
[a,b,c,d,1,2,e,f,g,h,3,4,i,j,k,l,5,6...]
Basically after every n elements from list1, i get m elements from list2.
EDIT: If one list runs out of elements, the items in the remaining list should simply get added to the final list.
EDIT2: Both the lists can have objects as elements.
I want to find the most efficient way to solve this problem.
Here’s one way of doing this in Groovy:
So I have a method
mixwhich takes a map with Integer keys (the number of elements required), and Lists as values:Then, given:
That returns:
(formatted to look better here)
As you can see, it runs out of numbers first, and when it does, the list ends. This is because transpose stops when one list runs out of elements.
EDIT:
Worked out another way with Iterators (so it’s lazy and won’t use up more memory than is otherwise required):
You call it by:
And ret will then equal: