user2947615
user2947615

Reputation: 497

Returning elements of a row in a list using Scala

I need to write a method that will return the contents of a particular row (index of it is inputted as method parameter). I have to use recursion and no loops.

So far I have attempted this uncompleted code (and I have no idea how to continue it):

class Sudoku(val grid: List[List[Int]]) {

   def r(r: Int): Set[Int] = {
   if (grid.isEmpty) Set()
   else 

  }
}

I also do not know how Set works. Any help would be really appreciated. PS: I am not asking for complete code, an algorithm explanation would be more than enough!

Upvotes: 0

Views: 208

Answers (1)

Knut Arne Vedaa
Knut Arne Vedaa

Reputation: 15742

This is the answer to the literal interpretation of the question:

class Sudoku(val grid: List[List[Int]]) {
  def row(n: Int): List[Int] =
    if (grid.size > n) grid(n) else Nil
}

The apply method on List, here applied on the value grid, which can be written either grid apply n, or simply grid(n) returns the n'th element of the list. If that element does not exist (e.g. grid(1000000)), it throws an exception, therefore we check the size of the list first.

I have no idea why you should return a Set, but you could simple call .toSet on the result. A Set is a collection with distinct elements (each element only occurs once) with no guarantee of ordering.

I also don't know why you would need recursion for this, so I reckon the question is part of a larger problem.

Upvotes: 1

Related Questions