diff --git a/day13/parse.go b/day13/parse.go index dfd848d..40f4f8b 100644 --- a/day13/parse.go +++ b/day13/parse.go @@ -9,7 +9,7 @@ import ( var schedule struct { Departure int - Lines []int + Lines map[int]int } func ParseFile(input string) { @@ -21,14 +21,15 @@ func ParseFile(input string) { // Store time schedule.Departure = time + schedule.Lines = make(map[int]int) - for _, row := range strings.Split(rows[1], ",") { + for offset, row := range strings.Split(rows[1], ",") { if row != "x" { // Convert bus number line, _ := strconv.Atoi(row) // Add to schedule - schedule.Lines = append(schedule.Lines, line) + schedule.Lines[offset] = line } } } diff --git a/day13/solve2.go b/day13/solve2.go index 17d298b..403173d 100644 --- a/day13/solve2.go +++ b/day13/solve2.go @@ -1,12 +1,51 @@ package day13 import ( - "fmt" "log" ) func Solve2() { - fmt.Println(len(schedule.Lines)) + // Storage if it's a valid run or not + isValidRun := false - log.Printf("2020-12-13.02: Answer: %d\n", len(schedule.Lines)) + i := 1 + for isValidRun == false { + // Calculate the departure time for this first run + departureTime := i * schedule.Lines[0] + + // Storage if it's a valid start or not + isValidStart := true + + // Go throgh the rest of the lines + for offset, line := range schedule.Lines { + // Ignore first column which has no offset which we base + // this brute force on anyways. + if offset == 0 { + continue + } + + // Calculate next departure time for this line + nextDeparture := departureTime/line*line + line + + // If this doesn't match the rules to follow the offsets + // to go a minute after previous bus, break the loop and + // set it as an invalid start. + if departureTime+offset != nextDeparture { + isValidStart = false + + break + } + } + + if isValidStart { + isValidRun = true + } + + i++ + } + + validRunId := i * schedule.Lines[0] + + log.Printf("2020-12-13.02: Answer: %d\n", validRunId) + log.Printf("2020-12-13.02: Answer: %d\n", validRunId-schedule.Lines[0]) }