Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a list in specific number of sublists

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.)

like image 429
Surya Avatar asked Feb 26 '23 23:02

Surya


1 Answers

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)
like image 61
2 revs Avatar answered Mar 01 '23 12:03

2 revs