user3995789
user3995789

Reputation: 3460

how to dropFirst takeFirst item according to a predicate in scala

I have these elements shuffled in a list

val list = (1,2,3,0, 0)

I need to split this list into two lists.

val list1 = (1)
val list2 = (2, 3, 0, 0)

The first list contains a single item that is not a 0, the second list contains the rest of the items.

Fix below code, so list1 never contains 0 and list1 :: list2 == list

val list = (1, 2, 0, 3, 0).shuffle

val list1 = list(0)
val list2 = list drop 1

Somewhat similar to this: How should I remove the first occurrence of an object from a list in Scala?

Upvotes: 0

Views: 185

Answers (2)

Michael Bar-Sinai
Michael Bar-Sinai

Reputation: 2739

Many ways of doing this, here's mine:

val list = List(0,1,0,3,2)
val list1 = List(list.find(_!=0).get)
val list2 = list.filter( _!=list1(0) )

End results (Scala REPL)

list: List[Int] = List(0, 1, 0, 3, 2)
list1: List[Int] = List(1)
list2: List[Int] = List(0, 0, 3, 2)

Note that this code assumes list has at list one non-zero member.

Updated (per @theArchetypalPaul's remark) to support lists with non-unique non-zero members:

val temp = list.span( _ == 0 )
val list1 = List(temp._2.head)
val list2 = temp._1 ++ temp._2.tail

Upvotes: 0

Nikita
Nikita

Reputation: 4515

I would start from the following function:

def sep(l: List[Int]) = 
  (l.find(_ != 0).toList, 
   l.takeWhile(_ == 0) ::: l.dropWhile(_ == 0).tail)

It returns what you need if solution exists:

sep(List(0, 1, 0, 2, 3)) -> (List(1),List(0, 0, 2, 3))
sep(List(1, 4, 0, 2, 3)) -> (List(1),List(4, 0, 2, 3))
sep(List(0, 0, 4, 5))    -> (List(4),List(0, 0, 5))

But if you have List(0,0)... The next step is to write it recursively so it uses the only one iteration.

Upvotes: 2

Related Questions