Created
January 6, 2024 13:25
-
-
Save glitchcowboy/676464e3a2da67ea1a90ded11657988b to your computer and use it in GitHub Desktop.
AoC-Day3-regexified
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import re | |
def main(): | |
df = pd.read_csv("input.txt", index_col=False) | |
re_number = re.compile(r'\d') | |
re_spec_char = re.compile(r'[*&%\-/#&$@+=]') | |
re_spec_char_dot = re.compile(r'[*&%\-/#&$@+=.]') | |
df.columns = ['col1'] | |
# Split each character into a new column | |
df_split = pd.DataFrame(df['col1'].apply(list).tolist()) | |
symbols = set() | |
total_numbers = [] | |
for row in range(df_split.shape[0]): | |
for col in range(df_split.shape[1]): | |
this_cell = df_split.iloc[row, col] | |
symbols.add(this_cell) | |
if re.match(re_spec_char, this_cell): | |
spec_char_spot = this_cell | |
# see if there are any numbers around this spot | |
found_numbers_already = [] | |
for near_row in [-1, 0, 1]: | |
for near_col in [-1, 0, 1]: | |
near_row_int = row + near_row | |
near_col_int = col + near_col | |
nearby_numbers = [] | |
if re.match(re_number, df_split.iloc[near_row_int, near_col_int]): | |
# see if this number is the first spot of the number | |
if re.match(re_spec_char_dot, df_split.iloc[near_row_int, near_col_int - 1]): | |
begin_int_spot = near_col_int | |
elif re.match(re_number, df_split.iloc[near_row_int, near_col_int - 1]): | |
if re.match(re_spec_char_dot, df_split.iloc[near_row_int, near_col_int - 2]): | |
begin_int_spot = near_col_int - 1 | |
elif re.match(re_number, df_split.iloc[near_row_int, near_col_int - 2]): | |
begin_int_spot = near_col_int - 2 | |
# find the end int spot | |
if re.match(re_spec_char_dot, df_split.iloc[near_row_int, begin_int_spot + 1]): | |
end_int_spot = begin_int_spot | |
elif re.match(re_number,df_split.iloc[near_row_int, begin_int_spot + 1]): | |
if re.match(re_spec_char_dot, df_split.iloc[near_row_int, begin_int_spot + 2]): | |
end_int_spot = begin_int_spot + 1 | |
elif re.match(re_number,df_split.iloc[near_row_int, begin_int_spot + 2]): | |
end_int_spot = begin_int_spot + 2 | |
spot_start = begin_int_spot | |
end_spot = end_int_spot + 1 | |
nearby_number = [x for x in df_split.iloc[near_row_int, spot_start:end_spot]] | |
nearby_number = int(''.join(nearby_number)) | |
if (near_row_int, spot_start) not in found_numbers_already: | |
found_numbers_already += [(near_row_int, spot_start)] | |
total_numbers += [nearby_number] | |
if row == 1: | |
print(df_split.iloc[row, col], row, col, nearby_number, found_numbers_already, | |
total_numbers) | |
print(sum(total_numbers)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment