parent
0fc1e2b2a3
commit
25e076604e
@ -0,0 +1,18 @@
|
||||
# Day 4
|
||||
|
||||
## Instructions
|
||||
|
||||
From the root directory of the crate (where this README is) just execute:
|
||||
|
||||
```
|
||||
python day5.py
|
||||
```
|
||||
|
||||
The solution will be printed to the terminal output.
|
||||
|
||||
## Notes:
|
||||
|
||||
I had very little time so decided to just crank out a quick solution using Python.
|
||||
I was under a heavy time constraint so I ended up just implementing the brute force approach instead of designing a better algorithm.
|
||||
Hopefully I can do some more algorithmic design for future problems to get better time complexity, even though it doesn't really matter.
|
||||
|
@ -0,0 +1,77 @@
|
||||
# %%
|
||||
import itertools
|
||||
|
||||
|
||||
# %% Define functions
|
||||
def read_file(path):
|
||||
"""Read the example input file and return a tuple of rules and orderings"""
|
||||
rules = list()
|
||||
updates = list()
|
||||
with open(path, "r") as f:
|
||||
for line in f:
|
||||
if "|" in line:
|
||||
rules.append(line)
|
||||
elif not line.isspace():
|
||||
updates.append(line)
|
||||
return rules, updates
|
||||
|
||||
|
||||
def prepare_rules(rules):
|
||||
"""Prepare the rules for use by the analysis algorithm"""
|
||||
return set(rules)
|
||||
|
||||
|
||||
def process_updates(updates, rules):
|
||||
sum = 0
|
||||
for update in updates:
|
||||
# Brute force this because I started late
|
||||
nums = [int(val) for val in update.split(",")]
|
||||
correct = True
|
||||
for (i, num1), (j, num2) in itertools.product(enumerate(nums), enumerate(nums)):
|
||||
if i < j:
|
||||
bad_rule = f"{num2}|{num1}\n"
|
||||
if bad_rule in rules:
|
||||
correct = False
|
||||
break
|
||||
if correct:
|
||||
sum += nums[int(len(nums) / 2)]
|
||||
return sum
|
||||
|
||||
|
||||
def fix_bad_update(update, rules):
|
||||
sum = 0
|
||||
for update in updates:
|
||||
# Brute force this because I started late and don't have time to design a better algorithm
|
||||
nums = [int(val) for val in update.split(",")]
|
||||
fix_count = 0
|
||||
correct = False
|
||||
while correct == False:
|
||||
correct = True
|
||||
for (i, num1), (j, num2) in itertools.product(
|
||||
enumerate(nums), enumerate(nums)
|
||||
):
|
||||
if i < j:
|
||||
bad_rule = f"{num2}|{num1}\n"
|
||||
if bad_rule in rules:
|
||||
correct = False
|
||||
fix_count += 1
|
||||
nums[i] = num2
|
||||
nums[j] = num1
|
||||
break
|
||||
|
||||
if fix_count > 0:
|
||||
sum += nums[int(len(nums) / 2)]
|
||||
return sum
|
||||
|
||||
|
||||
# %% Execut
|
||||
|
||||
if __name__ == "__main__":
|
||||
rules, updates = read_file("./input.txt")
|
||||
rules = prepare_rules(rules)
|
||||
sum = process_updates(updates, rules)
|
||||
print(f"Part1 answer is {sum}")
|
||||
sum = fix_bad_update(updates, rules)
|
||||
print(f"Part2 answer is {sum}")
|
||||
|
||||
# %%
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue