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) }