diff options
| author | omagdy <omar.professional8777@gmail.com> | 2024-12-12 18:31:50 +0200 |
|---|---|---|
| committer | omagdy <omar.professional8777@gmail.com> | 2024-12-12 18:31:50 +0200 |
| commit | 0cb12b95ef11fe283731e862e3953f27eeea8757 (patch) | |
| tree | 66d54e44b821073ddf6381bf9b3d9d55b3d86c31 /2024/go/src/day03 | |
| parent | 93cc02c058f39d370472dfe7d667ae7a2f6396b3 (diff) | |
| download | aoc-0cb12b95ef11fe283731e862e3953f27eeea8757.tar.xz aoc-0cb12b95ef11fe283731e862e3953f27eeea8757.zip | |
Day 11 done.
Diffstat (limited to '2024/go/src/day03')
| -rw-r--r-- | 2024/go/src/day03/main.go | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/2024/go/src/day03/main.go b/2024/go/src/day03/main.go new file mode 100644 index 0000000..11e9f47 --- /dev/null +++ b/2024/go/src/day03/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "os" + "regexp" + "strconv" +) + +func FileRead(path string) string { + file, err := os.ReadFile(path) + if err != nil { + fmt.Println("Couldn't Read file: ", err) + } + return string(file) + +} + +func solve_part_one(data string) int { + pattern := `mul\((\d+),(\d+)\)` + regex := regexp.MustCompile(pattern) + + // FindStringSubmatch returns the full match and all capture groups + matches := regex.FindAllStringSubmatch(data, -1) + + ans := 0 + + // Iterate over all matches + for _, match := range matches { + // fmt.Printf("Match %d:\n", i+1) + // fmt.Println(" Full match:", match[0]) // Entire match + left, _ := strconv.Atoi(match[1]) + right, _ := strconv.Atoi(match[2]) + ans += left * right + } + return ans +} + +func solve_part_two(data string) int { + pattern := `mul\((\d+),(\d+)\)|don't\(\)|do\(\)` + regex := regexp.MustCompile(pattern) + + // FindStringSubmatch returns the full match and all capture groups + matches := regex.FindAllStringSubmatch(data, -1) + + ans := 0 + enabled := true + + // Iterate over all matches + for _, match := range matches { + left, _ := strconv.Atoi(match[1]) + right, _ := strconv.Atoi(match[2]) + if match[0] == "don't()" { + enabled = false + } else if match[0] == "do()" { + enabled = true + } + if enabled { + ans += left * right + } + } + return ans +} + +func main() { + test := FileRead("../input/day03.test") + test_2 := FileRead("../input/day03_2.test") + prod := FileRead("../input/day03.prod") + // Define the regex pattern with capture groups + + fmt.Println("Part_1 test: ", solve_part_one(test)) + fmt.Println("Part_1 prod: ", solve_part_one(prod)) + fmt.Println("Part_2 test: ", solve_part_two(test_2)) + fmt.Println("Part_2 prod: ", solve_part_two(prod)) +} |
