【发布时间】:2020-06-09 07:37:27
【问题描述】:
存储这样的字符串网格的最佳数据结构是什么,以及如何简洁地将字符串转换为该数据类型?
"""10 15 20 11
14 19 04 10
18 63 92 68"""
我想通过使用一对坐标轻松访问网格中的任何数字。
【问题讨论】:
标签: kotlin grid coordinates data-storage
存储这样的字符串网格的最佳数据结构是什么,以及如何简洁地将字符串转换为该数据类型?
"""10 15 20 11
14 19 04 10
18 63 92 68"""
我想通过使用一对坐标轻松访问网格中的任何数字。
【问题讨论】:
标签: kotlin grid coordinates data-storage
您可以使用lineSequence 和split 将每一行读取为使用“”(空格分隔符)的字符串:
例子:
val str =
"""
10 15 20 11
14 19 04 10
18 63 92 68
""".trimIndent() // remove extra indents.
val list = str.lineSequence()
.map { it.split(" ") /*.toInt()*/ } // performs intermediate operation (isn't done yet)
.toList() // performs terminal operation (performing map, and then convert to list)
println(list) // prints: [[10, 15, 20, 11], [14, 19, 04, 10], [18, 63, 92, 68]]
【讨论】:
您可以使用list 的列表,如下所示:
val grid: List<List<String>> = listOf(
listOf("10", "15", "20"),
listOf("14", "19", "04"),
listOf("18", "63", "92")
)
val elem = grid[1][1]
您也可以编写自己的extension function 并将其与pairs 一起使用:
fun List<List<String>>.get(i: Pair<Int, Int>) = this[i.first][i.second]
val element = grid.get(1 to 1)
更新
您可以使用此辅助扩展函数从字符串创建列表列表:
fun String.asGrid(size: Int): List<List<String>> = split(" ", "\n").chunked(size)
在这种情况下,首先我们 split 我们的字符串来分隔数字并获取字符串集合 List<String>。在这之后我们chunk这个列表得到List<List<String>>
用法:
val grid = """10 15 20 11
14 19 04 10
18 63 92 68""".asGrid(4)
【讨论】:
grid.split("\n").map { line -> line.split(" ").map { nr -> Integer.parseInt(nr) } }
在这里,您首先将输入分成几行(得到一个字符串列表),然后映射每个商店列表以按空格分隔它们。然后你可以解析里面的每一个字符串,把它们解析成一个整数。这导致最后变成一个整数列表。
您可能想要更改确切的解析以支持更多选项(例如拆分所有空格)或解析为不同的类型。
【讨论】: