Standard Library: math and sort
The math package
math holds mathematical constants and functions for float64:
math.Sqrt(16) // 4
math.Pow(2, 10) // 1024
math.Abs(-3.5) // 3.5
math.Hypot(3, 4) // 5 — sqrt(3*3 + 4*4)
math.Floor(2.7) // 2
math.Ceil(2.1) // 3
math.Round(2.5) // 3 — membulatkan ke bilangan bulat terdekat
math.Max(3, 8) // 8
math.Pi // 3.141592653589793
math.MaxInt // nilai int terbesar
math.Round rounds to the nearest whole number, and math.MaxInt is the largest int value. All the functions above take and return float64, so convert first if your data is an int: math.Sqrt(float64(n)). (For int, Go 1.21 and later also has the built-in min and max functions.)
A trick for rounding to one decimal place: multiply by 10, round, divide by 10.
math.Round(3.14159*10) / 10 // 3.1
The sort package
You already met sort.Strings in Chapter 10. For a slice of structs with your own ordering rule, use sort.Slice with a comparison function less(i, j) that returns true if element i should come before element j:
produk := []Produk{{"Teh", 18000}, {"Kopi", 25000}, {"Air", 5000}}
sort.Slice(produk, func(i, j int) bool {
return produk[i].Harga < produk[j].Harga // termurah dulu
})
That sorts the cheapest first. For layered rules (say, highest score first, and alphabetical by name on a tie):
sort.Slice(p, func(i, j int) bool {
if p[i].Skor != p[j].Skor {
return p[i].Skor > p[j].Skor
}
return p[i].Nama < p[j].Nama
})
sort.Slice changes the slice in place. If the original slice must not change, copy it first with make + copy (Chapter 9).
Note: modern Go also provides the newer
slicespackage (slices.Sort,slices.SortFunc). You'll still seesorta lot in existing code, so it's worth knowing.
Task
For a game leaderboard, complete the following (add import "math" and "sort" yourself):
papanPeringkat(daftar []Pemain) []stringreturns the players' names, highest score first; if scores are equal, alphabetical by name. The order of the originaldaftarslice must not change.rataRata(skor []int) float64returns the average rounded to one decimal place withmath.Round. For an empty slice, return0.jarak(x1, y1, x2, y2 float64) float64returns the straight-line distance between two points on the map, that is, the square root of(x2-x1)² + (y2-y1)². Usemath.Sqrtormath.Hypot.