I am new to Go language and troubling in the code to find the unique elements in the go.
var arr [10]string
arr[0]="table"
arr[1]="chair"
arr[2]="table"
arr[3]="table"
arr[4]="chair"
arr[5]="bench"
arr[6]="table,chair"
arr[7]="bench,chair"
arr[8]="chair,table,bench"
arr[9]="car"
The output should be like:
table
chair
bench
car
I am really stuck on this. how to get the unique elements from the above array. The array contains comma seperated values also but i need to print only the unique elements.
Pls someone help me on this.
Thanks for advance.
Idea: use map[string]bool
to collect unique elements, use strings.Split
to split comma-separated list of words into strings.
Example: http://play.golang.org/p/sBopFGrzbX
package main
import (
"fmt"
"strings"
)
func main() {
arr := [...]string{
"table",
"chair",
"table",
"table",
"chair",
"bench",
"table,chair",
"bench,chair",
"chair,table,bench",
"car",
}
m := make(map[string]bool)
for _, e := range arr {
for _, w := range strings.Split(e, ",") {
m[w] = true
}
}
for k, _ := range m {
fmt.Println(k)
}
}