Full permutation implementation of Golang permutation algorithm problem

  • 2020-06-01 10:01:33
  • OfStack

In this paper, an example of Golang permutation algorithm is presented. I will share it with you for your reference as follows:

[permutation and combination problem]

1 altogether N trains (0 < N < 10), each train is numbered 1-9, and the train's outbound serial number is required to be output in lexicographical order.

Input:

Including N positive integers (0) < N < 10), which ranges from 1 to 9. The Numbers are separated by Spaces. The first part of the string does not contain Spaces.

Output:

Output the lexicographical train outbound sequence number, each number separated by a space, each output sequence line feed.

Sample input:

1 2 3

Sample output:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Code implementation:

package huawei
import (
    "fmt"
    "sort"
    "strings"
)
func Test7Base() {
    in := "5 2 3"
    result := outOrder(strings.Fields(in))
    dictSort(result)
    s := format(result)
    fmt.Println(s)
}
// The input trainsNums , returns all permutations
// Such as the input [1 2 3] , the return [123 132 213 231 312 321]
func outOrder(trainsNums []string) []string {
    COUNT := len(trainsNums)
    // check
    if COUNT == 0 || COUNT > 10 {
        panic("Illegal argument. trainsNums size must between 1 and 9.")
    }
    // If only 1 The number is directly returned
    if COUNT == 1 {
        return []string{trainsNums[0]}
    }
    // Otherwise, it will be the last 1 Number inserted into all positions in the preceding permutation number (recursion)
    return insert(outOrder(trainsNums[:COUNT-1]), trainsNums[COUNT-1])
}
func insert(res []string, insertNum string) []string {
    // Save the result slice
    result := make([]string, len(res)*(len(res[0])+1))
    index := 0
    for _, v := range res {
        for i := 0; i < len(v); i++ {
            // in v Each of the 1 Two elements are inserted in front of each other
            result[index] = v[:i] + insertNum + v[i:]
            index++
        }
        // in v Backmost insertion
        result[index] = v + insertNum
        index++
    }
    return result
}
// Sort in lexicographical order
func dictSort(res []string) {
    sort.Strings(res)
}
// Output in the specified format
func format(res []string) string {
    strs := make([]string, len(res))
    for i := 0; i < len(res); i++ {
        strs[i] = addWhiteSpace(res[i])
    }
    return strings.Join(strs, "\n")
}
// Add a space
func addWhiteSpace(s string) string {
    var retVal string
    for i := 0; i < len(s); i++ {
        retVal += string(s[i])
        if i != len(s)-1 {
            retVal += " "
        }
    }
    return retVal
}

I hope this article has been helpful to you in the programming of Go language.


Related articles: