6-1 complete

This commit is contained in:
DutchEllie 2021-12-08 10:25:03 +01:00
parent 4b38fa4b0d
commit 9bfd0cd8fc
1 changed files with 84 additions and 2 deletions

View File

@ -1,7 +1,89 @@
package main
import "fmt"
import (
"bufio"
"bytes"
"fmt"
"os"
"strconv"
)
func main() {
fmt.Printf("Yeet")
fishies, err := readInput("input")
if err != nil {
fmt.Printf("Error reading or something\n%s", err)
return
}
fishiesptr := &fishies
// Run for i days
for i := 0; i < 80; i++ {
newfishies, _ := nextDay(*fishiesptr)
fishiesptr = &newfishies
fmt.Printf("On day %d: there are %d fishies\n", i+1, len(newfishies))
}
}
// Read the fishies slice and returns the slice of new fishies
func nextDay(fishies []int) ([]int, error) {
// For every fish (integer) in the slice, decrement by 1 if >= 1, reset to 6 if it was 0
// Also, if the number was 0, add a new fish with counter 8 to a second slice
// After everything, append the slices and return the result
newfishies := make([]int, 0)
for i := 0; i < len(fishies); i++ {
if fishies[i] >= 1 {
fishies[i] -= 1
continue
}
if fishies[i] == 0 {
fishies[i] = 6
newfishies = append(newfishies, 8)
continue
}
}
fishies = append(fishies, newfishies...)
return fishies, nil
}
func readInput(inputfile string) ([]int, error) {
file, err := os.OpenFile(inputfile, 0, 0)
if err != nil {
return nil, err
}
defer file.Close()
splitfunc := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
nextIndex := bytes.IndexByte(data, ',')
if nextIndex > 0 {
// Returning the next position aka taking only the stuff up to nextIndex and slicing off everything else
buffer := data[:nextIndex]
// nextIndex plus 1 because index is at the comma, we want the next number
return nextIndex + 1, bytes.TrimSpace(buffer), nil
}
// If we are at the end of the buffer, then return the entire buffer, but only if there is data
if atEOF {
if len(data) > 0 {
return len(data), bytes.TrimSpace(data), nil
}
}
// https://github.com/kgrz/reading-files-in-go/blob/master/comma-separated-string.go
// For more info
return 0, nil, nil
}
scanner := bufio.NewScanner(file)
scanner.Split(splitfunc)
fishies := make([]int, 0)
for scanner.Scan() {
fish, err := strconv.Atoi(scanner.Text())
if err != nil {
fmt.Printf("Error converting string to integer\n")
return nil, err
}
fishies = append(fishies, fish)
}
return fishies, nil
}