Home > Backend Development > Golang > How to Generate All Permutations of a List in Go?

How to Generate All Permutations of a List in Go?

Patricia Arquette
Release: 2024-12-05 15:20:10
Original
731 people have browsed it

How to Generate All Permutations of a List in Go?

Permutations in Go: An In-Depth Guide

This article discusses the different ways to generate all possible permutations of a list of elements in Go.

One common method is Heap's algorithm, which generates each permutation from the previous one by swapping a pair of elements. The following Go function implements this algorithm:

func permutations(arr []int)[][]int{
    var helper func([]int, int)
    res := [][]int{}

    helper = func(arr []int, n int){
        if n == 1{
            tmp := make([]int, len(arr))
            copy(tmp, arr)
            res = append(res, tmp)
        } else {
            for i := 0; i < n; i++{
                helper(arr, n - 1)
                if n % 2 == 1{
                    tmp := arr[i]
                    arr[i] = arr[n - 1]
                    arr[n - 1] = tmp
                } else {
                    tmp := arr[0]
                    arr[0] = arr[n - 1]
                    arr[n - 1] = tmp
                }
            }
        }
    }
    helper(arr, len(arr))
    return res
}
Copy after login

To use this function, simply pass in a slice of integers and it will return a slice of all the permutations of the input list. For example:

arr := []int{1, 2, 3}
fmt.Println(permutations(arr))
Copy after login

Another method of generating permutations is to use the factorial number system. This method allows for the quick generation of the nth lexicographical permutation. For more information on this method, refer to the "Permutation" section in the article above.

By implementing these methods, you can easily generate permutations in Go for use in a variety of applications.

The above is the detailed content of How to Generate All Permutations of a List in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template