Created
November 10, 2015 13:35
-
-
Save maksadbek/64b75ab17fc4f5b82a38 to your computer and use it in GitHub Desktop.
Pattern matching exercise solution that I failed on job interview.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"strings" | |
) | |
func match(pattern, text string) bool { | |
patterns := strings.Split(pattern, "") | |
words := strings.Split(text, " ") | |
// if the length of patterns and words does not the same the mapping is wrong | |
if len(words) != len(patterns) { | |
return false | |
} | |
// mapping hashmap is to keep pattern to word mappings | |
mapping := make(map[string]string) | |
// range over patterns | |
for i, pat := range patterns { | |
// range over mappings | |
for p, w := range mapping { | |
// if patterns match and words does not | |
// or the words match and patterns does not | |
// then the mapping is wrong | |
if (words[i] == w && p != pat) || (p == pat && words[i] != w) { | |
return false | |
} | |
} | |
mapping[pat] = words[i] | |
} | |
return true | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
) | |
func TestMatch(t *testing.T) { | |
if got := match("aabbcc", "ali ali baba baba camel camel"); !got { | |
t.Errorf("want %b, got %b", true, got) | |
} | |
if got := match("aabbcc", "ali ali baba huy camel camel"); got { | |
t.Errorf("want %b, got %b", true, got) | |
} | |
if got := match("aadbcc", "ali ali baba baba camel camel"); got { | |
t.Errorf("want %b, got %b", false, got) | |
} | |
if got := match("aadbcc", "ali ali baba baba camel camel joke"); got { | |
t.Errorf("want %b, got %b", false, got) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment