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.

Zeta
19.6k2 gold badges57 silver badges90 bronze badges
asked Jul 17, 2017 at 6:33
\$\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.

answered Jul 17, 2017 at 8:37
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.