doubi5520 2017-02-12 04:16
浏览 552
已采纳

GoLang打印数组中值的出现次数

The following is my code where I need to Print the number of occurances of each values in an array.

package main

import "fmt"

func main(){
    //Initialize an array 
    inputArray := []int{10,20,30,56,67,90,10,20}
    printUniqueValue(inputArray)
}

func printUniqueValue( arr []int){
    //Create a   dictionary of values for each element
    var  dict map[int]int 
    count := 0
    for _ , num :=  range arr {
        dict[num] = count+1
    }
    fmt.Println(dict)
}

But I couldn't construct the dictionary as I wish like , dict[10] should have value 2. Sample Expected Output :

dict[10] = 2
dict[20] = 2
dict[30] = 1  

Error I got: panic: assignment to entry in nil map

  • 写回答

2条回答 默认 最新

  • duanjian4150 2017-02-12 04:24
    关注

    You need to initialize dict with a non-nil map; one way would be with var dict = make(map[int]int).

    Once you fix that, you will also need to deal with the logic error in dict[num] = count+1, where the count of that value is set to 1 (count is always 0) instead of one more than the previous value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码