1
0

day2.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "math"
  7. "os"
  8. "strconv"
  9. "strings"
  10. )
  11. func isSafe(level []int) bool {
  12. increasing := true
  13. decreasing := true
  14. for i := 1; i < len(level); i++ {
  15. diff := level[i] - level[i-1]
  16. if math.Abs((float64(diff))) < 1 || math.Abs(float64(diff)) > 3 {
  17. return false
  18. }
  19. if diff < 0 {
  20. decreasing = false
  21. }
  22. if diff > 0 {
  23. increasing = false
  24. }
  25. }
  26. return increasing || decreasing
  27. }
  28. func isSafeWithDeletion(level []int) bool {
  29. for i := 0; i < len(level); i++ {
  30. modified := append([]int{}, level[:i]...)
  31. modified = append(modified, level[i+1:]...)
  32. if isSafe(modified) {
  33. return true
  34. }
  35. }
  36. return false
  37. }
  38. func main() {
  39. args := flag.Bool("example", false, "example or input, just type the 'example' for example")
  40. // Read input from file
  41. flag.Parse()
  42. filename := "input.txt"
  43. if *args {
  44. filename = "example.txt"
  45. }
  46. file, err := os.Open(filename)
  47. if err != nil {
  48. panic("Can't read the file")
  49. }
  50. defer file.Close()
  51. reader := bufio.NewReader(file)
  52. safeCount := 0
  53. safeCountWithDeletion := 0
  54. for {
  55. line, _, err := reader.ReadLine()
  56. if len(line) == 0 {
  57. break
  58. }
  59. if err != nil {
  60. fmt.Println(err)
  61. }
  62. var level []int
  63. for _, num := range strings.Fields(string(line)) {
  64. numi, _ := strconv.Atoi(num)
  65. level = append(level, numi)
  66. }
  67. if isSafe(level) {
  68. safeCount++
  69. } else {
  70. if isSafeWithDeletion(level) {
  71. safeCountWithDeletion++
  72. }
  73. }
  74. }
  75. fmt.Println("Part 1 Safe Counts:", safeCount)
  76. fmt.Println("Part 2 Safe Counts With Deletion:", safeCount+safeCountWithDeletion)
  77. }