Created
May 13, 2012 03:42
-
-
Save jonbodner/2676533 to your computer and use it in GitHub Desktop.
Calculate 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 "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