0

I want to define a function like this:
def mixUp[A](lista: List[A], aprop: Int, listb: List[A], bprop: Int): List[A]

lista and listb are two List that has the same generic.

And the aprop,bprop meaning the proportion of lista and listb that appears.


Assume

val lista = List("1", "2", "3")
val listb = List("a", "b", "c", "d", "e", "f")

Then the result of calling mixUp(lista, 1, listb, 2) should be
List("1", "a", "b", "2", "c", "d", "3", "e", "f")


And if

val lista = List("1", "2")
val listb = List("a", "b", "c", "d", "e")

The result of mixUp(lista, 1, listb, 2) should be
List("1", "a", "b", "2", "c", "d", "e")


If

val lista = List("1", "2", "3", "4")
val listb = List("a", "b", "c")

The result of mixUp(lista, 1, listb, 2) should be
List("1", "a", "b", "2", "c", "3", "4")

How to implement the function?

Joe
  • 3,581
  • 4
  • 23
  • 28

2 Answers2

4
def mix[A](lista: List[A], aprop: Int, listb: List[A], bprop: Int): List[A] = 
  lista.grouped(aprop).zipAll(listb.grouped(bprop), List(), List()).flatMap(t => t._1 ++ t._2).toList

Use grouped to split the List by size, and zipAll with default empty List() to keep all results are same size, flatMap to flatten map and concat the tuple.

Result:

scala> mix(lista, 1, listb, 2)
res8: List[AnyVal] = List(1, a, b, 2, c, d, 3)

scala> mix(lista, 2, listb, 2)
res9: List[AnyVal] = List(1, 2, a, b, 3, c, d)

scala> mix(lista, 2, listb, 3)
res10: List[AnyVal] = List(1, 2, a, b, c, 3, d)
chengpohi
  • 14,064
  • 1
  • 24
  • 42
1
def mixUp[A]( lista: List[A]
            , aprop: Int
            , listb: List[A]
            , bprop: Int
            , acc: List[A] = List()
            ): List[A] = {
  if (lista.nonEmpty)
    mixUp(listb, bprop, lista.drop(aprop), aprop, acc ++ lista.take(aprop))
  else if (listb.nonEmpty)
    mixUp(listb.drop(bprop), bprop, lista, aprop, acc ++ listb.take(bprop))
  else acc
}

Add elements to the accumulator in the proper proportions until you run out of elements.

jwvh
  • 50,871
  • 7
  • 38
  • 64