Skip to content

Instantly share code, notes, and snippets.

@IsaiasSantana
Created December 6, 2023 19:27
Show Gist options
  • Select an option

  • Save IsaiasSantana/5ec32e31b3bf0a423bb79255ae28bc0f to your computer and use it in GitHub Desktop.

Select an option

Save IsaiasSantana/5ec32e31b3bf0a423bb79255ae28bc0f to your computer and use it in GitHub Desktop.
Advent of code 2023, day 1
package main
import (
"bufio"
"log"
"os"
"regexp"
"strconv"
"unicode/utf8"
)
func StringToInt(str string) (int, error) {
number, error := strconv.Atoi(str)
if error != nil {
return 0, error
}
return number, nil
}
func main() {
onlyDigitsRegex := regexp.MustCompile("[0-9]+")
result := 0
input, error := os.Open("input.txt")
if error != nil {
log.Fatal(error)
input.Close()
return
}
scanner := bufio.NewScanner(input)
for scanner.Scan() {
line := scanner.Text()
onlyNumbers := onlyDigitsRegex.FindAllString(line, -1)
firstDigit := string(onlyNumbers[0][0])
lastString := onlyNumbers[len(onlyNumbers)-1]
lastDigit := string(lastString[utf8.RuneCountInString(lastString)-1])
number, _ := StringToInt(firstDigit + lastDigit)
result += number
}
input.Close()
println("The result is ", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment