我有一个代表网格的列表列表。我需要访问特定块的元素。例如:
| 0 | 1 | 0 || 0 | 0 | 0 || 0 | 0 | 8 |
| 0 | 0 | 0 || 2 | 9 | 0 || 5 | 1 | 3 |
| 0 | 0 | 0 || 7 | 0 | 0 || 0 | 0 | 0 |
-------------------------------------
| 0 | 4 | 0 || 5 | 0 | 0 || 7 | 0 | 2 |
| 0 | 0 | 0 || 4 | 6 | 0 || 9 | 8 | 1 |
| 3 | 0 | 0 || 1 | 0 | 0 || 0 | 0 | 0 |
-------------------------------------
| 0 | 1 | 0 || 5 | 0 | 0 || 4 | 0 | 2 |
| 0 | 2 | 0 || 0 | 1 | 0 || 0 | 0 | 0 |
| 0 | 9 | 0 || 3 | 0 | 0 || 0 | 0 | 4 |
给定块(0)应返回List(1),给定块(5)应返回List(7,8,9,1,2)
我的尝试:
((grid.grouped(3).toList(block / 3).map(_.grouped(3).toList(block % 3)))flatten)
并且它有效,但我需要找到一种没有所有这些集合的简单方法
答案 0 :(得分:1)
grid.drop(3 * (block / 3)).take(3).flatMap(_.drop(3 * (block % 3)).take(3)).filter(_ != 0)
这样效率更高 - 直接“缩放”到您想要的数据;坚持列表(没有转换)。
scala> val grid = List(List(0,1,0,0,0,0,0,0,8),
List(0,0,0,2,9,0,5,1,3),
List(0,0,0,7,0,0,0,0,0),
List(0,4,0,5,0,0,7,0,2),
List(0,0,0,4,6,0,9,8,1),
List(3,0,0,1,0,0,0,0,0),
List(0,1,0,5,0,0,4,0,2),
List(0,2,0,0,1,0,0,0,0),
List(0,9,0,3,0,0,0,0,2))
grid: List[List[Int]] = List(List(0, 1, 0, 0, 0, 0, 0, 0, 8), List(0, 0, 0, 2, 9, 0, 5, 1, 3), List(0, 0, 0, 7, 0, 0, 0, 0, 0), List(0, 4, 0, 5, 0, 0, 7, 0, 2), List(0, 0, 0, 4, 6, 0, 9, 8, 1), List(3, 0, 0, 1, 0, 0, 0, 0, 0), List(0, 1, 0, 5, 0, 0, 4, 0, 2), List(0, 2, 0, 0, 1, 0, 0, 0, 0), List(0, 9, 0, 3, 0, 0, 0, 0, 2))
scala> def blockElements(block: Int) = grid.drop(3 * (block / 3)).take(3).flatMap(_.drop(3 * (block % 3)).take(3)).filter(_ != 0)
blockElements: (block: Int)List[Int]
scala> blockElements(0)
res1: List[Int] = List(1)
scala> blockElements(5)
res2: List[Int] = List(7, 2, 9, 8, 1)
顺便说一句:第9个子广场有两个4::)。