Calculate all permutations of a string in Swift

后端 未结 8 1349
余生分开走
余生分开走 2020-12-03 03:28

For the string \"ABC\" the code snippet below calculates 5 of the 6 total permutations. My strategy was to insert each character at each index possible index. B

8条回答
  •  爱一瞬间的悲伤
    2020-12-03 03:58

    You can use the functions of this framework to calculate permutations and combinations both with repetition and without repetition. You can investigate the source code and compare with your own.

    https://github.com/amirrezaeghtedari/AECounting

    This library calculates the results based on lexicographic order. For example the result of permutation 3 items out of 5 items are same as below:

    let result = Permutation.permute(n: 5, r: 3)
    
    //result
    //[
    // [1, 2, 3],
    // [1, 2, 4],
    // [1, 2, 5],
    //  ...,
    // 5, 4, 3]
    //].
    

    You can easily assign your problem items to 1 to n numbers in the result array.

    In case of your problem, you should call:

    let result = Permutation.permute(n: 3, r: 3)
    

提交回复
热议问题