Created
December 11, 2023 02:54
-
-
Save phrozen/61778cd5e0b2e14041ef1a27bf1a2616 to your computer and use it in GitHub Desktop.
Advent of Code 2023 - Day 4
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 ( | |
"fmt" | |
"math" | |
"os" | |
"regexp" | |
"slices" | |
"strings" | |
) | |
func LoadLinesFromFile(src string) []string { | |
data, err := os.ReadFile("input.txt") | |
if err != nil { | |
panic(err) | |
} | |
return strings.Split(string(data), "\r\n") | |
} | |
func GetScratchNumbers(line string) ([]string, []string) { | |
re := regexp.MustCompile(`\d+`) | |
data := strings.Split(strings.Split(line, ":")[1], "|") | |
return re.FindAllString(data[0], -1), re.FindAllString(data[1], -1) | |
} | |
func PartOne(lines []string) int { | |
points := 0 | |
for _, line := range lines { | |
winners, ticket := GetScratchNumbers(line) | |
wins := -1 | |
for _, number := range ticket { | |
if slices.Contains(winners, number) { | |
wins++ | |
} | |
} | |
points += int(math.Pow(2, float64(wins))) | |
} | |
return points | |
} | |
func PartTwo(lines []string) int { | |
copies := make([]int, len(lines)) | |
total := 0 | |
for i, line := range lines { | |
copies[i]++ | |
winners, ticket := GetScratchNumbers(line) | |
wins := 0 | |
for _, number := range ticket { | |
if slices.Contains(winners, number) { | |
wins++ | |
copies[i+wins] += copies[i] | |
} | |
} | |
total += copies[i] | |
} | |
return total | |
} | |
func main() { | |
lines := LoadLinesFromFile("input.txt") | |
fmt.Println("PartOne:", PartOne(lines)) | |
fmt.Println("PartTwo:", PartTwo(lines)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment