Working out solutions for Advent of Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """ Advent of Code 2018
  2. December 02, puzzle 2
  3. """
  4. def main(lines):
  5. """ For each line, check to see if another line varies by only one character.
  6. There's an easy but expensive way to do this. I'll start with that
  7. and see if I can refine it later.
  8. """
  9. # Testing a new implementation (should be O(n log n))
  10. #
  11. # lines.sort()
  12. # for i, line in enumerate(lines):
  13. # if i + 1 != len(lines):
  14. # word = lines[i+1]
  15. # diffs = 0
  16. # idx = 0
  17. # for j in range(len(line)):
  18. # if line[j] != word[j]:
  19. # diffs += 1
  20. # idx = j
  21. # if diffs == 1:
  22. # print("Found a match: {} and {}".format(line, word))
  23. # print("Matched value: {}".format("".join([word[:idx],word[(idx+1):]])))
  24. # return
  25. # Original implementation kept for reference (O(n^2))
  26. #
  27. for i, line in enumerate(lines): # enumerate gives us an index and the value at that index
  28. if i + 1 != len(lines): # don't overflow the list
  29. for word in lines[(i+1):]: # only check lines further down the list
  30. diffs = 0 # track the number of differences between lines
  31. idx = 0 # track the index of the most recent difference
  32. for j in range(len(line)): # iterate over the length of a word (they're all the same length)
  33. if line[j] != word[j]: # if this character in the first word is different from the same character in the second
  34. diffs += 1 # increment the number of differences by 1
  35. idx = j # set the difference index equal to the current iteration index
  36. if diffs == 1: # if we only found one difference
  37. print("Found a match: {} and {}".format(line, word)) # print the matched words
  38. print("Matched value: {}".format("".join([word[:idx],word[(idx+1):]]))) # print the matching (NOT non-matching) letters
  39. return
  40. if __name__ == "__main__":
  41. lines = [] # an empty list for the lines in the input file
  42. with open("02in.txt","r") as f: # open the file. "with" means we don't have to close it
  43. for line in f: # iterate over the lines in the input file
  44. lines.append(line.strip()) # strip the newline character, then add it to the list
  45. main(lines) # and pass the list to our main function.