Esercizi di Go

Anagram Check in Go

Do two texts use exactly the same letters? Sort the letters of both and compare.

  • Principiante
  • 3 min di lettura
  • 1 esempio eseguibile
Cosa imparerai
  • Normalizing text
  • slices.Sort on runes
  • Comparing the results
listen and silent
listen
  • sorted
  • eilnst
silent
  • sorted
  • eilnst

Same letters, different order

Two words are anagrams when one can be made by rearranging the letters of the other, such as listen and silent. Sorting the letters of both gives the same result exactly when they are anagrams.

normalize makes the text lower case, drops the spaces and sorts the remaining characters with slices.Sort. Two texts are anagrams when their normalized forms are equal.

Punti chiave

  1. Lower case and drop the spaces.
  2. Sort the letters of each text.
  3. Equal sorted forms mean an anagram.

Esempio Go eseguibile

Go
Esegui il codice →
main.go
package main

import (
	"fmt"
	"slices"
	"strings"
)

func normalize(text string) string {
	runes := []rune{}
	for _, r := range strings.ToLower(text) {
		if r != ' ' {
			runes = append(runes, r)
		}
	}
	slices.Sort(runes)
	return string(runes)
}

func isAnagram(a, b string) bool {
	return normalize(a) == normalize(b)
}

func main() {
	fmt.Println(isAnagram("listen", "silent"))
	fmt.Println(isAnagram("Dormitory", "dirty room"))
	fmt.Println(isAnagram("gopher", "golang"))
}
Crea un pulsante Run per questo esempio Risultato dell'esecuzione
true
true
false

Esercitati

Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.

Hai finito questa lezione?

Segnala come imparata per tenere traccia dei tuoi progressi.

Esercitati con una sfida

Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.

Tutte le sfide