我目前正在功能编程中读取数据。我得到了Map [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---
-------------
I need to get:
Something(1,1) - Horizontal
Oats(2,1) - Vertical
Game(9,1) - Vertical
Man(9,3) - Horizontal
我已经通过在地图上构建网格实现了这一目标。然后正则表达式开始起作用。但是,如何在不实现字符串的情况下做到这一点呢?有任何想法吗?
-非常感谢!! ^^
答案 0 :(得分:1)
您的意思是这样的吗? 请注意,我绝不会在生产中使用类似的东西-虽然它是“功能性”的,但效率不高,而且绝对不可读。
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)))