From 2d9dc1b236e84c65d51c66b765f049c4183fa50b Mon Sep 17 00:00:00 2001 From: Elias Kohout Date: Sat, 7 Dec 2024 00:47:35 +0100 Subject: [PATCH] performance improvement on part 2 of day 6, but still not a correct result --- day6/data.txt | 1 - day6/loop_guard.go | 50 ++++++++++++++++------------------------------ 2 files changed, 17 insertions(+), 34 deletions(-) diff --git a/day6/data.txt b/day6/data.txt index 6aa3008..7ae77b7 100644 --- a/day6/data.txt +++ b/day6/data.txt @@ -128,4 +128,3 @@ ...........................#..............#.....#............#.....................#........#....#.......................#........ ........#..##................#.....#.#..............#..............................#........................#.........#........... .........................................................#...........................##..........#........#.##.................... - diff --git a/day6/loop_guard.go b/day6/loop_guard.go index 8da1f3e..9133916 100644 --- a/day6/loop_guard.go +++ b/day6/loop_guard.go @@ -5,7 +5,10 @@ import ( "fmt" "strings" ) + + // type definitions + type Direction int const ( Up Direction = iota + 1 @@ -26,8 +29,8 @@ func new_state(text string) *state { field := make([][]rune, len(lines)) guard := [2]int{-1,-1} - for y := range lines { - field[y] = []rune(lines[y]) + for y, line := range lines { + field[y] = []rune(line) for x, r := range field[y] { if r == '^' { @@ -41,24 +44,16 @@ func new_state(text string) *state { return &s } -func (s *state) equals(other *state) bool { - return s.guard_x == other.guard_x && s.guard_y == other.guard_y && s.direction == other.direction -} // general util + func check(e error) { if e != nil { panic(e) } } -func add_non_duplicate(slice []*state, elem *state) []*state { - for _, e := range slice { - if e.equals(elem) { return slice } - } - return append(slice, elem) -} - // simulation functions + func iter(s *state) *state { new_guard_x := s.guard_x new_guard_y := s.guard_y @@ -109,35 +104,24 @@ func iter(s *state) *state { } func will_loop(s *state) bool { - distinct_states := make([]*state, 0, 130 * 130 * 4) + counter := 0 // while guard is within the field - for s.guard_x >= 0 { - // store copy of the current state - old_len := len(distinct_states) - cpy := state{ - field: s.field, - guard_x: s.guard_x, - guard_y: s.guard_y, - direction: s.direction, - } - distinct_states = add_non_duplicate(distinct_states, &cpy) - - // if duplicate state found, loop found - if len(distinct_states) == old_len { - return true - } - + for s.guard_x >= 0 && counter < 10000 { // iterate s = iter(s) + counter++ + } + if s.guard_x < 0 { + // the guard is no longer in the field, not a loop + return false + } else { + return true } - // the guard is no longer in the field, not a loop - return false } - func print(s *state) { out := make([]string, 0, len(*s.field)) - for _, line := range *s.field { + for line := range *s.field { out = append(out, string(line)) } fmt.Println(strings.Join(out, "\n"))