code.go 850 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. )
  8. func readInput(path string) []byte {
  9. data, err := ioutil.ReadFile(path)
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. return data
  14. }
  15. func check(duplicates map[byte]int) bool {
  16. for _, value := range duplicates {
  17. if value > 1 {
  18. return false
  19. }
  20. }
  21. return true
  22. }
  23. func process(text []byte, limit int) int {
  24. count := 0
  25. toDelete := 0
  26. duplicates := make(map[byte]int)
  27. for i := range text {
  28. count++
  29. duplicates[text[i]]++
  30. if count-toDelete > limit {
  31. if check(duplicates) {
  32. break
  33. }
  34. duplicates[text[toDelete]]--
  35. toDelete++
  36. }
  37. }
  38. return count
  39. }
  40. func main() {
  41. if len(os.Args) < 2 {
  42. log.Fatal("You need to specify a file!")
  43. }
  44. filePath := os.Args[1]
  45. text := readInput(filePath)
  46. fmt.Println("Part1:", process(text, 3))
  47. fmt.Println("Part2:", process(text, 13))
  48. }