瀏覽代碼

Day 2 solutions in Python

master
Noëlle Anthony 6 年之前
父節點
當前提交
3c886c76ee
共有 2 個檔案被更改,包括 73 行新增0 行删除
  1. 41
    0
      02a.py
  2. 32
    0
      02b.py

+ 41
- 0
02a.py 查看文件

@@ -0,0 +1,41 @@
""" Advent of Code 2018

December 02, puzzle 1
"""

def main(lines):
""" For each line, count characters.

If any character appears exactly twice, increment x2.
If any character appears exactly three times, increment x3.
Ignore any doubles or triples past the first set.
At the end, multiply x2 by x3 to get the checksum.
"""
x2, x3 = 0, 0
for line in lines:
chars = {}
gota2, gota3 = False, False
for char in line:
if char in chars.keys():
chars[char] += 1
else:
chars[char] = 1
for k,v in chars.items():
if v == 2 and not gota2:
x2 += 1
gota2 = True
if v == 3 and not gota3:
x3 += 1
gota3 = True
if gota2 and gota3:
break
print("Totals: x2 {}, x3 {}".format(x2, x3))
print("Checksum: {}".format(x2 * x3))


if __name__ == "__main__":
lines = []
with open("02in.txt","r") as f:
for line in f:
lines.append(line.strip())
main(lines)

+ 32
- 0
02b.py 查看文件

@@ -0,0 +1,32 @@
""" Advent of Code 2018

December 02, puzzle 2
"""

def main(lines):
""" For each line, check to see if another line varies by only one character.

There's an easy but expensive way to do this. I'll start with that
and see if I can refine it later.
"""
for i, line in enumerate(lines):
if i + 1 != len(lines):
for word in lines[(i+1):]:
diffs = 0
idx = 0
for j in range(len(line)):
if line[j] != word[j]:
diffs += 1
idx = j
if diffs == 1:
print("Found a match: {} and {}".format(line, word))
print("Matched value: {}".format("".join([word[:idx],word[(idx+1):]])))
return

if __name__ == "__main__":
lines = []
with open("02in.txt","r") as f:
for line in f:
lines.append(line.strip())
main(lines)

Loading…
取消
儲存