Last active
February 11, 2024 14:34
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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