gpt4 book ai didi

kotlin - 在Kotlin中存储String网格的最佳数据结构是什么?

转载 作者:行者123 更新时间:2023-12-02 13:03:26 25 4
gpt4 key购买 nike

存储这样的String网格的最佳数据结构是什么?如何将String简洁地转换为该数据类型?
"""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)

关于kotlin - 在Kotlin中存储String网格的最佳数据结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62277382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com