GO   131
Leonardo Christofer
Guest on 9th May 2022 08:49:18 AM

1. package main
2.
3. import "fmt"
4.
5. // Given an array of Integers, create a function to tell whether there is a pair of any integers that summed up to Q.
6.
7. // - The function should receive an array of integers and integer Q
8. // - The function shall return `true` if there is a pair that summed up to Q, return `false` otherwise
9.
10. // Example
11.
12. // arr: []int{1, 2, 4, 7}
13.
14. // when Q == 3 then true
15. // when Q == 4 then false
16. // when Q == 5 then true
17. // when Q == 6 then true
18. // when Q == 7 then false
19. // when Q == 8 then true
20. // when Q == 9 then true
21. // when Q == 10 then false
22.
23. func main() {
24.         arr := []int{1, 2, 4, 7}
25.         q := []int{3, 4, 5, 6, 7, 8, 9, 10}
26.
27.         for _, i := range q {
28.                 havePair := solution(arr, i)
29.
30.                 fmt.Printf("when Q == %d then %t\n", i, havePair)
31.         }
32. }
33.
34. func solution(arr []int, q int) bool {
36.         temp := 0
37.         ok := true
38.         for idx := range arr {
39.                 temp += arr[idx]
40.                 if temp == q {
41.                         ok = true
42.                         temp = 0
43.                         break
44.                 } else {
45.                         ok = false
46.                 }
47.         }
48.         if !ok {
49.                 return false
50.         } else {
51.                 return true
52.         }
53. }

Raw Paste

or to edit or fork this paste. It's free.