Created
December 7, 2022 06:27
-
-
Save galElmalah/3830293074bad10cde7d7b949e87f0a5 to your computer and use it in GitHub Desktop.
Advent of Code 2022 solution in Go
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" | |
"os" | |
"strings" | |
) | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} | |
func main() { | |
fmt.Println("Part 1") | |
fmt.Println(pt1()) | |
fmt.Println("Part 2") | |
fmt.Println(pt2()) | |
} | |
func pt1() int { | |
groups := parse() | |
sum := 0 | |
for _, group := range groups { | |
s1 := group[0] | |
s2 := group[1] | |
for k, _ := range s1 { | |
if s2[k] { | |
sum += calcPriority(k) | |
} | |
} | |
} | |
return sum | |
} | |
func pt2() int { | |
groups := parse2() | |
sum := 0 | |
for _, group := range groups { | |
s1 := group[0] | |
s2 := group[1] | |
s3 := group[2] | |
for k, _ := range s1 { | |
if s2[k] && s3[k] { | |
sum += calcPriority(k) | |
} | |
} | |
} | |
return sum | |
} | |
func makeSet(chars string) map[rune]bool { | |
set := map[rune]bool{} | |
for _, c := range chars { | |
set[c] = true | |
} | |
return set | |
} | |
func parse() [][]map[rune]bool { | |
data, _ := os.ReadFile("./input.txt") | |
lines := strings.Split(string(data), "\n") | |
rucksacks := [][]map[rune]bool{} | |
for _, line := range lines { | |
c1 := makeSet(line[len(line)/2:]) | |
c2 := makeSet(line[:len(line)/2]) | |
w := []map[rune]bool{c1, c2} | |
rucksacks = append(rucksacks, w) | |
} | |
return rucksacks | |
} | |
func parse2() [][]map[rune]bool { | |
data, _ := os.ReadFile("./input.txt") | |
rows := strings.Split(string(data), "\n") | |
groups := chunkInto(rows, 3) | |
rucksacks := [][]map[rune]bool{} | |
for _, chunk := range groups { | |
w := []map[rune]bool{} | |
for _, c := range chunk { | |
w = append(w, makeSet(c)) | |
} | |
rucksacks = append(rucksacks, w) | |
} | |
return rucksacks | |
} | |
func calcPriority(c rune) int { | |
if c >= 'a' && c <= 'z' { | |
return int(c) - 'a' + 1 | |
} else { | |
return int(c) - 'A' + 27 | |
} | |
} | |
func chunkInto(s []string, size int) [][]string { | |
results := [][]string{} | |
for i := 0; i < len(s); i += size { | |
results = append(results, s[i:i+size]) | |
} | |
return results | |
} | |
func sum(arr []int) int { | |
res := 0 | |
for _, num := range arr { | |
res += num | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment