Scala在给定符号及其位置的地图时查找水平和垂直单词
我目前正在读函数式编程中的数据。给我一张地图[Vec2,Char],我必须提取水平和垂直单词。坐标从左上方开始。示例输入可以如下所示:Scala在给定符号及其位置的地图时查找水平和垂直单词,scala,parsing,dictionary,Scala,Parsing,Dictionary,我目前正在读函数式编程中的数据。给我一张地图[Vec2,Char],我必须提取水平和垂直单词。坐标从左上方开始。示例输入可以如下所示: All data is in form of Map[Vec2, Char] For example we have our Map info like this: '-' means empty space here ------------- -SOMETHING--- --A------A--- --T------MAN- --S------E--- --
All data is in form of Map[Vec2, Char]
For example we have our Map info like this:
'-' means empty space here
-------------
-SOMETHING---
--A------A---
--T------MAN-
--S------E---
-------------
I need to get:
Something(1,1) - Horizontal
Oats(2,1) - Vertical
Game(9,1) - Vertical
Man(9,3) - Horizontal
我通过在地图上构建一个网格来实现这一点。然后正则表达式开始发挥作用。但是,在不实现字符串的情况下,如何做到这一点呢?有什么想法吗
-非常感谢你^^ 你的意思是这样的吗? 请注意,我永远不会在生产中使用这样的东西——虽然它是“功能性的”,但它效率低下,而且绝对不可读
val in = Map[(Int, Int), Char](
(1, 1) -> 'S',
(1, 2) -> 'O',
(1, 3) -> 'M',
(1, 4) -> 'T',
(1, 5) -> 'H',
(1, 6) -> 'I',
(1, 7) -> 'N',
(1, 8) -> 'G',
(2, 2) -> 'A',
(3, 2) -> 'T',
(4, 2) -> 'S',
(2, 8) -> 'A',
(3, 8) -> 'M',
(4, 8) -> 'E',
(3, 9) -> 'A',
(3,10) -> 'N',
).toList
val rows = in.map(entry => entry._1._1 -> (entry._1._2 -> entry._2)).groupBy(_._1).mapValues(_.map(_._2).sorted)
val cols = in.map(entry => entry._1._2 -> (entry._1._1 -> entry._2)).groupBy(_._1).mapValues(_.map(_._2).sorted)
def groupWords(charsAndOffsets: List[(Int, Char)]): List[(Int, String)] = charsAndOffsets.foldLeft(List.empty[(Int, String)]) {
case (Nil, (col, char)) =>
List(col -> char.toString)
case ((lastCol, lastWord) :: prevWords, (col, char)) if lastCol + lastWord.length == col =>
(lastCol, lastWord + char) :: prevWords
case ((lastCol, lastWord) :: prevWords, (col, char)) =>
(col, char.toString) :: (lastCol, lastWord) :: prevWords
}.filter(_._2.length > 1)
val wordsInRows = rows.mapValues(groupWords).filter(_._2.nonEmpty)
val wordsInCols = cols.mapValues(groupWords).filter(_._2.nonEmpty)
println(wordsInRows)
println(wordsInCols)
程序按如下方式打印行中的单词和cols中的单词:
Map(1 -> List((1,SOMTHING)), 3 -> List((8,MAN)))
Map(2 -> List((1,OATS)), 8 -> List((1,GAME)))
是的,这个任务看起来很傻,但这只是一个练习。谢谢你的解决方案,我会去看看^^