I Tried To Add Booleans, But It Gave The Wrong Answer. Advent Of Code 2022, Day 4

Question:

So what I had to do for this challenge was parse through a text file, looks like this

1-6,7-9
10-11,11-11

And I had to check if one range contains each other. In the above, in the second pair, range 2 is fully contained in range 1. I had to check for stuff like that.
So I built this code.

with open("input4.txt") as f:
    text_array = f.read().split("n")
    total = 0
    for i in text_array:
        parts = i.split(",")
        pair1 = parts[0].split("-")
        pair2 = parts[1].split("-")
        if (pair1[0] <= pair2[0] and pair1[1] >= pair2[1]) and (pair2[0] <= pair1[0] and pair2[1] >= pair1[1]):
          total += 1 

    print(total)

(Ignore the other print statements but the last one) And it gave me 596, which in the advent of code it says it is too high.

It gave me 596, and when put into the problem, it says it is too high. I am wondering if there are any cases that slid in or idk. I literally made custom input, and it gave the correct answer. Does anyone know where did I go wrong?

Asked By: Riyan Nayak

||

Answers:

Looks like the problem is in your "if".
maybe you can try this code

text_array = f.read().split("n")
total = 0
for i in text_array:
parts = i.split(",")
pair1 = parts[0].split("-")
pair2 = parts[1].split("-")
if (pair1[0] <= pair2[0] and pair1[1] >= pair2[1]) or (pair2[0] <= pair1[0] and pair2[1] >= pair1[1]):
total += 1
Answered By: Ahmad Mihdan Advani

Try this.

Not sure but comparing strings may lead to issues when numbers are made of several digits.

pair1 = [int(x) for x in  parts[0].split("-")]
pair2 = [int(x) for x in  parts[1].split("-")]
Answered By: 0x0fba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.