Accessing an index in a list in Scala

2019-08-12 07:18发布

问题:

I have to write a method "all()" which returns a list of tuples; each tuple will contain the row, column and set relevant to a particular given row and column, when the function meets a 0 in the list. I already have written the "hyp" function which returns the set part I need, eg: Set(1,2). I am using a list of lists:

| 0 | 0 | 9 |
| 0 | x | 0 |
| 7 | 0 | 8 |

If Set (1,2) are referring to the cell marked as x, all() should return: (1,1, Set(1,2)) where 1,1 are the index of the row and column.

I wrote this method by using zipWithIndex but I can't use this function. Is there any simpler way how to access an index as in this case? Thanks in advance

Code:

 def all(): List[(Int, Int, Set[Int])] = 
 {
    puzzle.list.zipWithIndex flatMap 
    { 
      rowAndIndex =>
      rowAndIndex._1.zipWithIndex.withFilter(_._1 == 0) map 
      { 
        colAndIndex =>
        (rowAndIndex._2, colAndIndex._2,  hyp(rowAndIndex._2, colAndIndex._2)) 
      }
    }
 } 

The (_._1 == 0 ) is because the function has to return the (Int,Int, Set()) only when it finds a 0 in the grid

回答1:

The all function can be simplified as this:

// Given a list of list
puzzle.list = List(List(0, 0, 9), List(0, 5, 0), List(7, 0, 8))

for {

  (row, rIndex) <- puzzle.list.zipWithIndex   // List of (row, index)
                                              // List( (List(0,0,9), 0) ...

  (col, cIndex) <- row.zipWithIndex;          // List of (col, index)
                                              // List( (0,0), (0,1), (9, 2) ...

  if (col == 0)                               // keep only col with 0

} yield (rIndex, cIndex, hyp(rIndex, cIndex))