How can i get the max value from several values?

i wanna get the value of the largest age from the patients ,

package main

import (
  "fmt"
  "math"
  //"reflect"
)

type patient_details struct {
  name string
  age int
  gender string
}

func main() {
  var patient1 = patient_details{"Jack", 22, "male"}
  var patient2 = patient_details{"Daniel", 34, "male"}
  var patient3 = patient_details{"Sarah", 12, "female"}
  var patient4 = patient_details{"Superman", 52, "male"}

  fmt.Println("who is the oldest patient in our hospital?")

  var oldest_patient = math.Max(patient1.age, patient2.age, patient3.age, patient4.age)

  fmt.Println(oldest_patient)

}

i tried max but it only works for 2 float64 vars , so any ideas ??

thank you

You can find largest and smallest by sorting age in an array.

package main

import (
	"fmt"
	"sort"
	//"reflect"
)

type patient_details struct {
	name   string
	age    int
	gender string
}

func main() {
	var patient1 = patient_details{"Jack", 22, "male"}
	var patient2 = patient_details{"Daniel", 34, "male"}
	var patient3 = patient_details{"Sarah", 12, "female"}
	var patient4 = patient_details{"Superman", 52, "male"}

	fmt.Println("who is the oldest patient in our hospital?")
	age := []int{patient1.age,patient2.age,patient3.age,patient4.age}
	sort.Ints(age)

	fmt.Println("smallest:", age[0], ",Oldest:", age[len(age)-1])

}
1 Like

You can store several values in slice and after that just looking in range for whatever - min/max/…

1 Like

Sorting is O(n log n) at best, while a single iteration scan can can give you minimum and maximum in O(n).

The most optimal solution is just a simple loop, iterating over the input.

2 Likes

how , can you demonstrate it please ?

and thank you all for your support

Sure.

This example uses a simple []int as an example.

https://play.golang.org/p/w-7i1T7ptWz

1 Like

thank you for the help , the sort method is much simpler , easier and less code , although the looping method is more fun

	age := []int{patient1.age,patient2.age,patient3.age,patient4.age}

this might not be a problem for small arrays but will be a memory waste for big arrays, no need to allocate new array for this problem, just a loop is enough to find max and min as @NobbZ mentioned.