dongmu5815 2013-12-12 00:39
浏览 24
已采纳

按频率图对字符串片段进行排序

I have a slice of slices of strings, and want to sort them by their frequency, I tried to follow the byAge example from the docs here http://golang.org/pkg/sort/ but was unable how to pass a list of frequencies to it.

Meaning, the outcome of the example would be:

 [[a,b] [a,b,c,d] [a,c,d,e]]

Would the approach be to have "a" be represented by a custom struct with frequency as it's own attribute? That seems to be more in line with the byAge example.

func main() {

    transactions := [][]string{{"a", "b"}, {"b", "c", "d", "a"}, {"c", "d", "e", "a"}}

    frequencies := map[string]int{
        "a": 3,
        "b": 2,
        "c": 2,
        "d": 2,
        "e": 1,
    }

    fmt.Println(transactions, frequencies)

}
  • 写回答

2条回答 默认 最新

  • dourong4031 2013-12-12 01:00
    关注

    In case you need more than the data you want to sort in the sorting process, a common way is to implement your own struct, yes. In your case this would be something like this (on play):

    type SortableTransaction struct {
        data        []string
        frequencies map[string]int
    }
    

    data would be the slice with strings and frequencies your specific frequency table.

    The following implementation could be used for the Sort interface:

    func (s SortableTransaction) Len() int { return len(s.data) }
    func (s SortableTransaction) Less(i, j int) bool {
        return s.frequencies[s.data[i]] > s.frequencies[s.data[j]]
    }
    func (s SortableTransaction) Swap(i, j int) {
        s.data[j], s.data[i] = s.data[i], s.data[j]
    }
    

    If your frequency table is constant, you can declare it at package level of course.

    In case you want to sort the outer slice as well, you'd have to sort the inner slices first and then the outer slices.

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器