13

Given an array of any kind and the wanted number of subarray, i need this output :

print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3))
// [[0, 3, 6], [1, 4], [2, 5]]

Output must contain the correct number of subarrays even if there is not "enough" elements to fill those :

print([0, 1, 2].splitInSubArrays(into: 4))
// [[0], [1], [2], []]

I have this working implementation for now but is there a better (more elegant) way of achieving this output :

extension Array {

    func splitInSubArrays(into size: Int) -> [[Element]] {

        var output: [[Element]] = []

        (0..<size).forEach {

            var subArray: [Element] = []

            for elem in stride(from: $0, to: count, by: size) {
                subArray.append(self[elem])
            }

            output.append(subArray)
        }

        return output
    }
}
1
  • Do note that all you're doing is: sorting by remainder. You can actually get these instantly by dividing. (If relevant, you don't need to actually make the three arrays!)
    – Fattie
    Nov 20, 2020 at 17:52

5 Answers 5

20

You can replace both loops with a map() operation:

extension Array {
    func splitInSubArrays(into size: Int) -> [[Element]] {
        return (0..<size).map {
            stride(from: $0, to: count, by: size).map { self[$0] }
        }
    }
}

The outer map() maps each offset to the corresponding array, and the inner map() maps the indices to the array elements.

Examples:

print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3))
// [[0, 3, 6], [1, 4], [2, 5]]

print([0, 1, 2].splitInSubArrays(into: 4))
// [[0], [1], [2], []]
5
  • 1
    Well done. I was scratching my head trying to figure out what the OP was trying to do, and you came up with a simple, elegant solution. (Voted)
    – Duncan C
    Nov 20, 2020 at 16:42
  • 1
    This is beautiful, so obvious now :)
    – Manel
    Nov 20, 2020 at 17:46
  • @Manel in algorithms, % is your friend :)
    – Fattie
    Nov 20, 2020 at 17:48
  • Hey @Fattie, sorry but what is "%" ? :)
    – Manel
    Nov 20, 2020 at 17:52
  • 2
    ah, I just mean "remainder".
    – Fattie
    Nov 20, 2020 at 17:55
6

Just for fun a generic implementation that would work with strings as well:

extension Collection {
    func every(n: Int, start: Int = 0) -> UnfoldSequence<Element,Index> {
        sequence(state: dropFirst(start).startIndex) { index in
            guard index < endIndex else { return nil }
            defer { index = self.index(index, offsetBy: n, limitedBy: endIndex) ?? endIndex }
            return self[index]
        }
    }
}

extension RangeReplaceableCollection {
    func splitIn(subSequences n: Int) -> [SubSequence] {
        (0..<n).map { .init(every(n: n, start: $0)) }
    }
}

[0, 1, 2, 3, 4, 5, 6].splitIn(subSequences: 3)   // [[0, 3, 6], [1, 4], [2, 5]]
[0, 1, 2].splitIn(subSequences: 4)               // [[0], [1], [2], []]
"0123456".splitIn(subSequences: 3)               // ["036", "14", "25"]
6

KISS, algorithm-matching approach:

The most intuitive way to do this is dead simple:

  • for each index
  • get the remainder when dividing by three
  • put the number in that array

So it's really nothing more than this:

arrays[i%n].append(item i)

Example code per @LeoDabus comment below

extension RangeReplaceableCollection {
    func moduloishtrancheization(n: Int) -> [SubSequence] {
        var r: [SubSequence] = .init(repeating: .init(), count: n)
        var i = 0
        forEach {
            r[i%n].append($0)
            i += 1
        }
        return r
    }
}

That's the whole thing.

6
  • 1
    extension RangeReplaceableCollection { func splitIn(subSequences n: Int) -> [SubSequence] { var result: [SubSequence] = .init(repeating: .init(), count: n) var index = 0 forEach { result[index%n].append($0) index += 1 } return result } }
    – Leo Dabus
    Nov 20, 2020 at 18:35
  • I'm not sure if this “remainder method” would be more efficient than OP's, Leo's, and my approach which only repeatedly add a fixed number to the offsets. But – as you said – it probably does not matter.
    – Martin R
    Nov 20, 2020 at 18:41
  • MartinR, regarding efficiency in Swift I'm afraid I have all-but no idea of how very complex structures / operations like sequences, subsequences, appending, slicing, striding etc operate in Swift. So, I have absolutely no clue.
    – Fattie
    Nov 20, 2020 at 18:50
  • @Fattie Feel free to edit your question and post it to your answer
    – Leo Dabus
    Nov 20, 2020 at 18:57
  • good call @LeoDabus You know, I've often wondered if there's a way to get "that" index when you "$0" idiom (in the example, the clumsy "var i" would disappear and it would be something like result[$0.magicIndex % n].append .. )
    – Fattie
    Nov 20, 2020 at 19:47
5

For completeness, here's a reduce-based solution that works on all Collection types:

extension Collection {
    func splitInSubArrays(_ size: Int) -> [[Element]] {
        enumerated().reduce(into: [[Element]](repeating: [], count: size)) {
            $0[$1.offset % size].append($1.element)
        }
    }
}

How the function works: it creates a an empty array of [Element] entries, and appends each element of the original array to the corresponding sub-array. We're using here of reduce just to carry the result array, to avoid explicitly creating a local variable (though internally reduce is doing that for us).

Usage:

print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(3)) // [[0, 3, 6], [1, 4], [2, 5]]
print([0, 1, 2].splitInSubArrays(4))             // [[0], [1], [2], []]
print("ABCDEF".splitInSubArrays(3))              // ["A", "D"], ["B", "E"], ["C", "F"]]

Note that, as Leo Dabus pointed out, in the last example above the 2-D array is not a string-based one, it's a 2-D character array [[Character]]. To generate a array of substrings instead, RangeReplaceableCollection can be extended, and the result type can be changed to [SubSequence].

16
  • This is exactly what has been suggested by Fattie
    – Leo Dabus
    Nov 20, 2020 at 18:41
  • @LeoDabus I don't know how to reply to this, are you implying I plagiarised other's answer?
    – Cristik
    Nov 20, 2020 at 18:43
  • I just said he did not provided the code but suggested this approach
    – Leo Dabus
    Nov 20, 2020 at 18:44
  • 1
    ( @Cristik - I'm pretty sure L.D. was just noting "Ah, this is the algorithm Fattie mentioned. ) Please note that it is the overwhelmingly common way to do this (you often see it in game-related code for example )
    – Fattie
    Nov 20, 2020 at 18:44
  • 1
    @Fattie depending on the drinks :)
    – Cristik
    Nov 20, 2020 at 18:44
5

'Twould be good to allow it to be used on all sequences.

stride(from: 0, through: 6, by: 1).splitInSubArrays(into: 3)

(Put this into a public extension too, if it's useful across many apps, like the one below is.)

extension Sequence {
  func splitInSubArrays(into size: Int) -> [[Element]] {
    enumerated()
      .grouped { $0.offset % size }
      .map { $0.map(\.element) }
  }
}
  /// Group the elements by a transformation into an `Equatable`.
  /// - Note: Similar to `Dictionary(grouping values:)`,
  /// but preserves "key" ordering, and doesn't require hashability.
  func grouped<Equatable: Swift.Equatable>(
    by equatable: (Element) throws -> Equatable
  ) rethrows -> [[Element]] {
    try reduce(into: [(equatable: Equatable, elements: [Element])]()) {
      let equatable = try equatable($1)

      if let index = ( $0.firstIndex { $0.equatable == equatable } ) {
        $0[index].elements.append($1)
      } else {
        $0.append((equatable, [$1]))
      }
    }.map(\.elements)
  }
10
  • indeed, you just group by remainder
    – Fattie
    Nov 20, 2020 at 18:20
  • Jessy, I may misunderstand, but why would you sort? In any situation I can think of where you do this, you surely want to maintain the original order seen in the original array? Sorry if I misunderstand
    – Fattie
    Nov 20, 2020 at 18:23
  • The Dictionary initializer is Swift's only built-in grouping algorithm, but although the values will keep their order, the key-value-pairs are unordered.
    – Jessy
    Nov 20, 2020 at 18:25
  • "The Dictionary initializer is Swift's only built-in grouping algorithm" got it, thanks .. but .. I'm too stupid to understand: in fact, would the resulting child arrays, have the values in the same order as seen in the original array? thx :O
    – Fattie
    Nov 20, 2020 at 18:27
  • 😸 Yes, but it's not actually guaranteed. You can go to GitHub and see the algorithm, which does preserve ordering in the value arrays.
    – Jessy
    Nov 20, 2020 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.