Go course

Packages and ModulesStandard Library: math and sort

Go

Display

Theme

Packages and Modules · Test exercise

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 slices package (slices.Sort, slices.SortFunc). You'll still see sort a lot in existing code, so it's worth knowing.

Task

For a game leaderboard, complete the following (add import "math" and "sort" yourself):

  1. papanPeringkat(daftar []Pemain) []string returns the players' names, highest score first; if scores are equal, alphabetical by name. The order of the original daftar slice must not change.
  2. rataRata(skor []int) float64 returns the average rounded to one decimal place with math.Round. For an empty slice, return 0.
  3. jarak(x1, y1, x2, y2 float64) float64 returns the straight-line distance between two points on the map, that is, the square root of (x2-x1)² + (y2-y1)². Use math.Sqrt or math.Hypot.
main.go
package main

import "fmt"

type Pemain struct {
	Nama string
	Skor int
}

func papanPeringkat(daftar []Pemain) []string {
	// TODO: salin daftar, urutkan dengan sort.Slice, kembalikan nama-nama
	return nil
}

func rataRata(skor []int) float64 {
	// TODO: hitung rata-rata, bulatkan 1 desimal dengan math.Round
	return 0
}

func jarak(x1, y1, x2, y2 float64) float64 {
	// TODO: gunakan math.Sqrt atau math.Hypot
	return 0
}

func main() {
	daftar := []Pemain{{"Raka", 1200}, {"Nadia", 1500}, {"Bagas", 1200}}
	fmt.Println(papanPeringkat(daftar))
	fmt.Println(rataRata([]int{1200, 1500, 1200}))
	fmt.Println(jarak(0, 0, 3, 4))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)