合并排序计数器切片

Merge Sort Counter Slices

我有一个关于切片、计数器、时间以及 Go 中令人困惑的合并和排序的一般性问题。

我通过在线练习编写了一个小程序来学习 Go,我很困惑为什么我编写的解决方案会出错。

代码只是两个计数器切片,它们按时间排序,我决定尝试合并它并再次按计数对应的时间排序。我已经完成了其余的代码,但合并让我感到困惑。

将提供代码片段供您阅读。

package main

import (
  "fmt"
  "time"
)

/*
Given Counter slices that are sorted by Time, merge the slices into one slice.
Make sure that counters with the same Time are merged and the Count is increased.
E.g:

A = [{Time: 0, Count: 5}, {Time:1, Count: 3}, {Time: 4, Count 7}]
B = [{Time: 1, Count: 9}, {Time:2, Count: 1}, {Time: 3, Count 3}]

merge(A, B) ==>

[{Time: 0, Count: 5}, {Time: 1: Count: 12}, {Time: 2, Count 1}, {Time: 3, Count: 3}, {Time: 4: Count: 7}]

Explain the efficiency of your merging.
*/

type Counter struct {
  Time  time.Time
  Count uint64
}
var (

  A = []Counter{
    {Time: time.Unix(0, 0), Count: 5},
    {Time: time.Unix(0, 1), Count: 3},
    {Time: time.Unix(0, 4), Count: 7},
  }

  B = []Counter{
    {Time: time.Unix(0, 0), Count: 5},
    {Time: time.Unix(0, 1), Count: 12},
    {Time: time.Unix(0, 2), Count: 1},
    {Time: time.Unix(0, 3), Count: 3},
    {Time: time.Unix(0, 4), Count: 7},
  }
)

func merge(a, b []Counter) []Counter {
  // Insert your code here
  res1 := append(a)  <--- ERROR?
  res2 := append(b)  <--- ERROR?
  
  return nil
}

func main() {
  AB := merge(A, B)
  for _, c := range AB {
    fmt.Println(c)
  }
}

要解决关于对数组进行附加和排序的问题,您只需将一个数组的片段附加到另一个数组,如下所示:

result := append(a, b...)

要根据 unix 时间等内部结构类型对数组进行排序,最好的办法是创建切片的自定义类型并实现 sort.Interface 的方法。

示例为:

type ByTime []Counter

func (c ByTime) Len() int           { return len(c) }
func (c ByTime) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c ByTime) Less(i, j int) bool { return c[i].Time.Before(c[j].Time) }

然后只调用

sort.Sort(ByTime(result))

完整示例:https://play.golang.org/p/L9_aPRlQsss

但请注意,我不是在解决您的编码练习,即如何根据内部指标合并两个数组,仅将一个数组附加到另​​一个数组。你需要在你的家庭作业中做一些工作;-) 这仍然会产生排序的(不是元素合并的)切片:

{1970-01-01 00:00:00 +0000 UTC 5}
{1970-01-01 00:00:00.000000001 +0000 UTC 3}
{1970-01-01 00:00:00.000000001 +0000 UTC 9}
{1970-01-01 00:00:00.000000002 +0000 UTC 1}
{1970-01-01 00:00:00.000000003 +0000 UTC 3}
{1970-01-01 00:00:00.000000004 +0000 UTC 7}