Sumit
Sumit

Reputation: 1430

Print each items of List N times

I'm new to Scala/Functional Programming and want to understand if my below solution fits into the functional programming world. If someone can suggest me a better approach, I will be obliged.

Problem Statement: Print each item of a list, n times

Solution:

import scala.collection.mutable.ListBuffer

object ListReplication extends App {


  def printNTimes(items: List[Int], n: Int): ListBuffer[Int] = {

    var outputList = new ListBuffer[Int]

    def storeNTime(item: Int): Unit = {

      for (_ <- 1 to n) outputList += item

    }

    for (item <- items) storeNTime(item)

    outputList
  }

  val result = printNTimes(items = List(1,2,4), n = 3)
  println(result)
}

Upvotes: 1

Views: 307

Answers (1)

Tomer Shetah
Tomer Shetah

Reputation: 8529

It is always better to work with immutable types. So I'll change the return type into List[Int]. You can just do:

def printNTimes(items: List[Int], n: Int): List[Int] = {
  items.flatMap(i => Vector.fill(n)(i))
}

or:

def printNTimes(items: List[Int], n: Int): List[Int] = {
  items.flatMap(Vector.fill(n)(_))
}

Then running:

println(printNTimes(List(1,2,4), 3))

will output:

List(1, 1, 1, 2, 2, 2, 4, 4, 4)

Upvotes: 6

Related Questions