Skip to content

Commit

Permalink
feat: Implement part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
obalunenko committed Dec 1, 2023
1 parent e5ee4f3 commit a845429
Showing 1 changed file with 64 additions and 2 deletions.
66 changes: 64 additions & 2 deletions internal/puzzles/solutions/2023/day01/solution.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
package day01

import (
"bufio"
"fmt"
"io"
"strconv"
"unicode"

"github.com/obalunenko/advent-of-code/internal/puzzles"
)
Expand All @@ -21,8 +25,66 @@ func (s solution) Day() string {
return puzzles.Day01.String()
}

func (s solution) Part1(_ io.Reader) (string, error) {
return "", puzzles.ErrNotImplemented
func (s solution) Part1(input io.Reader) (string, error) {
scanner := bufio.NewScanner(input)

var values []int

for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}

first, last := -1, -1

for _, c := range line {
if !unicode.IsDigit(c) {
continue
}

if first == -1 {
d, err := strconv.Atoi(string(c))
if err != nil {
return "", fmt.Errorf("failed to convert %s to int: %w", string(c), err)
}

first = d
}

if first != -1 {
d, err := strconv.Atoi(string(c))
if err != nil {
return "", fmt.Errorf("failed to convert %s to int: %w", string(c), err)
}

last = d
}
}

if last == -1 {
last = first
}

value, err := strconv.Atoi(strconv.Itoa(first) + strconv.Itoa(last))
if err != nil {
return "", fmt.Errorf("failed to convert %d%d to int: %w", first, last, err)
}

values = append(values, value)
}

if err := scanner.Err(); err != nil {
return "", fmt.Errorf("reading input: %w", err)
}

var sum int

for _, v := range values {
sum += v
}

return strconv.Itoa(sum), nil
}

func (s solution) Part2(_ io.Reader) (string, error) {
Expand Down

0 comments on commit a845429

Please sign in to comment.