68 lines
1.3 KiB
Go
68 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
type Solver interface {
|
|
ParseInput(input []string)
|
|
SolvePart1() int
|
|
SolvePart2() int
|
|
}
|
|
|
|
func ReadInput(inputFileName string) ([]string, error) {
|
|
var input = make([]string, 0)
|
|
|
|
reader, err := os.Open(inputFileName)
|
|
if err != nil {
|
|
return input, fmt.Errorf("failed to open input file: %w", err)
|
|
}
|
|
|
|
scanner := bufio.NewScanner(reader)
|
|
for scanner.Scan() {
|
|
input = append(input, scanner.Text())
|
|
}
|
|
return input, nil
|
|
}
|
|
|
|
func GetInputFileName(dayNumber int, testMode bool) string {
|
|
var testString string
|
|
if testMode {
|
|
testString = "test"
|
|
} else {
|
|
testString = "prod"
|
|
}
|
|
|
|
return fmt.Sprintf("day%d/%s.in.txt", dayNumber, testString)
|
|
}
|
|
|
|
func DownloadInput(sessionCookie string, dayNumber int, inputFileName string) error {
|
|
req, err := http.NewRequest("GET", fmt.Sprintf("https://adventofcode.com/2022/day/%d/input", dayNumber), nil)
|
|
if err != nil {
|
|
log.Fatalf("couldn't create reques: %s", err)
|
|
}
|
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionCookie})
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
writer, err := os.Create(inputFileName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := io.Copy(writer, resp.Body); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|