2022-11-07 23:02:36 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"protohackers/pkg/conn"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
2023-09-15 21:20:51 +00:00
|
|
|
err := conn.StartSimpleTCP(meansToAnEnd)
|
2022-11-07 23:02:36 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func meansToAnEnd(c net.Conn) {
|
|
|
|
defer c.Close()
|
|
|
|
var ledger = make(map[int32]int32)
|
|
|
|
buf := make([]byte, 9)
|
|
|
|
|
|
|
|
for {
|
|
|
|
if _, err := io.ReadFull(c, buf); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if _, err := c.Write(process(buf, ledger)); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func process(buf []byte, ledger map[int32]int32) []byte {
|
|
|
|
i1, i2 := int32(binary.BigEndian.Uint32(buf[1:5])), int32(binary.BigEndian.Uint32(buf[5:]))
|
|
|
|
|
|
|
|
switch buf[0] {
|
|
|
|
case 'I':
|
|
|
|
ledger[i1] = i2
|
|
|
|
case 'Q':
|
|
|
|
var c int64
|
|
|
|
var t int64
|
|
|
|
for k, v := range ledger {
|
|
|
|
if i1 <= k && k <= i2 {
|
|
|
|
t += int64(v)
|
|
|
|
c++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if c == 0 {
|
|
|
|
c = 1 /* Can't divide by zero! */
|
|
|
|
}
|
|
|
|
mean := t / c
|
|
|
|
r := make([]byte, 4)
|
|
|
|
binary.BigEndian.PutUint32(r, uint32(mean))
|
|
|
|
return r
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|