From 594f17547277c575663f807c73af882d2d9306e6 Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Mon, 7 Nov 2022 11:24:46 -0800 Subject: [PATCH] implement primetime --- cmd/primetime/main.go | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/cmd/primetime/main.go b/cmd/primetime/main.go index 7ad3841..5921b0e 100644 --- a/cmd/primetime/main.go +++ b/cmd/primetime/main.go @@ -1,15 +1,24 @@ package main import ( + "bufio" + "encoding/json" "log" + "math/big" "net" "protohackers/pkg/conn" ) +var ( + malformedResponse = []byte("malformed\n") + trueResponse = []byte(`{"method":"isPrime","prime":true}` + "\n") + falseResponse = []byte(`{"method":"isPrime","prime":false}` + "\n") +) + type data struct { - Method string `json:"method"` - Number int `json:"number"` + Method string `json:"method"` + Number *float64 `json:"number"` } func main() { @@ -21,4 +30,23 @@ func main() { func primetime(c net.Conn) { defer c.Close() + sc := bufio.NewScanner(c) + for sc.Scan() { + response := process(sc.Bytes()) + c.Write(response) + } + if err := sc.Err(); err != nil { + log.Fatalln(err) + } +} + +func process(buf []byte) []byte { + var in data + err := json.Unmarshal(buf, &in) + if err != nil || in.Method != "isPrime" || in.Number == nil { + return malformedResponse + } else if big.NewInt(int64(*in.Number)).ProbablyPrime(0) { + return trueResponse + } + return falseResponse }