From c17546495d02904e85080f79b0f973a3cf5144fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luna=20=C5=9Awi=C4=85tek?= Date: Tue, 19 Dec 2023 03:01:21 +0100 Subject: [PATCH] day 2 part 1 --- day2/day2.go | 101 +++++++++++++++++++++++++++++++++++++++++++++++ day2/example.txt | 5 +++ go.work | 1 + 3 files changed, 107 insertions(+) create mode 100644 day2/day2.go create mode 100644 day2/example.txt create mode 100644 go.work diff --git a/day2/day2.go b/day2/day2.go new file mode 100644 index 0000000..f450db4 --- /dev/null +++ b/day2/day2.go @@ -0,0 +1,101 @@ +package main + +import ( + "fmt" + "io" + "os" + "regexp" + "strconv" + "strings" +) + +type Limitations struct { + red int + blue int + green int +} + +type Draw struct { + red int + blue int + green int +} + +type Game struct { + id int + draws []Draw + possible bool +} + +func readInput() string { + stdin, err := io.ReadAll(os.Stdin) + + if err != nil { + panic(err) + } + str := string(stdin) + return str +} + +func getColors(input string, color string) string { + rg := regexp.MustCompile(`[0-9]+ ` + regexp.QuoteMeta(color)) + return rg.FindString(input) +} + +func parseGameLine(line string, limits Limitations) Game { + splitted := strings.Split(line, ":") + draws_splitted := strings.Split(splitted[1], ";") + game_prefix := splitted[0] + + id, _ := strconv.Atoi(strings.Split(game_prefix, " ")[1]) + draws := []Draw{} + possible := true + for _, v := range draws_splitted { + draw := Draw{} + draw.red, _ = strconv.Atoi(strings.Split(getColors(v, "red"), " ")[0]) + draw.green, _ = strconv.Atoi(strings.Split(getColors(v, "green"), " ")[0]) + draw.blue, _ = strconv.Atoi(strings.Split(getColors(v, "blue"), " ")[0]) + if (draw.red > limits.red) || (draw.green > limits.green) || (draw.blue > limits.blue) { + possible = false + } + draws = append(draws, draw) + } + + game := Game{ + id: id, + draws: draws, + possible: possible, + } + + // fmt.Println(game) + return game +} + +func part1(lines []string) { + limits := Limitations{ + red: 12, + green: 13, + blue: 14, + } + var games []Game + sum_ids := 0 + for _, l := range lines { + if len(l) == 0 { + continue + } + game := parseGameLine(l, limits) + if game.possible { + games = append(games, game) + sum_ids += game.id + } + } + + fmt.Println(sum_ids) + +} + +func main() { + input := readInput() + lines := strings.Split(input, "\n") + part1(lines) +} diff --git a/day2/example.txt b/day2/example.txt new file mode 100644 index 0000000..295c36d --- /dev/null +++ b/day2/example.txt @@ -0,0 +1,5 @@ +Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green +Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue +Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red +Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red +Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green diff --git a/go.work b/go.work new file mode 100644 index 0000000..b777406 --- /dev/null +++ b/go.work @@ -0,0 +1 @@ +go 1.21.5