gpt/2025-12-10/sorting_letters_heaps.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
package main
import (
"bufio"
"os"
)
func letterSlice(n int) []byte {
if n <= 0 {
return []byte{}
}
if n > 26 {
n = 26
}
res := make([]byte, n)
for i := 0; i < n; i++ {
res[i] = 'a' + byte(i)
}
return res
}
// Iterative Heap's algorithm with fast buffered output.
func permuteIterative(nums []byte, w *bufio.Writer) {
n := len(nums)
if n == 0 {
return
}
// c is the control array for Heap's algorithm.
c := make([]int, n)
// Helper to write one permutation.
writePerm := func() {
w.Write(nums)
w.WriteByte('\n')
}
// Print the first permutation (initial order).
writePerm()
i := 0
for i < n {
if c[i] < i {
var swapIdx int
if i%2 == 0 {
swapIdx = 0
} else {
swapIdx = c[i]
}
// Swap
nums[swapIdx], nums[i] = nums[i], nums[swapIdx]
// Print next permutation
writePerm()
c[i]++
i = 0
} else {
c[i] = 0
i++
}
}
}
func main() {
// Hardcode length 10: a..j
nums := letterSlice(10)
// Buffered writer for much faster output than fmt.Printf in a tight loop.
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
permuteIterative(nums, w)
}
|