Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active February 11, 2024 14:34
Show Gist options
  • Save benigumocom/1f2d472c747df977b914e33f958fa209 to your computer and use it in GitHub Desktop.
Save benigumocom/1f2d472c747df977b914e33f958fa209 to your computer and use it in GitHub Desktop.
Convert 1D array to 2D array and vice versa, chunk array by n pieces each πŸ‘‰ https://android.benigumo.com/20240211/handle-array/
let d2: [[String]] = [
// x (col) β†’
["あ", "い", "う", "え", "お"],
["か", "き", "く", "け", "こ"],
["さ", "し", "す", "せ", "そ"]
]
print(d2)
// [["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"], ["さ", "し", "す", "せ", "そ"]]
print(d2[0][1])
// い
// β†’ d2[y][x]
// x = 1, y = 0
print(d2[0][1])
// い
// x = 3, y = 2
print(d2[2][3])
// せ
let numCols = d2.first!.count
let numRows = d2.count
print(numCols, numRows) // 5 3
// d2 to d1 *
let d1 = d2.flatMap { $0 }
print(d1)
// ["あ", "い", "う", "え", "お", "か", "き", "く", "け", "こ", "さ", "し", "す", "せ", "そ"]
// index = 1
print(d1[1]) // い
print(d1[0 * numCols + 1]) // い
// index = 13
print(d1[13]) // せ
print(d1[2 * numCols + 3]) // せ
// β†’ index = y * numCols + x
// index = 1
print(d2[1 / numCols][1 % numCols])
// い
// β†’ x = index % numCols
// β†’ y = index / numCols
// index = 13
print(d2[13 / numCols][13 % numCols])
// せ
// い d1(1) d2[0][1] (1, 0)
// せ d1(14) d2[2][3] (3, 2)
// *
// index = y * numCols + x
// x = index % numCols
// y = index / numCols
print(
d1[0 ... 2]
)
// ["あ", "い", "う"]
print(
(0 ..< numRows)
.map {
$0 * numCols
}
.map {
$0 ..< $0 + numCols
}
.map {
d1[$0] // ArraySlice
}
.map {
Array($0)
}
)
// [["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"], ["さ", "し", "す", "せ", "そ"]]
print(
(0 ..< numRows).map {
Array(d1[$0 * numCols ..< ($0 + 1) * numCols])
}
)
// [["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"], ["さ", "し", "す", "せ", "そ"]]
print(
// d1 to d2 *
(0 ..< d1.count / numCols).map {
Array(d1[($0 * numCols) ..< ($0 + 1) * numCols])
}
)
// [["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"], ["さ", "し", "す", "せ", "そ"]]
// chunk by 5 pieces each *
let n = 5
print(
(0 ..< d1.count / n).map {
Array(d1[$0 * n ..< ($0 + 1) * n])
}
)
// [["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"], ["さ", "し", "す", "せ", "そ"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment