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

Time:12-06

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?

CodePudding user response:

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("-")]

CodePudding user response:

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

CodePudding user response:

Maybe you could try this and compare with yours:


tot = 0

for line in open('04.in'):
    a, b, x, y = map(int, line.replace(",", "-").split("-")) # convert to integer! 
    if a <= x and b >= y or x <= a and y >= b:     # comp. the ranges
        tot  = 1

print(f' Part 1: {tot}')
  • Related