Question

I need to print a List of Lists using Scala and the function toString, where every occurrence of 0 needs to be replaced by an '_'. This is my attempt so far. The commented code represents my different attempts.

override def toString() = {

    // grid.map(i => if(i == 0) '_' else i)
    // grid map{case 0 => '_' case a => a}
    // grid.updated(0, "_")
    //grid.map{ case 0 => "_"; case x => x}  
    grid.map(_.mkString(" ")).mkString("\n")  

 }

My output should look something like this, but an underscore instead of the zeros

0 0 5 0 0 6 3 0 0
0 0 0 0 0 0 4 0 0
9 8 0 7 4 0 0 0 5
1 0 0 0 7 0 9 0 0
0 0 9 5 0 1 6 0 0
0 0 8 0 2 0 0 0 7
6 0 0 0 1 8 0 9 3
0 0 1 0 0 0 0 0 0

Thanks in advance.

Was it helpful?

Solution 3

Although the other solutions are functionally correct, I believe this shows more explicitly what happens and as such is better suited for a beginner:

def gridToString(grid: List[List[Int]]): String = {

  def replaceZero(i: Int): Char =
    if (i == 0) '_'
    else i.toString charAt 0

  val lines = grid map { line =>
    line map replaceZero mkString " "
  }

  lines mkString "\n"
}

First we define a method for converting the digit into a character, replacing zeroes with underscores. (It is assumed from your example that all the Int elements are < 10.)

The we take each line of the grid, run each of the digits in that line through our conversion method and assemble the resulting chars into a string.

Than we take we take the resulting line-strings and turn them into the final string.

The whole thing could be written shorter, but it wouldn't necessarily be more readable.

It is also good Scala style to use small inner methods like replaceZero in this example instead of writing all code inline, as the naming of a method helps indicating what it is does, and as such enhances readability.

OTHER TIPS

Just put an extra map in there to change 0 to _

grid.map(_.map(_ match {case 0 => "_"; case x => x}).mkString(" ")).mkString("\n")

Nothing special:

def toString(xs: List[List[Int]]) = xs.map { ys => 
    ys.map { 
        case 0 => "_"
        case x => String.valueOf(x)
    }.mkString(" ")
}.mkString("\n")

There's always room for another solution. ;-)

A grid:

type Grid[T] = List[List[T]]

Print a grid:

def print[T](grid: Grid[T]) = grid map(_ mkString " ") mkString "\n"

Replace all zeroes:

for (row <- grid) yield row.collect {
    case 0 => "_"
    case anything => anything
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top