Created
May 16, 2018 13:58
-
-
Save toVersus/56de31d8330fc13fb7aa30238170bea5 to your computer and use it in GitHub Desktop.
Find maximum element of slice in the specified range
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 main() { | |
a := []int{5, 3, 3, 4, 5} | |
fmt.Println(findMaximum(a, 0, 4)) | |
} | |
func findMaximum(A []int, left, right int) int { | |
mid := (left + right) / 2 | |
if left == right-1 { | |
return A[left] | |
} | |
u := findMaximum(A, left, mid) | |
v := findMaximum(A, mid, right) | |
return max(u, v) | |
} | |
func max(a, b int) int { | |
if a > b { | |
return a | |
} | |
return b | |
} |
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 ( | |
"reflect" | |
"testing" | |
) | |
var findMaximumTests = []struct { | |
name string | |
a []int | |
left int | |
right int | |
want int | |
}{ | |
{ | |
name: "should return maximum value from full range of slice", | |
a: []int{5, 3, 2, 10, 14, 20}, | |
left: 0, | |
right: 6, | |
want: 20, | |
}, | |
{ | |
name: "should return maximum value from adjacent elements of slice", | |
a: []int{5, 3, 2, 10, 14, 20}, | |
left: 1, | |
right: 2, | |
want: 3, | |
}, | |
} | |
func TestFindMaximum(t *testing.T) { | |
for _, testcase := range findMaximumTests { | |
t.Log(testcase.name) | |
if result := findMaximum(testcase.a, testcase.left, testcase.right); !reflect.DeepEqual(result, testcase.want) { | |
t.Errorf("result => %#v\n, want => %#v", result, testcase.want) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment