summaryrefslogtreecommitdiff
path: root/2023/go/internal/day_03/part_01/part_01.go
blob: 49837b38387ab50a3cf5399160c7e249f91663ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package part_01

/**
 * TRIED:
 * 530923
 */

import (
	"os"
	"strconv"
	"strings"
)

const USE_SAMPLE = true

func Solve() {
	var content []byte
	if USE_SAMPLE {
		content, _ = os.ReadFile("../_input/day_03_part_01_sample.txt")
	} else {
		content, _ = os.ReadFile("../_input/day_03.txt")
	}
	lines := strings.Split(string(content), "\n")

	validNumbers := walkLines(lines)

	answer := 0
	for _, number := range validNumbers {
		answer += number
	}

	println(answer)
}

func walkLines(lines []string) []int {
	var validNumbers []int

	for y := 0; y < len(lines); y++ {
		line := lines[y]

		if line == "" || line == "\n" {
			continue
		}

		// Counts as a symbol...
		filteredLine := strings.ReplaceAll(line, "\r", "")

		previousWasNumber := false
		number := ""
		for x := 0; x < len(filteredLine); x++ {
			char := filteredLine[x]

			_, err := strconv.Atoi(string(char))
			isNumeric := err == nil

			if isNumeric {
				previousWasNumber = true
				number += string(char)
				continue
			}

			if !previousWasNumber {
				continue
			}

			isValid := checkValidity(lines, x, y, len(number))
			if isValid {
				num, _ := strconv.Atoi(number)
				validNumbers = append(validNumbers, num)
			}

			println(number)

			previousWasNumber = false
			number = ""
		}
	}

	return validNumbers
}

// N = number
// k = numOfDigits + 1
// (x-k,y-1) (x-1,y-1) ( x ,y-1)
// (x-k, y )     N     ( x , y )
// (x-k,y+1) (x-1,y+1) ( x ,y+1)
func checkValidity(lines []string, x int, y int, numOfDigits int) bool {

	for i := max(y-1, 0); i <= y+1; i++ {

		var debugLine string

		for j := max(x-(numOfDigits+1), 0); j <= x; j++ {

			if lineExists := len(lines) > i; !lineExists {
				continue
			}

			if charExists := len(lines[i]) > j; !charExists {
				continue
			}

			char := rune(lines[i][j])
			debugLine += string(char)

			if char == '.' {
				continue
			}

			_, err := strconv.Atoi(string(char))
			isNumeric := err == nil
			if isNumeric {
				continue
			}

			debugLine = "" //nolint:ineffassign // Only used for debugging and needs to be reset

			return true
		}
	}

	return false
}