gpt4 book ai didi

go - 合并排序计数器 slice

转载 作者:行者123 更新时间:2023-12-01 22:33:25 24 4
gpt4 key购买 nike

我有一个关于 slice 、计数器、时间以及 Go 中令人费解的合并和排序的一般性问题。
我从在线实践练习中编写了一个小程序来学习 Go,我很困惑为什么我编写的解决方案会出错。
代码只是两个计数器 slice ,它们是按时间排序的,我决定尝试合并它,然后再次按照计数的对应时间对其进行排序。我已经完成了其余的代码,但合并让我感到困惑。
将提供代码片段供您阅读。

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 time 等内部结构类型对数组进行排序,最好的办法是创建 slice 的自定义类型并实现 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
但请注意,我并没有解决您的编码练习如何基于内部指标合并两个数组,仅将一个附加到另一个。你需要在你的家庭作业中做一些工作;-)
这仍然会产生排序的(不是元素合并的) slice :
{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}

关于go - 合并排序计数器 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64069982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com