Home > database >  How to generate combinations of r elements in a given array of size n in swift?
How to generate combinations of r elements in a given array of size n in swift?

Time:12-22

I want total permutation pairs and its count Like. If input array is {1, 2, 3, 4} and r is 2. then output should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.

CodePudding user response:

Actually the total permutation pairs are

[[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]

There's no need to reinvent the wheel. Apple provides a collection of useful and optimized algorithms.

Add the package Swift Algorithms to your project

Then write

import Algorithms

let array = [1, 2, 3, 4]
    
let permutations = array.permutations(ofCount: 2)
print(Array(permutations), permutations.count)

CodePudding user response:

You can store this pairs in an array. Firstly create a structure of your data type

struct MyData {
        var a: Int = 0
        var b: Int = 0
}

Then declare initial empty array

var pairs = [MyData]()
let yourData = [1,2,3,4,5]

Now for storing data you need to run two for loops as-

for i in 0..<yourData.count {
    for j in 0..<yourData.count {
        if i!= j {
            let obj = MyData()
            obj.a = yourData[i]
            obj.b = yourData[j]
            pairs.append(obj)
         }
     }
}

Here pairs is your answer.

pairs.count // Number of combination
  • Related