Search code examples
swiftpermutation

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


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}.


Solution

  • 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)