0

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?

Community
  • 1
  • 1
user3995789
  • 3,452
  • 1
  • 19
  • 35
  • If the list is shuffled, I'm not sure the second requirement could hold. Assume the order is (0,1,2,3,0), the first list should contain (1), but concatenating them would give us (1,0,2,3,0). Can the second requirement be relaxed such that `list1::list2` has the same members and count as `list`, but not the same order? – Michael Bar-Sinai Jul 03 '16 at 08:55
  • order doesn't matter @MichaelBar-Sinai – user3995789 Jul 03 '16 at 10:24
  • 1
    What solutions have you already tried? – Dima Jul 03 '16 at 11:35
  • @MichaelBar-Sinai, I think when the first element is 0, `list1` must be empty to preserve the invariant. – The Archetypal Paul Jul 03 '16 at 21:18

2 Answers2

2

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.

Nikita
  • 4,435
  • 3
  • 24
  • 44
0

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
Michael Bar-Sinai
  • 2,729
  • 20
  • 27