Hi Gophers,
I once again seek your guidance in solving this problem. The problem is as follows:
Given two maps, write a program that would return common elements (if any) and unique elements(if any) in two separate maps.
Here’s what I’ve done so far:
package main
import "fmt"
func main() {
fmt.Println("vim-go")
firstMap := map[string]string{
"first": "Pritesh",
"middle": "Manohar",
"last": "Ugrankar",
"city": "Bangalore",
"building": "Ittina Neela",
}
secondMap := map[string]string{
"first": "Pritesh",
"middle": "Manohar",
"last": "Ugrankar",
"location": "ECity",
}
common, unique := unique(firstMap, secondMap)
fmt.Println("First map contains:", firstMap)
fmt.Println("Second map contains:", secondMap)
fmt.Println("Common elements are:", common)
fmt.Println("Unique elements are:", unique)
}
func unique(first map[string]string, second map[string]string) (map[string]string, map[string]string) {
commonMap := make(map[string]string)
uniqueMap := make(map[string]string)
for key, _ := range first {
uniqueMap[key] = first[key]
}
for key, _ := range second {
if _, ok := uniqueMap[key]; ok == true {
delete(uniqueMap, key)
commonMap[key] = second[key]
} else {
uniqueMap[key] = second[key]
}
}
return commonMap, uniqueMap
}
And I get the answer as expected:
pritesh@debian:~/go/src/github.com/pritesh-ugrankar/umaps$ go run main.go
vim-go
First map contains: map[building:Ittina Neela city:Bangalore first:Pritesh last:Ugrankar middle:Manohar]
Second map contains: map[first:Pritesh last:Ugrankar location:ECity middle:Manohar]
Common elements are: map[first:Pritesh last:Ugrankar middle:Manohar]
Unique elements are: map[building:Ittina Neela city:Bangalore location:ECity]
pritesh@debian:~/go/src/github.com/pritesh-ugrankar/umaps$
My problem is with the following section in the code:
for key, _ := range second {
if _, ok := uniqueMap[key]; ok == true {
delete(uniqueMap, key)
commonMap[key] = second[key]
} else {
uniqueMap[key] = second[key]
Problem is if I remove the “else” loop, then the unique key from the second map does not get added to the unique map. I’ve tried everything but nothing works except this, and this looks really ugly like a shoddy workaround.
How can I make it better??