Add part 2 (digit1 detection works)

This commit is contained in:
askiiart 2023-12-06 08:46:47 -06:00
parent 81d1139474
commit 826a91cc61
Signed by untrusted user who does not match committer: askiiart
GPG key ID: BC3800E55FB54D67
6 changed files with 85 additions and 0 deletions

7
day-1/example-input Executable file
View file

@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

1
day-1/input Normal file → Executable file
View file

@ -998,3 +998,4 @@ one269
29onecklhjcxvpbzfour3
35vksqxhbnxk
sixfdqttpskdnbksqxg9three6bqqpngfhz
yriferiufjuifirtjhgrifjearifjesix

0
day-1/readme.md → day-1/part-1/readme.md Normal file → Executable file
View file

60
day-1/part-2/part-2.py Executable file
View file

@ -0,0 +1,60 @@
#!/usr/bin/env python3
DEBUG = False
num_text = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
#num_text = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
with open('day-1/input', 'rt') as f:
numbers = []
for line in f:
# just removes the newline to make printing work a bit better
line = line.rstrip()
digit1 = -1
# go through each line, start at the beginning, and keep going until it either matches a digit or it spelled out
# can probably be made more efficient
for i in range(0, len(line)):
if line[i].isdigit():
digit1 = int(line[i])
else:
# spelled out detection
for num in num_text:
# to make sure it doesn't go over the end
# fancy if thing needed so it doesn't go way over the end
end = i + len(num) if i + len(num) < len(line) else len(line)
if line[i:end] in num_text:
digit1 = num_text.index(line[i:end])
if digit1 != -1:
break
if digit1 != -1:
break
if DEBUG:
print('digit 1 debug:', line, digit1)
# TODO: digit 2, basically the same thing in reverse
digit2 = -1
'''
for char in line:
if str.isdigit(char):
digit1 = char
break
for i in range(len(line) - 2, -1, -1):
if str.isdigit(line[i]):
digit2 = line[i]
break
'''
# append if nums found, otherwise print error
numbers.append(int(str(digit1) + str(digit2))) if digit1 != -1 and digit2 != -1 else print(line, 'failed:', digit1, digit2, end='\n\n')
total = 0
for num in numbers:
total += num
print(total)

17
day-1/part-2/readme.md Executable file
View file

@ -0,0 +1,17 @@
# Day 1 - Part 2
Your calculation isn't quite right. It looks like some of the digits are actually **spelled out with letters**: one, two, three, four, five, six, seven, eight, and nine also count as valid "digits".
Equipped with this new information, you now need to find the real first and last digit on each line. For example:
```txt
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
```
In this example, the calibration values are `29`, `83`, `13`, `24`, `42`, `14`, and `76`. Adding these together produces 281.