Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: What's the best way to pair up elements of an Array

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)
like image 834
Alexander Avatar asked Nov 28 '16 10:11

Alexander


People also ask

How do you pair elements in an array?

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.

How do you group by the elements of an array in Swift?

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.

Which one is faster array or set in Swift?

Difference between an Array and Set in SwiftArray is faster than set in terms of initialization.

How can you put all the elements of an array in a String?

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(,).


2 Answers

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)

}
like image 115
Martin R Avatar answered Oct 18 '22 04:10

Martin R


This is now available as

Sequence.chunks(ofCount: 2) of the swift-algorithms package

for chunk in input.chunks(ofCount: 2) {
    print(chunk)
}
like image 26
Alexander Avatar answered Oct 18 '22 03:10

Alexander