[Golang] Anagram Check by Characters Count


Check whether two strings are anagram of each other in Go programming language.

Check by characters count:

  1. setup map structures to count the characters of both strings [2].
  2. compare if the two map structures are equal [3] via reflect.DeepEqual.

Another way to check anagram is by sorting, see [1].

Run Code on Go Playground

package anagram

import (
      "reflect"
)

func GetCharCount(s string) (c map[rune]int) {
      c = make(map[rune]int)
      for _, runeValue := range s {
              if _, ok := c[runeValue]; ok {
                      c[runeValue] += 1
              } else {
                      c[runeValue] = 1
              }
      }
      return
}

func AreAnagram(s1, s2 string) bool {
      c1 := GetCharCount(s1)
      c2 := GetCharCount(s2)

      return reflect.DeepEqual(c1, c2)
}

Testing:

package anagram

import (
      "testing"
)

func TestAreAnagram(t *testing.T) {
      if AreAnagram("listen", "silent") != true {
              t.Error(`"listen", "silent"`)
      }
      if AreAnagram("test", "ttew") != false {
              t.Error(`"test", "ttew"`)
      }
      if AreAnagram("geeksforgeeks", "forgeeksgeeks") != true {
              t.Error(`"geeksforgeeks", "forgeeksgeeks"`)
      }
      if AreAnagram("triangle", "integral") != true {
              t.Error(`"triangle", "integral"`)
      }
      if AreAnagram("abd", "acb") != false {
              t.Error(`"abd", "acb"`)
      }
}

Tested on:


References:

[1][Golang] Check Whether Two Strings Are Anagram of Each Other
[2]Go maps in action - The Go Blog
[3]go - How to compare struct, slice, map are equal? - Stack Overflow
[4]