What is the efficient way to convert an array of pixelValues [UInt8] into two dimensional array of pixelValues rows - [[UInt8]]
-
You want to append arrays into an multidimensional one [[UInt8]] or split the original array [UInt8] into smaller arrays that represent rows? if so, what is the rule to split it ?Jans– Jans2016-09-09 22:21:49 +00:00Commented Sep 9, 2016 at 22:21
-
@xhamr I want to make (from an array of pixelxValues [UInt8] of Image) a two-dimensional array where each element is pixelRow (i.e. [UInt8] ) from array of pixelxValues [UInt8] of Image.VYT– VYT2016-09-09 22:27:15 +00:00Commented Sep 9, 2016 at 22:27
Add a comment
|
2 Answers
You can write something like this:
var pixels: [UInt8] = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15]
let bytesPerRow = 4
assert(pixels.count % bytesPerRow == 0)
let pixels2d: [[UInt8]] = stride(from: 0, to: pixels.count, by: bytesPerRow).map {
Array(pixels[$0..<$0+bytesPerRow])
}
But with the value semantics of Swift Arrays, all attempt to create new nested Array requires copying the content, so may not be "efficient" enough for your purpose.
Re-consider if you really need such nested Array.
3 Comments
VYT
I have an array of pixelValues [UInt8] and have tried convert it using map, and end up with [ArraySlice<UInt8>] instead of [[UInt8]]. Does it make sense to use ArraySlice<UInt8>?
OOPer
ArraySlice is also a value type, but its copy-on-write feature would save some copying cost in some cases, all the same in some other cases. Depends on how you use that "2d-array".OOPer
@VYT, I need to note that indices of
ArraySlice does not always start with 0. That may not be what you want.This should work
private func convert1Dto2DArray(oneDArray:[String], stringsPerRow:Int)->[[String]]?{
var target = oneDArray
var outOfIndexArray:[String] = [String]()
let reminder = oneDArray.count % stringsPerRow
if reminder > 0 && reminder <= stringsPerRow{
let suffix = oneDArray.suffix(reminder)
let list = oneDArray.prefix(oneDArray.count - reminder)
target = Array(list)
outOfIndexArray = Array(suffix)
}
var array2D: [[String]] = stride(from: 0, to: target.count, by: stringsPerRow).map {
Array(target[$0..<$0+stringsPerRow])}
if !outOfIndexArray.isEmpty{
array2D.append(outOfIndexArray)
}
return array2D
}