Working d5p1, but I don't know what my code does

This commit is contained in:
Davide Oddone 2023-12-06 20:00:08 +01:00
parent 96dfe53951
commit 77f0c659d3

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
// "strings" // "strings"
"bufio" "bufio"
"math"
"os" "os"
"strconv" "strconv"
"regexp" "regexp"
@ -24,7 +25,6 @@ func GetMaps(scanner *bufio.Scanner, re *regexp.Regexp) [][]int {
// Scan until there is an empty line // Scan until there is an empty line
var tempNums int = 0 var tempNums int = 0
tempArray := make([][]int, 0) tempArray := make([][]int, 0)
PrintAndWait(tempArray)
for i := 0; scanner.Scan() && scanner.Text() != ""; i++ { for i := 0; scanner.Scan() && scanner.Text() != ""; i++ {
tempString := re.FindAllString(scanner.Text(), -1) tempString := re.FindAllString(scanner.Text(), -1)
temp := make([]int, 0) temp := make([]int, 0)
@ -33,15 +33,29 @@ func GetMaps(scanner *bufio.Scanner, re *regexp.Regexp) [][]int {
temp = append(temp, tempNums) temp = append(temp, tempNums)
} }
tempArray = append(tempArray, temp) tempArray = append(tempArray, temp)
PrintAndWait(tempArray)
} }
// Prepare for next line // Prepare for next line
scanner.Scan() scanner.Scan()
return tempArray return tempArray
} }
func NextResource(previous []int, resource [][]int) []int {
tempRes := make([]int, 0)
for i := range previous {
for j := range resource {
if previous[i] >= resource[j][1] &&
previous[i] <= (resource[j][1] + resource[j][2] - 1) {
tempRes = append(tempRes, previous[i] + (resource[j][0] - resource[j][1]))
}
}
if len(tempRes) == i {
tempRes = append(tempRes, previous[i])
}
}
return tempRes
}
func main () { func main () {
file, err := os.Open("./inputs/day05_test_input") file, err := os.Open("./inputs/day05_input")
check(err) check(err)
defer file.Close() defer file.Close()
@ -72,4 +86,32 @@ func main () {
temperatures = GetMaps(scanner, renum) temperatures = GetMaps(scanner, renum)
humidities = GetMaps(scanner, renum) humidities = GetMaps(scanner, renum)
locations = GetMaps(scanner, renum) locations = GetMaps(scanner, renum)
// [0] is dest, [1] is source, [2] is range
tempRes := make([]int, 0)
for i := range seeds {
for j := range soils {
if seeds[i] >= soils[j][1] &&
seeds[i] <= (soils[j][1] + soils[j][2] - 1) {
tempRes = append(tempRes, (seeds[i] + (soils[j][0] - soils[j][1])))
}
}
if len(tempRes) == i {
tempRes = append(tempRes, seeds[i])
}
}
tempRes = NextResource(tempRes, fertilizers)
tempRes = NextResource(tempRes, waters)
tempRes = NextResource(tempRes, lights)
tempRes = NextResource(tempRes, temperatures)
tempRes = NextResource(tempRes, humidities)
tempRes = NextResource(tempRes, locations)
minimum := math.MaxInt
for i := range tempRes {
if tempRes[i] < minimum {
minimum = tempRes[i]
}
}
PrintAndWait(minimum)
} }