diff --git a/02/02.go b/02/02.go index ff4a334..ec404ac 100644 --- a/02/02.go +++ b/02/02.go @@ -5,7 +5,6 @@ import ( "os" "strconv" "strings" - "slices" ) func SplitByLines(bytes []byte) []string { @@ -13,46 +12,100 @@ func SplitByLines(bytes []byte) []string { } func Less(a, b int) bool { - return ab + return a > b } -func P(f func (int, int) bool, a, b int) bool { - return f(a, b) && Abs(a-b)<=3 +func P(f func(int, int) bool, a, b int) bool { + return f(a, b) && Abs(a-b) <= 3 } func Abs(x int) int { - if x<0 { + if x < 0 { x = -x } return x } -func Safe1(l []int, j, e int) bool { +func Safe1(l []int) bool { + if l[0] == l[1] { + return false + } f := Less - if l[j-1]>l[j] { f = More } - for j l[1] { + f = More + } + j := 1 + for j < len(l) && P(f, l[j-1], l[j]) { j++ } - r := jl[1] { f = More } - c := 0 - j := 2 - for j= b { + cl++ + if il == -1 { + il = i + } + } + if a <= b { + cm++ + if im == -1 { + im = i + } + } + if Abs(a-b) > 3 { + cq++ + if iq == -1 { + iq = i + } } - j++ } - return c<2 + if cq == 0 && (cm == 0 || cl == 0) { + return true + } + if cq > 2 || cl > 2 && cm > 2 { + return false + } + if cq == 2 { + return Safe1(Skip(l, iq)) + } + if iq != -1 { + return Safe1(Skip(l, iq)) || Safe1(Skip(l, iq-1)) + } + if 0 < cl && cl <= 2 { + return Safe1(Skip(l, il)) || Safe1(Skip(l, il-1)) + } + if 0 < cm && cm <= 2 { + return Safe1(Skip(l, im)) || Safe1(Skip(l, im-1)) + } + return false +} +func Skip(l []int, i int) []int { + n := make([]int, len(l)-1) + k := 0 + for j, x := range l { + if j != i { + n[k] = x + k++ + } + } + return n } func main() { bytes, err := os.ReadFile("./input.txt") - if err != nil { panic(err) } + if err != nil { + panic(err) + } lines := SplitByLines(bytes) data := make([][]int, len(lines)) for i, l := range lines { @@ -66,24 +119,16 @@ func main() { } s := 0 for _, l := range data { - if Safe1(l, 1, len(l)) { s++ } + if Safe1(l) { + s++ + } } fmt.Println(s) s = 0 for _, l := range data { - t := make([]int, len(l)) - copy(t, l) - t = slices.Delete(t, 1, 2) - if Safe1(l, 1, len(l)) || - Safe1(l, 2, len(l)) || - Safe1(t, 1, len(t)) || - Safe1(l, 1, len(l)-1) { - s++ - } else if Safe2(l) { - fmt.Println(l) - s++ + if Safe2(l) { + s++ } } fmt.Println(s) - println(len(data)) }