Skip to content

Commit 75caa39

Browse files
committed
Update day 1 with part 2
1 parent 4ad300c commit 75caa39

File tree

2 files changed

+48
-7
lines changed

2 files changed

+48
-7
lines changed

day01/output.txt

+8-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,8 @@
1-
Elf(id=53, total_cals=69289)
1+
./process.py items.txt 3
2+
3+
Top 3 elves:
4+
Elf(id=53, total_cals=69289)
5+
Elf(id=227, total_cals=68321)
6+
Elf(id=10, total_cals=68005)
7+
8+
Combined: Elf(id=[53, 227, 10], total_cals=205615)

day01/process.py

+40-6
Original file line numberDiff line numberDiff line change
@@ -91,23 +91,45 @@ def AddCals(self, cals):
9191
def __lt__(self, other):
9292
return self.total_cals < other.total_cals
9393

94+
def __add__(self, other):
95+
ids = self.id + [other.id] if isinstance(self.id, list) else [self.id, other.id]
96+
total_cals = self.total_cals + other.total_cals
97+
return Elf(ids, total_cals)
98+
99+
def __radd__(self, other):
100+
return self if other == 0 else self.__add__(other)
101+
102+
103+
class TopN:
104+
items = list()
105+
106+
def __init__(self, n_items, init_item):
107+
self.items = [init_item for i in range(n_items)]
108+
109+
def Consider(self, candidate):
110+
for i in range(len(self.items)):
111+
if self.items[i] < candidate:
112+
self.items.insert(i, candidate)
113+
self.items.pop()
114+
break
115+
94116

95117
def get_next_elf(elf) -> Elf:
96118
return Elf(id=elf.id + 1)
97119

98120

99-
def process_list(items) -> Elf:
121+
def process_list(items, n) -> Elf:
100122
elf = Elf(id=1)
101-
elf_with_most = Elf(id=0)
123+
top_n = TopN(n, Elf(id=0))
102124

103125
for item in items:
104126
if item.strip().isdigit():
105127
elf.AddCals(int(item))
106128
else:
107-
elf_with_most = max(elf, elf_with_most)
129+
top_n.Consider(elf)
108130
elf = get_next_elf(elf)
109131

110-
return elf_with_most
132+
return top_n
111133

112134

113135
def parse_args():
@@ -121,15 +143,27 @@ def parse_args():
121143
help="A file holding zero or more calorie lists. One calorie per line."
122144
"A blank lines terminate the given elf's list.",
123145
)
146+
parser.add_argument(
147+
"top_n",
148+
metavar="N",
149+
type=int,
150+
choices=range(1, 100),
151+
help="Return the combined calories held by the top N elves.",
152+
)
124153
return parser.parse_args()
125154

126155

127156
def main():
128157
args = parse_args()
129158

130159
with args.calories_file.open("r") as items:
131-
elf_with_most = process_list(items)
132-
print(elf_with_most)
160+
top_n = process_list(items, args.top_n)
161+
162+
print(f"Top {args.top_n} elves:")
163+
for elf in top_n.items:
164+
print(" ", elf)
165+
166+
print(f"\nCombined:", sum(top_n.items))
133167

134168
return 0
135169

0 commit comments

Comments
 (0)