8000 feat: solution for scratchcards part 1 problem · christianotieno/adventofcode@c9fe8bf · GitHub
[go: up one dir, main page]

Skip to content

Commit c9fe8bf

Browse files
feat: solution for scratchcards part 1 problem
1 parent e0971da commit c9fe8bf

File tree

4 files changed

+298
-0
lines changed

4 files changed

+298
-0
lines changed

day4/scratchcards.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package day4
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"os"
7+
"strconv"
8+
"strings"
9+
)
10+
11+
func ScratchCards(filepath string) int {
12+
file, err := os.Open(filepath)
13+
if err != nil {
14+
_ = fmt.Errorf("error opening file: %v+", err)
15+
return 0
16+
}
17+
18+
defer func(file *os.File) {
19+
err := file.Close()
20+
if err != nil {
21+
_ = fmt.Errorf("error closing file %v+", err)
22+
}
23+
}(file)
24+
25+
scanner := bufio.NewScanner(file)
26+
totalPoints := 0
27+
28+
for scanner.Scan() {
29+
line := scanner.Text()
30+
parts := strings.Split(line, "|")
31+
if len(parts) != 2 {
32+
fmt.Printf("Invalid line format: %s\n", line)
33+
continue
34+
}
35+
36+
leftPart := strings.Split(parts[0], ":")
37+
38+
leftNumbers := extractNumbers(leftPart[1])
39+
rightNumbers := extractNumbers(parts[1])
40+
41+
points := calculatePoints(leftNumbers, rightNumbers)
42+
totalPoints += points
43+
}
44+
45+
fmt.Printf("Total Points: %d\n", totalPoints)
46+
return totalPoints
47+
}
48+
49+
func extractNumbers(s string) []int {
50+
numStr := strings.Fields(strings.TrimSpace(s))
51+
numbers := make([]int, len(numStr))
52+
53+
for i, str := range numStr {
54+
num, err := strconv.Atoi(str)
55+
if err != nil {
56+
fmt.Printf("Error converting %s to integer: %v\n", str, err)
57+
continue
58+
}
59+
numbers[i] = num
60+
}
61+
62+
return numbers
63+
}
64+
65+
func calculatePoints(leftNumbers, rightNumbers []int) int {
66+
points := 0
67+
matched := make(map[int]bool)
68+
69+
for _, num := range rightNumbers {
70+
if contains(leftNumbers, num) && !matched[num] {
71+
points++
72+
matched[num] = true
73+
}
74+
}
75+
76+
if points > 1 {
77+
points = 2 << (points - 2)
78+
}
79+
80+
return points
81+
}
82+
83+
func contains(numbers []int, target int) bool {
84+
for _, num := range numbers {
85+
if num == target {
86+
return true
87+
}
88+
}
89+
return false
90+
}

0 commit comments

Comments
 (0)
0