Alternating Lists
February 1, 2019
Today’s exercise is a simple task in list manipulation:
Write a program that takes one or more lists and returns a single list containing the elements of the input lists, taken alternately from the lists. If the lists are of different lengths, continue taking items from the lists that remain.
For instance, given the inputs (1 2 3 4 5)
, (a b c)
and (w x y z)
, the desired output is (1 a w 2 b x 3 c y 4 z 5)
.
Your task is to write a program to take items alternately from multiple lists. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Ruby. Assumes elements are in the lists are not nil.
Mumps version
1 a w 2 b x 3 c y 4 z 5
— Here’s some Haskell, I’ll leave it to enthusiasts to convert to pointfree style.
In Python.
I think my solution is a bit simpler:
(define (alternate x . y)
(cond
((null? y) x)
((null? x)
(apply alternate y))
(else
(cons
(car x)
(apply
alternate
(append y (list (cdr x))))))))
Here’s another Haskell solution. (In pointfree style! :-)
@Globules: very nice – it would be good to have a pointfree definition of transpose as well!
Here’s another Haskell version, this one is a simplification of a modification of the Haskell library definition of transpose. I’ve not seen that list comprehension with partial matches idiom before:
And here’s a pointfree Haskell solution that doesn’t seem too incomprehensible:
Here’s an simple-minded scheme solution with filter and map:
(define (not-null? x) (not (null? x)))
(define (splice . lists)
(let ((flists (filter not-null? lists)))
(if (not-null? flists)
(append (map car flists)
(apply splice (map cdr flists)))
'())))
Here’s a solution in C that uses linked lists.
Example:
Here’s a more raw, packageless python implementation I thought of:
def alternator(lists):
max_len = 0
if name == “main“:
lists = [[1,2,3,4,5],[‘a’,’b’,’c’],[‘w’,’x’,’y’,’z’]]
alternator(lists)
Here’s a solution in Common Lisp.
Example.
Here’s a solution in C that uses arrays.
Example:
Here’s a solution in Python.
Output: