diff --git a/puzzles/solutions/2023/d01/p1.py b/puzzles/solutions/2023/d01/p1.py new file mode 100644 index 00000000..a8ad35a5 --- /dev/null +++ b/puzzles/solutions/2023/d01/p1.py @@ -0,0 +1,23 @@ +import re +import sys + + +def calculate_calibration_values_sum(input_text: str) -> int: + calibration_values_sum = 0 + for line in input_text.splitlines(): + numbers = re.findall(r"\d", line) + calibration_value = int(numbers[0]) * 10 + int(numbers[-1]) + calibration_values_sum += calibration_value + return calibration_values_sum + + +def get_answer(input_text: str) -> int: + """Return the calibrations values sum.""" + return calculate_calibration_values_sum(input_text) + + +if __name__ == "__main__": + try: + print(get_answer(sys.argv[1])) + except IndexError: + pass # Don't crash if no input was passed through command line arguments. diff --git a/puzzles/solutions/2023/d01/p2.py b/puzzles/solutions/2023/d01/p2.py new file mode 100644 index 00000000..38717f3f --- /dev/null +++ b/puzzles/solutions/2023/d01/p2.py @@ -0,0 +1,37 @@ +import sys + +import p1 + + +DIGITS_NAMES_TO_NUMBERS = dict( + zip( + ("one", "two", "three", "four", "five", "six", "seven", "eight", "nine"), + (map(str, range(1, 10))), + ) +) + + +def _convert_digits_names_to_numbers(input_text: str) -> str: + new_text = "" + for line in input_text.splitlines(): + new_line = line[0] + for i in range(1, len(line)): + new_line += line[i] + for digit_name in DIGITS_NAMES_TO_NUMBERS: + if line.endswith(digit_name, 0, i + 1): + new_line += DIGITS_NAMES_TO_NUMBERS[digit_name] + new_text += new_line + "\n" + return new_text + + +def get_answer(input_text: str): + """Return the calibrations values sum where digits names are replaced with numbers.""" + input_text = _convert_digits_names_to_numbers(input_text) + return p1.calculate_calibration_values_sum(input_text) + + +if __name__ == "__main__": + try: + print(get_answer(sys.argv[1])) + except IndexError: + pass # Don't crash if no input was passed through command line arguments.