From 9d7e1a13b0cb421596e384666673df1a58ff223e Mon Sep 17 00:00:00 2001 From: Aravind Date: Wed, 5 Apr 2023 10:52:18 +0530 Subject: [PATCH 1/2] Anagram func --- strings/strings.go | 23 +++++++++++++++++++++++ strings/strings_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 strings/strings.go create mode 100644 strings/strings_test.go diff --git a/strings/strings.go b/strings/strings.go new file mode 100644 index 0000000..7c64d70 --- /dev/null +++ b/strings/strings.go @@ -0,0 +1,23 @@ +package strings + +func AreAnagrams(s1, s2 string) bool { + // If both strings are of unequal length, they are not anagrams + if len(s1) != len(s2) { + return false + } + + var charCount = make(map[rune]int) + + for _, ch := range s1 { + charCount[ch]++ + } + + for _, ch := range s2 { + charCount[ch]-- + if charCount[ch] < 0 { + return false + } + } + + return true +} diff --git a/strings/strings_test.go b/strings/strings_test.go new file mode 100644 index 0000000..8aad9d2 --- /dev/null +++ b/strings/strings_test.go @@ -0,0 +1,35 @@ +package strings + +import ( + "fmt" + "testing" +) + +func TestAreAnagrams(t *testing.T) { + tests := []struct { + s1 string + s2 string + want bool + }{ + {"", "", true}, + {"a", "a", true}, + {"aa", "aa", true}, + {"abcd", "dcba", true}, + {"anagram", "nag a ram", false}, + {"listen", "silent", true}, + {"abcdefg", "gfedcba", true}, + {"abc", "abcd", false}, + {"abcd", "dcbb", false}, + {":-;][=+", "+;=:", false}, + {":-asds;][=+", "+a;s[-d=:s]", true}, + {":-asds;][=+", "+;=:", false}, + {":-;][=+", "+asds;=:", false}, + } + for _, input := range tests { + t.Run(fmt.Sprintf("TestAreAnagrams(%v, %v)", input.s1, input.s2), func(t *testing.T) { + if got := AreAnagrams(input.s1, input.s2); got != input.want { + t.Errorf("AreAnagrams() = %v, want %v", got, input.want) + } + }) + } +} From 150994f15c29bf7e544f02e956dec0acbd6ef659 Mon Sep 17 00:00:00 2001 From: Aravind Date: Wed, 5 Apr 2023 11:42:32 +0530 Subject: [PATCH 2/2] Add comment --- strings/strings.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/strings/strings.go b/strings/strings.go index 7c64d70..8cd2324 100644 --- a/strings/strings.go +++ b/strings/strings.go @@ -1,5 +1,11 @@ package strings +/** + Checks if two strings are perfect anagrams of each other using character count comparison. + Anagrams are formed by rearranging the letters of one string using all the original letters exactly once. + + Example: "listen" and "silent" are perfect anagrams of each other, while "now silent" and "listennow" are not. +**/ func AreAnagrams(s1, s2 string) bool { // If both strings are of unequal length, they are not anagrams if len(s1) != len(s2) {