In: Computer Science
A simple anagram finder program in Golang?
package main
// import packages
import "fmt"
import "reflect"
// driver function
func main() {
//string variables to take input from user
var s1 string
var s2 string
//ask and input from user
fmt.Println("Enter the first string")
fmt.Scanf("%s", &s1)
fmt.Println("Enter the second string")
fmt.Scanf("%s", &s2)
//if both strings are of unequal length
if len(s1) != len(s2) {
fmt.Println("These strings are not
anagrams.")
}
//create a map and store (key, value) pair as
(character, frequency)
map1 := make(map[string]int)
//traverse string s1
for _, r := range s1 {
//string(r) used to convert rune
type to string type
j := map1[string(r)]
//if not present,then create it
otherwise add into it
if j == 0 {
map1[string(r)]
= 1
}else {
map1[string(r)]
= j + 1
}
}
//create a map and store (key, value) pair as
(character, frequency)
map2 := make(map[string]int)
//traverse string s2
for _, r := range s2 {
//string(r) used to convert rune
type to string type
j := map2[string(r)]
//if not present,then create it otherwise add into it
if j == 0 {
map2[string(r)]
= 1
}else {
map2[string(r)]
= j + 1
}
}
// so if both strings are anagrams i.e, having same
frequency of each character in any order the
// hashmap for both will be equal so comparing hashmap
we get,
anagram := reflect.DeepEqual(map1, map2)
//if anagram is true otherwise false
if anagram {
fmt.Println("These strings are
anagrams.")
}else {
fmt.Println("These strings are not
anagrams.")
}
}
CODE
So if you have any doubt regarding this solution then please feel free to ask in the comment section below and if it is helpful then please upvote this solution, THANK YOU.