Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

scala - 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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))
}

Then running:

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

will output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...