Loading...

List Replication in Scala

I’m still going through Scala bit by bit via HackerRank code tests, it’s taking me a little while to get going but the second challenge was, as per the question:

Given a list, repeat each element in the list amount of times. The input and output portions will be handled automatically by the grader. You need to write a function with the recommended method signature.

The definition of the function is provided in the editor before you begin, specifying the parametres it accepts. However you need to figure out the mechanics of which yourself. In trying to keep with functional programming standards I ended up with this:

def f(num:Int,arr:List[Int]):List[Int] = arr.flatMap(e => List.fill(num)(e))

def f() accepts the number of times we will reproduce the elements in the list and the list that will be filtered through, in this case using flatMap. arr.flatMap() returns a new list using List.fill(num)(val). The first parameter is how many times parameter two is repeated in the new list. I found more reading on Scala Lists on this site.

Leave a Reply

Your email address will not be published. Required fields are marked *