Advertisement
FubFubFub

Day 1

Dec 4th, 2022
854
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 2.00 KB | Source Code | 0 0
  1. % This is our database with facts.
  2. snack(elf1, 1000).
  3. snack(elf1, 2000).
  4. snack(elf1, 3000).
  5.  
  6. snack(elf2, 4000).
  7.  
  8. snack(elf3, 5000).
  9. snack(elf3, 6000).
  10.  
  11. snack(elf4, 7000).
  12. snack(elf4, 8000).
  13. snack(elf4, 9000).
  14.  
  15. snack(elf5, 10000).
  16.  
  17. % An elf is in the expedition if it carries at least one snack.
  18. elf_in_expedition(Elf) :- snack(Elf, _).
  19.  
  20. % The list of elves is the set of elves in the expedition.
  21. elflist(ElfList) :- setof(Elf, elf_in_expedition(Elf), ElfList).
  22.  
  23. % To find the total number of calories an elf is carrying, make a list of the calories of all the snacks the elf is carrying, and calculate the sum of that list.
  24. total_calories(Elf, TotalCalories) :- findall(Calories, snack(Elf, Calories), CalorieList), sum_list(CalorieList, TotalCalories).
  25.  
  26. % max_calories/2 returns the elf who is carrying the most calories and how much calories it is carrying. To do so, it first constructs the list of elves with snacks and calls max_calories/3.
  27. max_calories(Elf, MaxCalories) :- elflist(ElfList), max_calories(Elf, MaxCalories, ElfList).
  28.  
  29. % If there are no elves in the list, then the total number of calories is 0 and there is 'no elf'.
  30. max_calories(no_elf, 0, []).
  31. % The elf at the head of the list is the elf carrying the most calories if the total calories it is carrying is higher than the number of calories the elf with the highest number of calories in the rest of the list is carrying.
  32. max_calories(Elf, ElfCalories, [Elf|RestElves]) :- total_calories(Elf, ElfCalories), max_calories(_, RestMaxCalories, RestElves), ElfCalories > RestMaxCalories.
  33. % If the number of calories the elf at the head of the list is carrying, is lower (or equal) to the number of calories the elf with the highest number of calories in the rest of the list is carrying, then that elf is the elf with the highest number of calories in this list.
  34. max_calories(RestMaxElf, RestMaxCalories, [Elf|RestElves]) :- total_calories(Elf, ElfCalories), max_calories(RestMaxElf, RestMaxCalories, RestElves), ElfCalories =< RestMaxCalories.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement