What's an optimal data structure to store a String grid like this one and how to concisely convert the String into that data type?
"""10 15 20 11
14 19 04 10
18 63 92 68"""
I want to have easy access to any number from the grid by using a pair of coordinates.
You could use list of lists like this:
val grid: List<List<String>> = listOf(
listOf("10", "15", "20"),
listOf("14", "19", "04"),
listOf("18", "63", "92")
)
val elem = grid[1][1]
You also could write your own extension function and use it with pairs:
fun List<List<String>>.get(i: Pair<Int, Int>) = this[i.first][i.second]
val element = grid.get(1 to 1)
Update
You could create list of lists from string with this helper extension function:
fun String.asGrid(size: Int): List<List<String>> = split(" ", "\n").chunked(size)
In this case at first we split our string to separate numbers and get collection of strings List<String>
. And after this we chunk this list to get List<List<String>>
Usage:
val grid = """10 15 20 11
14 19 04 10
18 63 92 68""".asGrid(4)