I want to divide a list in "a specific number of" sublists.
That is, for example if I have a list List(34, 11, 23, 1, 9, 83, 5)
and the number of sublists expected is 3 then I want List(List(34, 11), List(23, 1), List(9, 83, 5))
.
How do I go about doing this? I tried grouped
but it doesn't seem to be doing what I want.
PS: This is not a homework question. Kindly give a direct solution instead of some vague suggestions.
EDIT:
A little change in the requirements...
Given a list List(34, 11, 23, 1, 9, 83, 5)
and number of sublists = 3, I want the output to be List(List(34), List(11), List(23, 1, 9, 83, 5))
. (i.e. 1 element per list except for the last list which holds all the remaining elements.)
In response to your changed requirements,
def splitN[A](list: List[A], n: Int): List[List[A]] =
if(n == 1) List(list) else List(list.head) :: splitN(list.tail, n - 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With