diff --git a/05/05_refactored.py b/05/05_refactored.py new file mode 100644 index 0000000..565f697 --- /dev/null +++ b/05/05_refactored.py @@ -0,0 +1,31 @@ +def read_file(): + with open("input.txt","r") as f: + return f.read().split('\n') + +def id(seat): + """ + Translate to binary. + """ + return int(seat.translate(str.maketrans('FBLR', '0101')), 2) + +def part1(seats): + """ + Find the highest seat ID. + """ + ids = sorted(map(id, seats)) + return max(ids) + +def part2(seats): + """ + Find your seat ID, which is missing. + """ + ids = sorted(map(id, seats)) + return sum( range(min(ids), max(ids)+1) ) - sum(ids) + +def main(): + seats = read_file() + print(f'{part1(seats)=}') + print(f'{part2(seats)=}') + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/05/05_translate.py b/05/05_translate.py new file mode 100644 index 0000000..d382367 --- /dev/null +++ b/05/05_translate.py @@ -0,0 +1,25 @@ +""" +Turns out int() accepts different bases than 10. +We can also translate a string using translate() and a table, + or maketrans(). #TIL +""" + +with open("input.txt", "r") as f: + seats = f.read().split('\n') + +def id(code): + trans = str.maketrans('FBLR', '0101') + return int(code.translate(trans), 2) # it's literally just binary lmao -- x8 just means x1000 so shift 3 places, and there are 3 digits in the colpart + +ids = [id(seat) for seat in seats] +print(f"Part 1: {max(ids)}") # i forgot that max() existed whoops + +""" +Also, instead of iterating over the entire list of IDs, + we can find the missing seat by simply summing them. +The missing seat will be excluded from the total. +""" + +expected_total = sum( range(min(ids), max(ids)+1) ) # some seats are missing +actual_total = sum(ids) +print(f"Part 2: {expected_total - actual_total}") \ No newline at end of file