Advertisement
FubFubFub

Day 3

Dec 3rd, 2022
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.84 KB | Source Code | 0 0
  1. % Our backpacks
  2.  
  3. backpack('vJrwpWtwJgWrhcsFMMfFFhFp').
  4. backpack('jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL').
  5. backpack('PmmdzqPrVvPwwTWBwg').
  6. backpack('wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn').
  7. backpack('ttgJtRGJQctTZtZT').
  8. backpack('CrZsJsPPZsGzwwsLwLmpwMDw').
  9.  
  10. % Split a backpacks into two lists of equal length
  11. sections(Backpack, SectionOne, SectionTwo) :- atom_length(Backpack, BackpackSize), Length is BackpackSize // 2, sub_atom(Backpack, 0, Length, Length, SectionOneChars), sub_atom(Backpack, Length, Length, _, SectionTwoChars), atom_chars(SectionOneChars, SectionOne), atom_chars(SectionTwoChars, SectionTwo).
  12.  
  13. % Check for items that occur in both lists
  14. common_items(SectionOne, SectionTwo, Common) :- setof(X, member(X, SectionOne), OneUnique), setof(Y, (member(Y, OneUnique), memberchk(Y, SectionTwo)), Common).
  15.  
  16. % Find all common items on a backpack. Result is a list of lists
  17. all_common(CommonListOfLists) :- findall(Common, (backpack(Backpack), sections(Backpack, SectionOne, SectionTwo), common_items(SectionOne, SectionTwo, Common)), CommonListOfLists).
  18.  
  19. % Find the values in a list of lists
  20. % Empty list has no values
  21. find_values([], 0).
  22. find_values([CommonList|RestListOfLists], SumValue) :- find_item_values(CommonList, ItemValues), find_values(RestListOfLists, RestSum), SumValue is ItemValues + RestSum.
  23.  
  24. % Find values in a list
  25. find_item_values([], 0).
  26. find_item_values([Item|Rest], SumValue) :- item_value(Item, ItemValue), find_item_values(Rest, RestSum), SumValue is ItemValue + RestSum.
  27.  
  28. % Determine the value of a single item
  29. item_value(Item, ItemValue) :- name(Item, AsciiValue), AsciiValue < 97, ItemValue is AsciiValue - 38.
  30. item_value(Item, ItemValue) :- name(Item, AsciiValue), AsciiValue > 96, ItemValue is AsciiValue - 96.
  31.  
  32. % Solve the puzzle
  33. solve(SumValue) :- all_common(CommonListOfLists), find_values(CommonListOfLists, SumValue).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement