Created
June 12, 2024 09:15
-
-
Save saayv1/7a9a8c30f28c824b519a12507b348346 to your computer and use it in GitHub Desktop.
Write a function thattakes an array of integers and a target sum, and returns allthe unique quadruplets [a,b,c,d] such that a+b+c+d= 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" | |
"slices" | |
) | |
// I hacked this. I am trying to learn go, still figuring out arrays and slices | |
var globalSolution map[[4]int]bool | |
func main() { | |
fmt.Println("Hello") | |
l := []int{1,-2,-5,-4,-3,3,3,5} | |
target := -11 | |
solve(l, target) | |
m := []int{1,0,-1,0,-2,2} | |
target = 0 | |
solve(m,target) | |
o := []int{} | |
target = 0 | |
solve(o,target) | |
} | |
// priliminary input check, then print solution | |
func solve(sample []int, target int) { | |
globalSolution = make(map[[4]int]bool) | |
var arr []int | |
if(len(sample)<4) { | |
fmt.Printf("solution for : %d\n", sample) | |
fmt.Println(arr) | |
return | |
} | |
slices.Sort(sample) | |
f(sample[0],sample[1],sample[2],sample[3],sample[4:],target) | |
if(len(globalSolution) == 0){ | |
fmt.Printf("solution for : %d\n", sample) | |
fmt.Println(arr) | |
} else { | |
fmt.Printf("solution for : %d\n", sample) | |
for k := range(globalSolution) { | |
fmt.Println(k) | |
} | |
} | |
fmt.Println() | |
} | |
// a recursive function which takes in a combination of 4 values in the sample array | |
// along with the remaining sample and target. | |
// if the solution ain't a+b+c+d, then recursively look for the solution by replacing | |
// a,b,c and d with the next available value | |
// if there isn't one, then we stop | |
// if there is, save to global solution | |
func f(a int, b int, c int, d int, arr []int, target int) bool { | |
if a+b+c+d == target{ | |
sol := []int{a,b,c,d} | |
var arr [4]int | |
slices.Sort(sol) | |
copy(arr[:],sol) | |
globalSolution[arr] = true | |
} | |
if(len(arr) == 0) { | |
return false; | |
} | |
e := arr[0] | |
if(len(arr)==1) { | |
arr = []int{} | |
} else { | |
arr = arr[1:] | |
} | |
return f(a,b,c,e,arr,target) || f(a,b,e,d,arr,target) || f(a,e,c,d,arr,target) || f(e,b,c,d,arr,target) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment