Go अभ्यास

Anagram Check in Go

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

  • शुरुआती
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • 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.

मुख्य बातें

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

चलने योग्य Go उदाहरण

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"))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
true
true
false

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज