Created
March 11, 2016 08:38
-
-
Save henryscala/3a5960ec413ac9c75f60 to your computer and use it in GitHub Desktop.
using combination to get a subset of a set of numbers and then calculate whether the sum of the subset equals a specific target
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" | |
"math/big" | |
"os" | |
) | |
var target int = 23813 | |
var totalNum int = 69 | |
var data []int = []int{396, 365, 238, 392, 378, 357, 402, 384, 348, 398, 370, 380, 396, 388, 341, 322, 370, 311, 396, 356, 380, 374, 327, 396, 388, 338, 331, 388, 356, 388, 381, 371, 374, 398, 372, 384, 286, 384, 391, 396, 400, 364, 372, 382, 378, 368, 398, 396, 379, 388, 438, 466, 380, 307, 378, 398, 388, 396, 394, 380, 378, 370, 388, 400, 324, 368, 378, 354, 406} | |
func fac(b int) *big.Int { | |
r := big.NewInt(1) | |
for i := 1; i < b; i++ { | |
adder := big.NewInt(int64(i)) | |
r = r.Mul(r, adder) | |
} | |
return r | |
} | |
func combinationNum(n, m int) *big.Int { | |
r1 := fac(n) | |
r2 := fac(m) | |
r3 := fac(n - m) | |
r := r1.Div(r1, r2) | |
r = r.Div(r, r3) | |
return r | |
} | |
func printAry(a []int) { | |
sum := sumInts(a) | |
if sum == target { | |
fmt.Println("found the target") | |
for i := 0; i < len(a); i++ { | |
fmt.Print(i) | |
fmt.Print(",") | |
} | |
fmt.Println() | |
for i := 0; i < len(a); i++ { | |
fmt.Print(a[i]) | |
fmt.Print(",") | |
} | |
fmt.Println() | |
for i := 0; i < len(a); i++ { | |
fmt.Print(data[a[i]]) | |
fmt.Print(",") | |
} | |
fmt.Println() | |
os.Exit(0) | |
} | |
} | |
func combination(n, r int, proc func([]int)) { | |
var ary []int = make([]int, r) | |
var i, k int | |
for i = 0; i < r; i++ { | |
ary[i] = i | |
} | |
proc(ary) | |
finished := false | |
for !finished { | |
finished = true | |
for i = r - 1; i >= 0; i-- { | |
if ary[i] < i+n-r { | |
ary[i]++ | |
finished = false | |
for k = i + 1; k < r; k++ { | |
ary[k] = ary[k-1] + 1 | |
} | |
proc(ary) | |
break | |
} | |
} | |
} | |
} | |
func sumInts(d []int) int { | |
s := 0 | |
for i := 0; i < len(d); i++ { | |
s += data[d[i]] | |
} | |
return s | |
} | |
func main() { | |
for i := 68; i >= 57; i-- { | |
stepNum := combinationNum(totalNum, i) | |
fmt.Println("working on", i, "this step has", stepNum, "steps") | |
combination(totalNum, i, printAry) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment