2D Slices and the slices Package
Two-dimensional slices
A slice's elements can be other slices. The result is a 2D slice ([][]T), great for tables, game boards, or seating charts:
denah := [][]string{
{"A1", "A2", "A3"},
{"B1", "B2"}, // panjang tiap baris boleh berbeda
}
fmt.Println(denah[1][0]) // B1
Note that each row can have a different length. To create a grid of a given size, make the outer slice and then fill each row with make:
papan := make([][]rune, 3)
for i := range papan {
papan[i] = make([]rune, 3)
}
You walk through it with nested loops:
for _, baris := range denah {
for _, kursi := range baris {
fmt.Print(kursi, " ")
}
fmt.Println()
}
The slices package
Since Go 1.21, the standard library has a slices package with common functions for slices:
import "slices"
skor := []int{70, 95, 82}
slices.Contains(skor, 95) // true
slices.Index(skor, 82) // 2 (-1 jika tidak ada)
slices.Max(skor) // 95 (panic jika slice kosong)
slices.Sort(skor) // skor menjadi [70 82 95] — mengubah slice ASLI
slices.Reverse(skor) // [95 82 70]
salinan := slices.Clone(skor) // salinan terpisah
slices.Equal(skor, salinan) // true
slices.Index returns -1 when the value isn't there, and slices.Max panics on an empty slice. Remember: slices.Sort and slices.Reverse change the slice in place, modifying the original. If the original data must not change, make a copy first with slices.Clone.
Task
An e-sports tournament records each team's score per match in a 2D slice: skor[i] is the list of scores for team i. Complete:
func totalPerTim(skor [][]int) []int: a slice holding each team's total score, in the same order asskor.func peringkat(skor [][]int) []int: each team's total score, sorted from highest to lowest. Useslices.Sortandslices.Reverse.func timDenganSkor(skor [][]int, nilai int) int: the index of the first team that scored exactlynilaiin one of its matches (useslices.Contains), or-1if there isn't one.func salinTanpaUbah(skor []int) []int: return a copy ofskorsorted in ascending order without changing the original slice (useslices.Clone).
Example: for skor = [][]int{{10, 7}, {12, 15, 3}, {9}}, totalPerTim → [17 30 9] and peringkat → [30 17 9].