Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Our backpacks
- backpack('vJrwpWtwJgWrhcsFMMfFFhFp').
- backpack('jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL').
- backpack('PmmdzqPrVvPwwTWBwg').
- backpack('wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn').
- backpack('ttgJtRGJQctTZtZT').
- backpack('CrZsJsPPZsGzwwsLwLmpwMDw').
- % Split a backpacks into two lists of equal length
- 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).
- % Check for items that occur in both lists
- common_items(SectionOne, SectionTwo, Common) :- setof(X, member(X, SectionOne), OneUnique), setof(Y, (member(Y, OneUnique), memberchk(Y, SectionTwo)), Common).
- % Find all common items on a backpack. Result is a list of lists
- all_common(CommonListOfLists) :- findall(Common, (backpack(Backpack), sections(Backpack, SectionOne, SectionTwo), common_items(SectionOne, SectionTwo, Common)), CommonListOfLists).
- % Find the values in a list of lists
- % Empty list has no values
- find_values([], 0).
- find_values([CommonList|RestListOfLists], SumValue) :- find_item_values(CommonList, ItemValues), find_values(RestListOfLists, RestSum), SumValue is ItemValues + RestSum.
- % Find values in a list
- find_item_values([], 0).
- find_item_values([Item|Rest], SumValue) :- item_value(Item, ItemValue), find_item_values(Rest, RestSum), SumValue is ItemValue + RestSum.
- % Determine the value of a single item
- item_value(Item, ItemValue) :- name(Item, AsciiValue), AsciiValue < 97, ItemValue is AsciiValue - 38.
- item_value(Item, ItemValue) :- name(Item, AsciiValue), AsciiValue > 96, ItemValue is AsciiValue - 96.
- % Solve the puzzle
- solve(SumValue) :- all_common(CommonListOfLists), find_values(CommonListOfLists, SumValue).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement