I came across a problem that required iterating over an array in pairs. What's the best way to do this? Or, as an alternative, what's the best way of transforming an Array into an Array of pairs (which could then be iterated normally)?
Here's the best I got. It requires output
to be a var
, and it's not really pretty. Is there a better way?
let input = [1, 2, 3, 4, 5, 6]
var output = [(Int, Int)]()
for i in stride(from: 0, to: input.count - 1, by: 2) {
output.append((input[i], input[i+1]))
}
print(output) // [(1, 2), (3, 4), (5, 6)]
// let desiredOutput = [(1, 2), (3, 4), (5, 6)]
// print(desiredOutput)
In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach: Traverse the array and select an element in each traversal.
Let's consider you have an array of fruit names and you want to group them according to their first alphabet. To achieve that we'll use a new initializer from the dictionary, init(grouping:by:) in the Swift. As you can see, the output is Dictionary groping by their first alphabet.
Difference between an Array and Set in SwiftArray is faster than set in terms of initialization.
To join the array elements we use arr. join() method. This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,).
You can map the stride instead of iterating it, that allows to get the result as a constant:
let input = [1, 2, 3, 4, 5, 6]
let output = stride(from: 0, to: input.count - 1, by: 2).map {
(input[$0], input[$0+1])
}
print(output) // [(1, 2), (3, 4), (5, 6)]
If you only need to iterate over the pairs and the given array is large then it may be advantageous to avoid the creation of an intermediate array with a lazy mapping:
for (left, right) in stride(from: 0, to: input.count - 1, by: 2)
.lazy
.map( { (input[$0], input[$0+1]) } ) {
print(left, right)
}
This is now available as
Sequence.chunks(ofCount: 2)
of the swift-algorithms
package
for chunk in input.chunks(ofCount: 2) {
print(chunk)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With