Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Calculate Partition in Go
package main
import "fmt"
import "sort"
type EMPTY struct {}
var PRESENT EMPTY = EMPTY{}
func partition(val int) []string {
set := make(map[string]EMPTY)
for i := 1; i<=val;i++ {
for _,result := range worker([]int{i},val-i) {
set[fmt.Sprintf("%v",result)]=PRESENT
}
}
out := make([]string,len(set))
pos :=0
for key := range set {
out[pos] = key
pos++
}
sort.Strings(out)
return out
}
func worker(already []int, val int) [][]int {
if val == 0 {
sort.Ints(already)
return [][]int{already}
}
out := [][]int {}
for i := 1;i<=val;i++ {
out = append(out,worker(append(already,i),val-i)...)
}
return out
}
func main() {
for i := 0;i<10;i++ {
result := partition(i)
fmt.Printf("%d (%d): %v\n",i,len(result),result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.