Created
January 5, 2015 14:13
-
-
Save dazfuller/6a7ef81313270805408f to your computer and use it in GitHub Desktop.
Lexicographical permutation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func nextPermutation(slice []int) bool { | |
var k int | |
for k = len(slice) - 2; k >= 0; k-- { | |
if slice[k] < slice[k+1] { | |
break | |
} | |
} | |
if k == -1 { | |
return false | |
} | |
var l int | |
for l = len(slice) - 1; l >= 0; l-- { | |
if slice[k] < slice[l] { | |
break | |
} | |
} | |
slice[k], slice[l] = slice[l], slice[k] | |
for i, j := k+1, len(slice)-1; i < j; i, j = i+1, j-1 { | |
slice[i], slice[j] = slice[j], slice[i] | |
} | |
return true | |
} | |
func main() { | |
d := []int{1, 0, 2, 3, 4, 5, 6, 7, 8, 9} | |
fmt.Println(d) | |
t0 := time.Now() | |
for nextPermutation(d) { | |
} | |
fmt.Println(d) | |
t1 := time.Now() | |
fmt.Printf("Time taken: %v\n", t1.Sub(t0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment