Motivation: Sometimes certain items in a list don't count towards your totals. For example, counting plane passengers in rows, where babies sit on a parent's laps.
Challenge: write a program to split a list of items into chunks. Each chunk (except possibly the last) is the same size, where size is defined as the number of items passing a predicate function.
Rules:
- Your program must take
- a list of items
- a positive integer chunk size
- a predicate function (takes an item, and returns true or false)
- You must return the input list split into chunks
- Each chunk is a list of items
- Overall the items must remain in the same order, with none disgarded
- The number of items passing predicate in each chunk (except possibly the last) should match the input chunk size.
- items failing the predicate should not count toward this size
- Items failing the predicate are
- still included in the output chunks
- allocated to the earliest chunk, in the case that a chunk is "full" but the next items are ones failing the predicate
- thus the final chunk may not consist solely of items failing the predicate
- The final chunk may be of size less than the chunk size because all the items have been accounted for.
Non exhaustive examples:
The simplest example is to consider 1
s and 0
s, where the predicate function is x ==> x > 0
. In this case, the sum
of each chunk must match the chunk size.
- items:
[]
, size:2
, predicate:x > 0
--> either[]
or[[]]
- items:
[0, 0, 0, 0, 0, 0]
, size:2
, predicate:x > 0
-->[[0, 0, 0, 0, 0, 0]]
- items:
[0, 1, 1, 0]
, size:2
, predicate:x > 0
-->[[0, 1, 1, 0]]
- items:
[0, 1, 1, 0, 1, 0, 0]
, size:2
, predicate:x > 0
-->[[0, 1, 1, 0], [1, 0, 0]]
- items:
[0, 1, 0, 0, 1, 0, 1, 1, 0]
, size:2
, predicate:x > 0
-->[[0, 1, 0, 0, 1, 0], [1, 1, 0]]
And let's finish with the plane passengers where babies sit on a parent's lap example. A
for adult, b
for baby, plane row is 3
seats wide, adult always listed before their baby:
- items:
[A, b, A, b, A, A, A, b, A, b, A, A, b]
, size:3
, predicate:x => x == A
-->[[A, b, A, b, A], [A, A, b, A, b], [A, A, b]]