5
\$\begingroup\$

Problem:

Given a list, repeat each element in the list n amount of times.

Solution:

def listReplication(num:Int,arr:List[Int]):List[Int] = {
      arr.flatMap(each => (1 to num).map(n => each))
}

Need review.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Use scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A) instead of your self written one:

def listReplication(num:Int,arr:List[Int]):List[Int] = {
      arr.flatMap(each => List.fill(num)(each))
}

Also note that listReplication is a nice candidate for generics:

def listReplication[A](num:Int,arr:List[A]):List[A] = {
      arr.flatMap(each => List.fill(num)(each))
}

That way you can also handle lists that contain something else than Int.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.