In the maximum exercise we created a max function that works on a slice of integers. The question now is to create a program that shows the maximum number and that works for both integers and floats. Try to make your program as generic as possible, although that is quite difficult in this case.
My implicit reading of that was the program should work on a slice of integers and a slice of floats, i.e. the reader should generalise their previous solution to floats too.
However, the solution currently in the text just compares two values.
For reference, code I wrote for it:
package main
import "fmt"
type sI []int
type sF []float64
type Greater interface {
Greater(int, int) bool
Len() int
Value(int) interface{}
}
func (s sI) Greater(i int, j int) bool {
return s[i] > s[j]
}
func (s sI) Len() int {
return len(s)
}
func (s sI) Value(i int) interface{} {
return s[i]
}
func (s sF) Greater(i int, j int) bool {
return s[i] > s[j]
}
func (s sF) Len() int {
return len(s)
}
func (s sF) Value(i int) interface{} {
return s[i]
}
func findMax(g Greater) interface{} {
max_index := 0
for i := 1; i < g.Len(); i++ {
if g.Greater(i, max_index) {
max_index = i
}
}
return g.Value(max_index)
}
func main() {
s := sI{850, 5, 843, -6, 7, 16, 842}
fmt.Println("Maximum of", s, "is", findMax(s))
f := sF{5.5, 13.223, 2.1, -6.4, 843.958}
fmt.Println("Maximum of", f, "is", findMax(f))
}
This solution has a similar structure to the proposed solution for the first max() question. It also has the advantage that it follows a similar pattern to that alluded to earlier in the chapter for bubble sorting.
Happy to submit a PR, but thought it worth asking what the fix should be: change the question text or the solution?
The problem is phrased as:
My implicit reading of that was the program should work on a slice of integers and a slice of floats, i.e. the reader should generalise their previous solution to floats too.
However, the solution currently in the text just compares two values.
For reference, code I wrote for it:
This solution has a similar structure to the proposed solution for the first max() question. It also has the advantage that it follows a similar pattern to that alluded to earlier in the chapter for bubble sorting.
Happy to submit a PR, but thought it worth asking what the fix should be: change the question text or the solution?