Created
May 7, 2012 17:03
-
-
Save jonbodner/2628990 to your computer and use it in GitHub Desktop.
Even-Odd Partition in Go
This file contains 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" | |
import "math/rand" | |
import "time" | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
vals := rand.Perm(10) | |
fmt.Println(vals) | |
makeEvenFirst(vals) | |
fmt.Println(vals) | |
} | |
func makeEvenFirst(vals []int) { | |
back := nextBack(len(vals)-1, vals) | |
for i := 0; i < back; i++ { | |
v := vals[i] | |
fmt.Println(v) | |
if v%2 != 0 { | |
fmt.Printf("swapping %d and %d\n", v, vals[back]) | |
vals[i] = vals[back] | |
vals[back] = v | |
back = nextBack(back-1, vals) | |
} | |
} | |
} | |
func nextBack(back int, vals []int) int { | |
for back > 0 { | |
if vals[back]%2 != 0 { | |
back-- | |
} else { | |
break | |
} | |
} | |
return back | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment