2

What is the efficient way to convert an array of pixelValues [UInt8] into two dimensional array of pixelValues rows - [[UInt8]]

2
  • 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 ? Commented 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. Commented Sep 9, 2016 at 22:27

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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>?
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".
@VYT, I need to note that indices of ArraySlice does not always start with 0. That may not be what you want.
0

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
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.