Created
May 14, 2015 10:51
-
-
Save vikashvikram/e29261f4e9378ad79011 to your computer and use it in GitHub Desktop.
Get all combinations of a given number of items from an array of int64 items (can type as per your requirement).
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" | |
) | |
func GetAllSubsets(arr []int64, size int) [][]int64{ | |
if len(arr) == size { | |
result := [][]int64{arr} | |
return result | |
} else if len(arr) > size && size > 0 { | |
sub_arr := arr[1:] | |
first_element := arr[0] | |
complete_subset_arr := GetAllSubsets(sub_arr, size) | |
partial_subset_arr := GetAllSubsets(sub_arr, size-1) | |
for _, i := range partial_subset_arr { | |
if len(i) != 0 { | |
new_slice := []int64{first_element} | |
new_slice = append(new_slice, i...) | |
complete_subset_arr = append(complete_subset_arr, new_slice) | |
} | |
} | |
if size == 1 { | |
complete_subset_arr = append(complete_subset_arr, []int64{first_element}) | |
} | |
return complete_subset_arr | |
} else { | |
result := [][]int64{} | |
return result | |
} | |
} | |
func main() { | |
arr := []int64{1,2,3,4,5} | |
combinations := GetAllSubsets(arr, 4) | |
for _, i := range combinations { | |
fmt.Println("====",i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment