Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created December 8, 2021 17:04
Show Gist options
  • Save kgaughan/70c0d38fb998364381802f49bbc2273e to your computer and use it in GitHub Desktop.
Save kgaughan/70c0d38fb998364381802f49bbc2273e to your computer and use it in GitHub Desktop.

Revisions

  1. kgaughan created this gist Dec 8, 2021.
    27 changes: 27 additions & 0 deletions permute.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    package permute

    func fact(n int) int {
    result := 1
    for i := 1; i <= n; i++ {
    result *= i
    }
    return result
    }

    func permute(chars string) []string {
    result := make([]string, 0, fact(len(chars)))
    generate(&result, []rune(chars), 0, len(chars)-1)
    return result
    }

    func generate(result *[]string, acc []rune, left, right int) {
    if left == right {
    *result = append(*result, string(acc))
    } else {
    for i := left; i <= right; i++ {
    acc[left], acc[i] = acc[i], acc[left]
    generate(result, acc, left+1, right)
    acc[left], acc[i] = acc[i], acc[left]
    }
    }
    }