Last active
November 4, 2021 23:12
-
-
Save murphybytes/aba3d86bc9268f577bf0e27a5b1e20ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"net" | |
"strings" | |
"time" | |
) | |
func main() { | |
conn, err := net.Dial("tcp", "palindromer-bd7e0fc867d57915.elb.us-east-1.amazonaws.com:7777") | |
if err != nil { | |
log.Fatal("could not connect", err) | |
} | |
defer conn.Close() | |
for { | |
func() { | |
t := time.Now() | |
defer func() { | |
log.Printf("elapsed %s\n", time.Since(t)) | |
}() | |
reader := bufio.NewReader(conn) | |
request, err := reader.ReadString('\n') | |
if err != nil { | |
log.Fatal("failed to read from connection", err) | |
} | |
if strings.HasPrefix(request, "!!!") { | |
log.Fatalf("all done %q\n", request) | |
} | |
request = strings.TrimRight(request, "\n") | |
candidates := strings.Split(request, " ") | |
pals := findPalindromes(candidates) | |
response := []byte(fmt.Sprintf("%s\n", strings.Join(pals, " "))) | |
n, err := conn.Write(response) | |
if err != nil { | |
log.Fatal("write failed ", err ) | |
} | |
if n != len(response) { | |
log.Fatalf("incomplete wrote %d expectd %d", n, len(response)) | |
} | |
}() | |
} | |
} | |
func findPalindromes(words []string) []string { | |
var result []string | |
for _, word := range words { | |
reversed := reverse(word) | |
if word == reversed { | |
result = append(result, reversed) | |
} | |
} | |
return result | |
} | |
func reverse(s string) string { | |
runes := []rune(s) | |
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { | |
runes[i], runes[j] = runes[j], runes[i] | |
} | |
return string(runes) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment