Go course

Slices2D Slices and the slices Package

Go

Display

Theme

Slices · Test exercise

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:

  1. func totalPerTim(skor [][]int) []int: a slice holding each team's total score, in the same order as skor.
  2. func peringkat(skor [][]int) []int: each team's total score, sorted from highest to lowest. Use slices.Sort and slices.Reverse.
  3. func timDenganSkor(skor [][]int, nilai int) int: the index of the first team that scored exactly nilai in one of its matches (use slices.Contains), or -1 if there isn't one.
  4. func salinTanpaUbah(skor []int) []int: return a copy of skor sorted in ascending order without changing the original slice (use slices.Clone).

Example: for skor = [][]int{{10, 7}, {12, 15, 3}, {9}}, totalPerTim → [17 30 9] and peringkat → [30 17 9].

main.go
package main

import "fmt"

// TODO: import paket "slices" saat Anda memakainya

func totalPerTim(skor [][]int) []int {
	// TODO
	return nil
}

func peringkat(skor [][]int) []int {
	// TODO: hitung total lalu urutkan menurun
	return nil
}

func timDenganSkor(skor [][]int, nilai int) int {
	// TODO
	return -1
}

func salinTanpaUbah(skor []int) []int {
	// TODO
	return skor
}

func main() {
	skor := [][]int{
		{10, 7},
		{12, 15, 3},
		{9},
	}
	fmt.Println("Total:", totalPerTim(skor))
	fmt.Println("Peringkat:", peringkat(skor))
	fmt.Println("Tim pencetak 15:", timDenganSkor(skor, 15))

	asli := []int{30, 10, 20}
	urut := salinTanpaUbah(asli)
	fmt.Println(asli, urut)
}

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)