英文:
How to have unique elements in integer array within a map?
问题
我有一个字符串和整数数组的映射,如下所示,正在填充:
var customerCatalog = make(map[string][]int64)
for ... {
var data = "....."
for _, catalogId := range data.Catalogs {
var ok bool
var keys []int64
var tmp interface{}
cusId := strconv.FormatInt(int64(catalogId), 10)
if tmp, ok = customerCatalog[cusId]; !ok {
keys = []int64{}
} else {
keys = tmp.([]int64)
}
keys = append(keys, data.ProductId)
customerCatalog[cusId] = keys
}
}
这里的data.Catalogs
是int32数组,data.ProductId
是int64。所以我需要遍历data.Catalogs
数组,并为每个data.ProductId
键填充我的customerCatalog
映射的唯一数组值。
正如你所看到的,我将映射的值设置为整数数组,其中可能包含重复的值。我希望确保映射中特定键的整数数组中的值是唯一的。由于Go语言不支持泛型,所以我们没有集合(set)。那么在这种情况下,我们应该如何处理呢?
英文:
I have a map of string and int array as shown below which is being populated -
var customerCatalog = make(map[string][]int64)
for ... {
var data = "....."
for _, catalogId := range data.Catalogs {
var ok bool
var keys []int64
var tmp interface{}
cusId := strconv.FormatInt(int64(catalogId), 10)
if tmp, ok = customerCatalog[cusId]; !ok {
keys = []int64{}
} else {
keys = tmp.([]int64)
}
keys = append(keys, data.ProductId)
customerCatalog[cusId] = keys
}
}
Here data.Catalogs
is int32 array. And data.ProductId
is int64. So I need to loop over data.Catalogs
array and populate my customerCatalog
map with unique array values for each data.ProductId
key.
As you can see I have value of map as integer array which can have duplicate values in it. I want to make sure integer array for particular key in the map should have unique values in them. Since go doesn't support generics so that is why we don't have set so how should we handle this case here?
答案1
得分: 3
由于Go语言不支持泛型,所以我们没有集合(set)的内置类型。
在Go中,可以使用map[int64]bool
来实现集合。
// 检查数组是否只包含唯一值。
func is_unique(array []int64) bool {
var unique = map[int64]bool{}
for _,v := range(array) {
if unique[v] {
return false
}
unique[v] = true
}
return true
}
// 返回去重后的数组
func uniq(array []int64) []int64 {
var unique = map[int64]bool{}
keys := make([]int64, 0)
for _,v := range(array) {
if _, ok := unique[v]; !ok {
keys = append(keys, v)
unique[v] = true
}
}
return keys
}
以上是使用map[int64]bool
实现集合的示例代码。
英文:
> Since go doesn't support generics so that is why we don't have set
Sets are often implemented using the keys of a hash table; ignore the values.
In Go, use a map[int64]bool
.
// Check if an array contains only unique values.
func is_unique(array []int64) bool {
var unique = map[int64]bool{}
for _,v := range(array) {
if unique[v] {
return false
}
unique[v] = true
}
return true
}
// Return a deduplicated array
func uniq(array []int64) []int64 {
var unique = map[int64]bool{}
keys := make([]int64, 1)
for _,v := range(array) {
if _, ok := unique[v]; !ok {
keys = append(keys, v)
unique[v] = true
}
}
return keys
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论