Ejercicios de Go
Anagram Check in Go
Do two texts use exactly the same letters? Sort the letters of both and compare.
Lo que aprenderás
- 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.
Puntos clave
- Lower case and drop the spaces.
- Sort the letters of each text.
- Equal sorted forms mean an anagram.
Ejemplo ejecutable de Go
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"))
}
true
true
falsePractica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
Todos los retos