我有一个关于切片,计数器,时间和令人困惑的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)
}
}
答案 0 :(得分:1)
要解决有关对数组进行追加和排序的问题,您可以像这样将一个数组的一部分追加到另一个数组中:
--auto-merge
要基于诸如unix time之类的内部结构类型对数组进行排序,最好的选择是创建切片的自定义类型并实现sort.Interface的方法。
示例为:
[[${#authentication.getPrincipal().getName()}]];
然后打电话给
<li sec:authorize="isAuthenticated()"> <span id="id" sec:authentication="name"></span></li>
完整示例:https://play.golang.org/p/L9_aPRlQsss
但是请注意,我没有解决您的编码练习,即如何仅基于内部指标将两个数组追加到另一个数组来合并两个数组。您将需要在家庭作业中做一些工作;-) 这仍然会产生排序(而不是元素合并)的切片:
result := append(a, b...)