Skip to main content

w_yw blog

Day1-Trebuchet

Table of Contents

My solution and thoughts on Day 1 puzzle of Advent of Code 2023

## Part One

# Puzzle

The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.

For example:

1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

In this example, the calibration values of these four lines are 123815, and 77. Adding these together produces _142_.

Consider your entire calibration document. What is the sum of all of the calibration values?

# File structure

command: tree

├── example.txt
├── go.mod
├── input1.txt
└── main.go

# Solution - Functions

├── main
├── extractNumbers
├── sumSlice
└── in main.go

## main

readFile - > split file ("\n") - > loop lines -> get number slices -> sumSlice -> print

func main(){
	file,err := os.ReadFile("txt")
	if err!=nil{
		return
	}
	
var numbers []int
// you can use string() to transfer byte[] to string
lines := strings.Split(string(file),"\n")
for _,line := range lines{
	// notice, the numbers will only have one slice
	numbers = append(numbers,extractNumbers(line)...)
}
sum := sumSlice(numbers)
fmt.Println(sum)
}

## extractNumbers

take each line as input and output a slice of int

func extractNumbers(line string) []int{
var s []string
var str string
var numbers []int

// loop line and extract numbers into slice
for i, char := range line{
	if char>= '0' && char <= '9'{
		str += string(char) // char here is integer
	}
	if i ==len(line)-1{
		s = append(s,str) 
		// we only add the final result to the slice
	}
}

// get the first and the last digit from the slice
var value string
for _,v := range s{
	for i, str := range v{ // loop in v
		if i == 0 || i == len(v)-1{
			value += string(str)
			if i == 0 && i ==len(v)-1{ 
			// if we only have one digit
			value += string(str) // we add it once again
			}
		}
		// convert string to number
		num,_ := strconv.Atoi(value) 
		// add nums to numbers
		numbers = append(numbers,num)
	}
}

return numbers
}

## sumSlice

get sum from looping the numbers slice

func sumSlice(numbers []int) int{
sum := 0
for _,num := range numbers{
	sum += num
}
return sum
}

# Notice

num := extractNumbers(line)  
// this will throw error:
// cannot use num (variable of type []int) as int value in argument to append
numbers = append(numbers, num) 
// use this
numbers = append(numbers, num...) 

## a way to deal with ASCII

if char >= '0' && char <= '9' {  
	// if you add just char
	// you will get ASCII, like 1 is 49
	// so char - '0' will be the actual difference
    numbers = append(numbers, int(char-'0'))
}

## alternative way to open file

This way is too verbose.

os.OpenFile("...")
alternative way to scan file  
scanner := bufio.NewScanner(strings.NewReader(string(file)))  
for scanner.Scan() {  
 line := scanner.Text()  
 numbers := extractNumbers(line)  
 fmt.Println(numbers)  
}