Two List Tasks
January 2, 2018
We have today two simple exercises on lists:
- Given a list of lists of integers, all the same length, return a list of the sums of the lists. For instance, given the list ((1 2 3 4) (2 3 4 5) (3 4 5 6)), return the list ((+ 1 2 3) (+ 2 3 4) (+ 3 4 5) (+ 4 5 6)), which is (6 9 12 15).
- Given a list of integers of length n = k × m, return a list of k items, each containing the sum of the next m integers from the original list. For instance, given the list, (1 2 3 4 2 3 4 5 3 4 5 6) and sub-list length m = 4, return the list (10 14 18).
Your task is to write programs that perform the two tasks. 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.
The answer to the first exercise could be simplified (in the eye of
this beholder) to:
(apply map + xss)
Another solution for the second exercise, using just R7RS Scheme.
A Haskell version.
Here’s a solution in C.
Output:
@Rutger, your solution to the first task sums elements within the sublists, as opposed to summing corresponding elements across the sublists.
Here’s a minor update that zips the lists so that the sum is across sublists.
Here’s the updated version that also supports sublists of differing lengths, padding the shorter sublists with zeros at the end.