I have a general question regarding slices, counter, time and the baffling merge and sort in Go.
I have coded a little program from a practical exercise online to learn about Go, I'm baffled as to why the solution I have written gets an error.
The code is simply two counter slices, they are sorted by time, I have decided to try and merge it and again sort it by the corresponding time to the count. I have completed the rest of the code but the merging has me confused.
Code snippet will be provided for your perusal.
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)
}
}
To solve your question about appending and sorting the arrays you can just append pieces of one array to the another like so:
result := append(a, b...)
To sort array based on internal struct types like unix time, your best bet is to create custom type of the slice and implement methods for sort.Interface.
Example would be:
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) }
and then call just
sort.Sort(ByTime(result))
Full example: https://play.golang.org/p/L9_aPRlQsss
But note that I am not solving your coding exercise how to merge two arrays based on internal metrics only appending one to another. You will need to put some work in your homework ;-) This will still produce sorted (not element merged) 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}