Home > Mobile >  How would I create a function that takes an array and returns a two dimensions array?
How would I create a function that takes an array and returns a two dimensions array?

Time:01-20

I am having problems creating a function that accepts an array and returns a two-dimensional array. An an example like [1,2,3,4,5,6] = [[1,2],[3,4],[5,6]].

So far I only have :

       func spiltArray(numbers:[Int])->[[Int]]{

  }

CodePudding user response:

func spiltArray(numbers:[Int])->[[Int]]{
    var result:[[Int]] = []
    if numbers.count == 0{
        return result
    }
    let split = 2
    var arr:[Int] = []
    for item in numbers{
        if(arr.count>=split){
            result.append(arr)
            arr = []
        }
        arr.append(item)
    }
    result.append(arr)
    return result
}

CodePudding user response:

The best way to accomplish what you want is using Swift type UnfoldSequence (The elements of the sequence are computed lazily) as shown in this post. If you need an array of subsequences you can initialize the unfolded subsequences. If you need an array of arrays you can map the unfolded subsequences initializing a new array for each subsequence:

extension Collection {
    func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
        sequence(state: startIndex) { start in
            guard start < self.endIndex else { return nil }
            let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
            defer { start = end }
            return self[start..<end]
        }
    }
    func subSequences(of n: Int) -> [SubSequence] {
        .init(unfoldSubSequences(limitedTo: n))
    }
    func subArrays(of n: Int) -> [[Element]] {
        unfoldSubSequences(limitedTo: n).map([Element].init)
    }
}

let nums = [1,2,3,4,5,6]
for subSequence in nums.unfoldSubSequences(limitedTo: 2) {
    print(subSequence)
    for element in subSequence {
        print(element)
    }
}

This will print:

[1, 2]
1
2
[3, 4]
3
4
[5, 6]
5
6


If you need the result to be an array of arrays [[Int]]:

let subArrays = nums.subArrays(of: 2)
subArrays  // [[1, 2], [3, 4], [5, 6]]
  •  Tags:  
  • Related